1//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// C Language Family Type Representation
12///
13/// This file defines the clang::Type interface and subclasses, used to
14/// represent types for languages in the C family.
15//
16//===----------------------------------------------------------------------===//
17
18#ifndef LLVM_CLANG_AST_TYPE_H
19#define LLVM_CLANG_AST_TYPE_H
20
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/TemplateName.h"
23#include "clang/Basic/AddressSpaces.h"
24#include "clang/Basic/AttrKinds.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/ExceptionSpecificationType.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/Visibility.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/APSInt.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/None.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/Twine.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/PointerLikeTypeTraits.h"
48#include "llvm/Support/type_traits.h"
49#include "llvm/Support/TrailingObjects.h"
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <cstring>
54#include <string>
55#include <type_traits>
56#include <utility>
57
58namespace clang {
59
60class ExtQuals;
61class QualType;
62class TagDecl;
63class Type;
64
65enum {
66 TypeAlignmentInBits = 4,
67 TypeAlignment = 1 << TypeAlignmentInBits
68};
69
70} // namespace clang
71
72namespace llvm {
73
74 template <typename T>
75 struct PointerLikeTypeTraits;
76 template<>
77 struct PointerLikeTypeTraits< ::clang::Type*> {
78 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
79
80 static inline ::clang::Type *getFromVoidPointer(void *P) {
81 return static_cast< ::clang::Type*>(P);
82 }
83
84 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
85 };
86
87 template<>
88 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
89 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
90
91 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
92 return static_cast< ::clang::ExtQuals*>(P);
93 }
94
95 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
96 };
97
98 template <>
99 struct isPodLike<clang::QualType> { static const bool value = true; };
100
101} // namespace llvm
102
103namespace clang {
104
105class ASTContext;
106template <typename> class CanQual;
107class CXXRecordDecl;
108class DeclContext;
109class EnumDecl;
110class Expr;
111class ExtQualsTypeCommonBase;
112class FunctionDecl;
113class IdentifierInfo;
114class NamedDecl;
115class ObjCInterfaceDecl;
116class ObjCProtocolDecl;
117class ObjCTypeParamDecl;
118struct PrintingPolicy;
119class RecordDecl;
120class Stmt;
121class TagDecl;
122class TemplateArgument;
123class TemplateArgumentListInfo;
124class TemplateArgumentLoc;
125class TemplateTypeParmDecl;
126class TypedefNameDecl;
127class UnresolvedUsingTypenameDecl;
128
129using CanQualType = CanQual<Type>;
130
131// Provide forward declarations for all of the *Type classes.
132#define TYPE(Class, Base) class Class##Type;
133#include "clang/AST/TypeNodes.def"
134
135/// The collection of all-type qualifiers we support.
136/// Clang supports five independent qualifiers:
137/// * C99: const, volatile, and restrict
138/// * MS: __unaligned
139/// * Embedded C (TR18037): address spaces
140/// * Objective C: the GC attributes (none, weak, or strong)
141class Qualifiers {
142public:
143 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
144 Const = 0x1,
145 Restrict = 0x2,
146 Volatile = 0x4,
147 CVRMask = Const | Volatile | Restrict
148 };
149
150 enum GC {
151 GCNone = 0,
152 Weak,
153 Strong
154 };
155
156 enum ObjCLifetime {
157 /// There is no lifetime qualification on this type.
158 OCL_None,
159
160 /// This object can be modified without requiring retains or
161 /// releases.
162 OCL_ExplicitNone,
163
164 /// Assigning into this object requires the old value to be
165 /// released and the new value to be retained. The timing of the
166 /// release of the old value is inexact: it may be moved to
167 /// immediately after the last known point where the value is
168 /// live.
169 OCL_Strong,
170
171 /// Reading or writing from this object requires a barrier call.
172 OCL_Weak,
173
174 /// Assigning into this object requires a lifetime extension.
175 OCL_Autoreleasing
176 };
177
178 enum {
179 /// The maximum supported address space number.
180 /// 23 bits should be enough for anyone.
181 MaxAddressSpace = 0x7fffffu,
182
183 /// The width of the "fast" qualifier mask.
184 FastWidth = 3,
185
186 /// The fast qualifier mask.
187 FastMask = (1 << FastWidth) - 1
188 };
189
190 /// Returns the common set of qualifiers while removing them from
191 /// the given sets.
192 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
193 // If both are only CVR-qualified, bit operations are sufficient.
194 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
195 Qualifiers Q;
196 Q.Mask = L.Mask & R.Mask;
197 L.Mask &= ~Q.Mask;
198 R.Mask &= ~Q.Mask;
199 return Q;
200 }
201
202 Qualifiers Q;
203 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
204 Q.addCVRQualifiers(CommonCRV);
205 L.removeCVRQualifiers(CommonCRV);
206 R.removeCVRQualifiers(CommonCRV);
207
208 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
209 Q.setObjCGCAttr(L.getObjCGCAttr());
210 L.removeObjCGCAttr();
211 R.removeObjCGCAttr();
212 }
213
214 if (L.getObjCLifetime() == R.getObjCLifetime()) {
215 Q.setObjCLifetime(L.getObjCLifetime());
216 L.removeObjCLifetime();
217 R.removeObjCLifetime();
218 }
219
220 if (L.getAddressSpace() == R.getAddressSpace()) {
221 Q.setAddressSpace(L.getAddressSpace());
222 L.removeAddressSpace();
223 R.removeAddressSpace();
224 }
225 return Q;
226 }
227
228 static Qualifiers fromFastMask(unsigned Mask) {
229 Qualifiers Qs;
230 Qs.addFastQualifiers(Mask);
231 return Qs;
232 }
233
234 static Qualifiers fromCVRMask(unsigned CVR) {
235 Qualifiers Qs;
236 Qs.addCVRQualifiers(CVR);
237 return Qs;
238 }
239
240 static Qualifiers fromCVRUMask(unsigned CVRU) {
241 Qualifiers Qs;
242 Qs.addCVRUQualifiers(CVRU);
243 return Qs;
244 }
245
246 // Deserialize qualifiers from an opaque representation.
247 static Qualifiers fromOpaqueValue(unsigned opaque) {
248 Qualifiers Qs;
249 Qs.Mask = opaque;
250 return Qs;
251 }
252
253 // Serialize these qualifiers into an opaque representation.
254 unsigned getAsOpaqueValue() const {
255 return Mask;
256 }
257
258 bool hasConst() const { return Mask & Const; }
259 void setConst(bool flag) {
260 Mask = (Mask & ~Const) | (flag ? Const : 0);
261 }
262 void removeConst() { Mask &= ~Const; }
263 void addConst() { Mask |= Const; }
264
265 bool hasVolatile() const { return Mask & Volatile; }
266 void setVolatile(bool flag) {
267 Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
268 }
269 void removeVolatile() { Mask &= ~Volatile; }
270 void addVolatile() { Mask |= Volatile; }
271
272 bool hasRestrict() const { return Mask & Restrict; }
273 void setRestrict(bool flag) {
274 Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
275 }
276 void removeRestrict() { Mask &= ~Restrict; }
277 void addRestrict() { Mask |= Restrict; }
278
279 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
280 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
281 void setCVRQualifiers(unsigned mask) {
282 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
283 Mask = (Mask & ~CVRMask) | mask;
284 }
285 void removeCVRQualifiers(unsigned mask) {
286 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
287 Mask &= ~mask;
288 }
289 void removeCVRQualifiers() {
290 removeCVRQualifiers(CVRMask);
291 }
292 void addCVRQualifiers(unsigned mask) {
293 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
294 Mask |= mask;
295 }
296 void addCVRUQualifiers(unsigned mask) {
297 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
298 Mask |= mask;
299 }
300
301 bool hasUnaligned() const { return Mask & UMask; }
302 void setUnaligned(bool flag) {
303 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
304 }
305 void removeUnaligned() { Mask &= ~UMask; }
306 void addUnaligned() { Mask |= UMask; }
307
308 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
309 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
310 void setObjCGCAttr(GC type) {
311 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
312 }
313 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
314 void addObjCGCAttr(GC type) {
315 assert(type);
316 setObjCGCAttr(type);
317 }
318 Qualifiers withoutObjCGCAttr() const {
319 Qualifiers qs = *this;
320 qs.removeObjCGCAttr();
321 return qs;
322 }
323 Qualifiers withoutObjCLifetime() const {
324 Qualifiers qs = *this;
325 qs.removeObjCLifetime();
326 return qs;
327 }
328
329 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
330 ObjCLifetime getObjCLifetime() const {
331 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
332 }
333 void setObjCLifetime(ObjCLifetime type) {
334 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
335 }
336 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
337 void addObjCLifetime(ObjCLifetime type) {
338 assert(type);
339 assert(!hasObjCLifetime());
340 Mask |= (type << LifetimeShift);
341 }
342
343 /// True if the lifetime is neither None or ExplicitNone.
344 bool hasNonTrivialObjCLifetime() const {
345 ObjCLifetime lifetime = getObjCLifetime();
346 return (lifetime > OCL_ExplicitNone);
347 }
348
349 /// True if the lifetime is either strong or weak.
350 bool hasStrongOrWeakObjCLifetime() const {
351 ObjCLifetime lifetime = getObjCLifetime();
352 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
353 }
354
355 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
356 LangAS getAddressSpace() const {
357 return static_cast<LangAS>(Mask >> AddressSpaceShift);
358 }
359 bool hasTargetSpecificAddressSpace() const {
360 return isTargetAddressSpace(getAddressSpace());
361 }
362 /// Get the address space attribute value to be printed by diagnostics.
363 unsigned getAddressSpaceAttributePrintValue() const {
364 auto Addr = getAddressSpace();
365 // This function is not supposed to be used with language specific
366 // address spaces. If that happens, the diagnostic message should consider
367 // printing the QualType instead of the address space value.
368 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace());
369 if (Addr != LangAS::Default)
370 return toTargetAddressSpace(Addr);
371 // TODO: The diagnostic messages where Addr may be 0 should be fixed
372 // since it cannot differentiate the situation where 0 denotes the default
373 // address space or user specified __attribute__((address_space(0))).
374 return 0;
375 }
376 void setAddressSpace(LangAS space) {
377 assert((unsigned)space <= MaxAddressSpace);
378 Mask = (Mask & ~AddressSpaceMask)
379 | (((uint32_t) space) << AddressSpaceShift);
380 }
381 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
382 void addAddressSpace(LangAS space) {
383 assert(space != LangAS::Default);
384 setAddressSpace(space);
385 }
386
387 // Fast qualifiers are those that can be allocated directly
388 // on a QualType object.
389 bool hasFastQualifiers() const { return getFastQualifiers(); }
390 unsigned getFastQualifiers() const { return Mask & FastMask; }
391 void setFastQualifiers(unsigned mask) {
392 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
393 Mask = (Mask & ~FastMask) | mask;
394 }
395 void removeFastQualifiers(unsigned mask) {
396 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
397 Mask &= ~mask;
398 }
399 void removeFastQualifiers() {
400 removeFastQualifiers(FastMask);
401 }
402 void addFastQualifiers(unsigned mask) {
403 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
404 Mask |= mask;
405 }
406
407 /// Return true if the set contains any qualifiers which require an ExtQuals
408 /// node to be allocated.
409 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
410 Qualifiers getNonFastQualifiers() const {
411 Qualifiers Quals = *this;
412 Quals.setFastQualifiers(0);
413 return Quals;
414 }
415
416 /// Return true if the set contains any qualifiers.
417 bool hasQualifiers() const { return Mask; }
418 bool empty() const { return !Mask; }
419
420 /// Add the qualifiers from the given set to this set.
421 void addQualifiers(Qualifiers Q) {
422 // If the other set doesn't have any non-boolean qualifiers, just
423 // bit-or it in.
424 if (!(Q.Mask & ~CVRMask))
425 Mask |= Q.Mask;
426 else {
427 Mask |= (Q.Mask & CVRMask);
428 if (Q.hasAddressSpace())
429 addAddressSpace(Q.getAddressSpace());
430 if (Q.hasObjCGCAttr())
431 addObjCGCAttr(Q.getObjCGCAttr());
432 if (Q.hasObjCLifetime())
433 addObjCLifetime(Q.getObjCLifetime());
434 }
435 }
436
437 /// Remove the qualifiers from the given set from this set.
438 void removeQualifiers(Qualifiers Q) {
439 // If the other set doesn't have any non-boolean qualifiers, just
440 // bit-and the inverse in.
441 if (!(Q.Mask & ~CVRMask))
442 Mask &= ~Q.Mask;
443 else {
444 Mask &= ~(Q.Mask & CVRMask);
445 if (getObjCGCAttr() == Q.getObjCGCAttr())
446 removeObjCGCAttr();
447 if (getObjCLifetime() == Q.getObjCLifetime())
448 removeObjCLifetime();
449 if (getAddressSpace() == Q.getAddressSpace())
450 removeAddressSpace();
451 }
452 }
453
454 /// Add the qualifiers from the given set to this set, given that
455 /// they don't conflict.
456 void addConsistentQualifiers(Qualifiers qs) {
457 assert(getAddressSpace() == qs.getAddressSpace() ||
458 !hasAddressSpace() || !qs.hasAddressSpace());
459 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
460 !hasObjCGCAttr() || !qs.hasObjCGCAttr());
461 assert(getObjCLifetime() == qs.getObjCLifetime() ||
462 !hasObjCLifetime() || !qs.hasObjCLifetime());
463 Mask |= qs.Mask;
464 }
465
466 /// Returns true if this address space is a superset of the other one.
467 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
468 /// overlapping address spaces.
469 /// CL1.1 or CL1.2:
470 /// every address space is a superset of itself.
471 /// CL2.0 adds:
472 /// __generic is a superset of any address space except for __constant.
473 bool isAddressSpaceSupersetOf(Qualifiers other) const {
474 return
475 // Address spaces must match exactly.
476 getAddressSpace() == other.getAddressSpace() ||
477 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
478 // for __constant can be used as __generic.
479 (getAddressSpace() == LangAS::opencl_generic &&
480 other.getAddressSpace() != LangAS::opencl_constant);
481 }
482
483 /// Determines if these qualifiers compatibly include another set.
484 /// Generally this answers the question of whether an object with the other
485 /// qualifiers can be safely used as an object with these qualifiers.
486 bool compatiblyIncludes(Qualifiers other) const {
487 return isAddressSpaceSupersetOf(other) &&
488 // ObjC GC qualifiers can match, be added, or be removed, but can't
489 // be changed.
490 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
491 !other.hasObjCGCAttr()) &&
492 // ObjC lifetime qualifiers must match exactly.
493 getObjCLifetime() == other.getObjCLifetime() &&
494 // CVR qualifiers may subset.
495 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
496 // U qualifier may superset.
497 (!other.hasUnaligned() || hasUnaligned());
498 }
499
500 /// Determines if these qualifiers compatibly include another set of
501 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
502 ///
503 /// One set of Objective-C lifetime qualifiers compatibly includes the other
504 /// if the lifetime qualifiers match, or if both are non-__weak and the
505 /// including set also contains the 'const' qualifier, or both are non-__weak
506 /// and one is None (which can only happen in non-ARC modes).
507 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
508 if (getObjCLifetime() == other.getObjCLifetime())
509 return true;
510
511 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
512 return false;
513
514 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
515 return true;
516
517 return hasConst();
518 }
519
520 /// Determine whether this set of qualifiers is a strict superset of
521 /// another set of qualifiers, not considering qualifier compatibility.
522 bool isStrictSupersetOf(Qualifiers Other) const;
523
524 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
525 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
526
527 explicit operator bool() const { return hasQualifiers(); }
528
529 Qualifiers &operator+=(Qualifiers R) {
530 addQualifiers(R);
531 return *this;
532 }
533
534 // Union two qualifier sets. If an enumerated qualifier appears
535 // in both sets, use the one from the right.
536 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
537 L += R;
538 return L;
539 }
540
541 Qualifiers &operator-=(Qualifiers R) {
542 removeQualifiers(R);
543 return *this;
544 }
545
546 /// Compute the difference between two qualifier sets.
547 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
548 L -= R;
549 return L;
550 }
551
552 std::string getAsString() const;
553 std::string getAsString(const PrintingPolicy &Policy) const;
554
555 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
556 void print(raw_ostream &OS, const PrintingPolicy &Policy,
557 bool appendSpaceIfNonEmpty = false) const;
558
559 void Profile(llvm::FoldingSetNodeID &ID) const {
560 ID.AddInteger(Mask);
561 }
562
563private:
564 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
565 // |C R V|U|GCAttr|Lifetime|AddressSpace|
566 uint32_t Mask = 0;
567
568 static const uint32_t UMask = 0x8;
569 static const uint32_t UShift = 3;
570 static const uint32_t GCAttrMask = 0x30;
571 static const uint32_t GCAttrShift = 4;
572 static const uint32_t LifetimeMask = 0x1C0;
573 static const uint32_t LifetimeShift = 6;
574 static const uint32_t AddressSpaceMask =
575 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
576 static const uint32_t AddressSpaceShift = 9;
577};
578
579/// A std::pair-like structure for storing a qualified type split
580/// into its local qualifiers and its locally-unqualified type.
581struct SplitQualType {
582 /// The locally-unqualified type.
583 const Type *Ty = nullptr;
584
585 /// The local qualifiers.
586 Qualifiers Quals;
587
588 SplitQualType() = default;
589 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
590
591 SplitQualType getSingleStepDesugaredType() const; // end of this file
592
593 // Make std::tie work.
594 std::pair<const Type *,Qualifiers> asPair() const {
595 return std::pair<const Type *, Qualifiers>(Ty, Quals);
596 }
597
598 friend bool operator==(SplitQualType a, SplitQualType b) {
599 return a.Ty == b.Ty && a.Quals == b.Quals;
600 }
601 friend bool operator!=(SplitQualType a, SplitQualType b) {
602 return a.Ty != b.Ty || a.Quals != b.Quals;
603 }
604};
605
606/// The kind of type we are substituting Objective-C type arguments into.
607///
608/// The kind of substitution affects the replacement of type parameters when
609/// no concrete type information is provided, e.g., when dealing with an
610/// unspecialized type.
611enum class ObjCSubstitutionContext {
612 /// An ordinary type.
613 Ordinary,
614
615 /// The result type of a method or function.
616 Result,
617
618 /// The parameter type of a method or function.
619 Parameter,
620
621 /// The type of a property.
622 Property,
623
624 /// The superclass of a type.
625 Superclass,
626};
627
628/// A (possibly-)qualified type.
629///
630/// For efficiency, we don't store CV-qualified types as nodes on their
631/// own: instead each reference to a type stores the qualifiers. This
632/// greatly reduces the number of nodes we need to allocate for types (for
633/// example we only need one for 'int', 'const int', 'volatile int',
634/// 'const volatile int', etc).
635///
636/// As an added efficiency bonus, instead of making this a pair, we
637/// just store the two bits we care about in the low bits of the
638/// pointer. To handle the packing/unpacking, we make QualType be a
639/// simple wrapper class that acts like a smart pointer. A third bit
640/// indicates whether there are extended qualifiers present, in which
641/// case the pointer points to a special structure.
642class QualType {
643 friend class QualifierCollector;
644
645 // Thankfully, these are efficiently composable.
646 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
647 Qualifiers::FastWidth> Value;
648
649 const ExtQuals *getExtQualsUnsafe() const {
650 return Value.getPointer().get<const ExtQuals*>();
651 }
652
653 const Type *getTypePtrUnsafe() const {
654 return Value.getPointer().get<const Type*>();
655 }
656
657 const ExtQualsTypeCommonBase *getCommonPtr() const {
658 assert(!isNull() && "Cannot retrieve a NULL type pointer");
659 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
660 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
661 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
662 }
663
664public:
665 QualType() = default;
666 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
667 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
668
669 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
670 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
671
672 /// Retrieves a pointer to the underlying (unqualified) type.
673 ///
674 /// This function requires that the type not be NULL. If the type might be
675 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
676 const Type *getTypePtr() const;
677
678 const Type *getTypePtrOrNull() const;
679
680 /// Retrieves a pointer to the name of the base type.
681 const IdentifierInfo *getBaseTypeIdentifier() const;
682
683 /// Divides a QualType into its unqualified type and a set of local
684 /// qualifiers.
685 SplitQualType split() const;
686
687 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
688
689 static QualType getFromOpaquePtr(const void *Ptr) {
690 QualType T;
691 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
692 return T;
693 }
694
695 const Type &operator*() const {
696 return *getTypePtr();
697 }
698
699 const Type *operator->() const {
700 return getTypePtr();
701 }
702
703 bool isCanonical() const;
704 bool isCanonicalAsParam() const;
705
706 /// Return true if this QualType doesn't point to a type yet.
707 bool isNull() const {
708 return Value.getPointer().isNull();
709 }
710
711 /// Determine whether this particular QualType instance has the
712 /// "const" qualifier set, without looking through typedefs that may have
713 /// added "const" at a different level.
714 bool isLocalConstQualified() const {
715 return (getLocalFastQualifiers() & Qualifiers::Const);
716 }
717
718 /// Determine whether this type is const-qualified.
719 bool isConstQualified() const;
720
721 /// Determine whether this particular QualType instance has the
722 /// "restrict" qualifier set, without looking through typedefs that may have
723 /// added "restrict" at a different level.
724 bool isLocalRestrictQualified() const {
725 return (getLocalFastQualifiers() & Qualifiers::Restrict);
726 }
727
728 /// Determine whether this type is restrict-qualified.
729 bool isRestrictQualified() const;
730
731 /// Determine whether this particular QualType instance has the
732 /// "volatile" qualifier set, without looking through typedefs that may have
733 /// added "volatile" at a different level.
734 bool isLocalVolatileQualified() const {
735 return (getLocalFastQualifiers() & Qualifiers::Volatile);
736 }
737
738 /// Determine whether this type is volatile-qualified.
739 bool isVolatileQualified() const;
740
741 /// Determine whether this particular QualType instance has any
742 /// qualifiers, without looking through any typedefs that might add
743 /// qualifiers at a different level.
744 bool hasLocalQualifiers() const {
745 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
746 }
747
748 /// Determine whether this type has any qualifiers.
749 bool hasQualifiers() const;
750
751 /// Determine whether this particular QualType instance has any
752 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
753 /// instance.
754 bool hasLocalNonFastQualifiers() const {
755 return Value.getPointer().is<const ExtQuals*>();
756 }
757
758 /// Retrieve the set of qualifiers local to this particular QualType
759 /// instance, not including any qualifiers acquired through typedefs or
760 /// other sugar.
761 Qualifiers getLocalQualifiers() const;
762
763 /// Retrieve the set of qualifiers applied to this type.
764 Qualifiers getQualifiers() const;
765
766 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
767 /// local to this particular QualType instance, not including any qualifiers
768 /// acquired through typedefs or other sugar.
769 unsigned getLocalCVRQualifiers() const {
770 return getLocalFastQualifiers();
771 }
772
773 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
774 /// applied to this type.
775 unsigned getCVRQualifiers() const;
776
777 bool isConstant(const ASTContext& Ctx) const {
778 return QualType::isConstant(*this, Ctx);
779 }
780
781 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
782 bool isPODType(const ASTContext &Context) const;
783
784 /// Return true if this is a POD type according to the rules of the C++98
785 /// standard, regardless of the current compilation's language.
786 bool isCXX98PODType(const ASTContext &Context) const;
787
788 /// Return true if this is a POD type according to the more relaxed rules
789 /// of the C++11 standard, regardless of the current compilation's language.
790 /// (C++0x [basic.types]p9). Note that, unlike
791 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
792 bool isCXX11PODType(const ASTContext &Context) const;
793
794 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
795 bool isTrivialType(const ASTContext &Context) const;
796
797 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
798 bool isTriviallyCopyableType(const ASTContext &Context) const;
799
800
801 /// Returns true if it is a class and it might be dynamic.
802 bool mayBeDynamicClass() const;
803
804 /// Returns true if it is not a class or if the class might not be dynamic.
805 bool mayBeNotDynamicClass() const;
806
807 // Don't promise in the API that anything besides 'const' can be
808 // easily added.
809
810 /// Add the `const` type qualifier to this QualType.
811 void addConst() {
812 addFastQualifiers(Qualifiers::Const);
813 }
814 QualType withConst() const {
815 return withFastQualifiers(Qualifiers::Const);
816 }
817
818 /// Add the `volatile` type qualifier to this QualType.
819 void addVolatile() {
820 addFastQualifiers(Qualifiers::Volatile);
821 }
822 QualType withVolatile() const {
823 return withFastQualifiers(Qualifiers::Volatile);
824 }
825
826 /// Add the `restrict` qualifier to this QualType.
827 void addRestrict() {
828 addFastQualifiers(Qualifiers::Restrict);
829 }
830 QualType withRestrict() const {
831 return withFastQualifiers(Qualifiers::Restrict);
832 }
833
834 QualType withCVRQualifiers(unsigned CVR) const {
835 return withFastQualifiers(CVR);
836 }
837
838 void addFastQualifiers(unsigned TQs) {
839 assert(!(TQs & ~Qualifiers::FastMask)
840 && "non-fast qualifier bits set in mask!");
841 Value.setInt(Value.getInt() | TQs);
842 }
843
844 void removeLocalConst();
845 void removeLocalVolatile();
846 void removeLocalRestrict();
847 void removeLocalCVRQualifiers(unsigned Mask);
848
849 void removeLocalFastQualifiers() { Value.setInt(0); }
850 void removeLocalFastQualifiers(unsigned Mask) {
851 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
852 Value.setInt(Value.getInt() & ~Mask);
853 }
854
855 // Creates a type with the given qualifiers in addition to any
856 // qualifiers already on this type.
857 QualType withFastQualifiers(unsigned TQs) const {
858 QualType T = *this;
859 T.addFastQualifiers(TQs);
860 return T;
861 }
862
863 // Creates a type with exactly the given fast qualifiers, removing
864 // any existing fast qualifiers.
865 QualType withExactLocalFastQualifiers(unsigned TQs) const {
866 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
867 }
868
869 // Removes fast qualifiers, but leaves any extended qualifiers in place.
870 QualType withoutLocalFastQualifiers() const {
871 QualType T = *this;
872 T.removeLocalFastQualifiers();
873 return T;
874 }
875
876 QualType getCanonicalType() const;
877
878 /// Return this type with all of the instance-specific qualifiers
879 /// removed, but without removing any qualifiers that may have been applied
880 /// through typedefs.
881 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
882
883 /// Retrieve the unqualified variant of the given type,
884 /// removing as little sugar as possible.
885 ///
886 /// This routine looks through various kinds of sugar to find the
887 /// least-desugared type that is unqualified. For example, given:
888 ///
889 /// \code
890 /// typedef int Integer;
891 /// typedef const Integer CInteger;
892 /// typedef CInteger DifferenceType;
893 /// \endcode
894 ///
895 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
896 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
897 ///
898 /// The resulting type might still be qualified if it's sugar for an array
899 /// type. To strip qualifiers even from within a sugared array type, use
900 /// ASTContext::getUnqualifiedArrayType.
901 inline QualType getUnqualifiedType() const;
902
903 /// Retrieve the unqualified variant of the given type, removing as little
904 /// sugar as possible.
905 ///
906 /// Like getUnqualifiedType(), but also returns the set of
907 /// qualifiers that were built up.
908 ///
909 /// The resulting type might still be qualified if it's sugar for an array
910 /// type. To strip qualifiers even from within a sugared array type, use
911 /// ASTContext::getUnqualifiedArrayType.
912 inline SplitQualType getSplitUnqualifiedType() const;
913
914 /// Determine whether this type is more qualified than the other
915 /// given type, requiring exact equality for non-CVR qualifiers.
916 bool isMoreQualifiedThan(QualType Other) const;
917
918 /// Determine whether this type is at least as qualified as the other
919 /// given type, requiring exact equality for non-CVR qualifiers.
920 bool isAtLeastAsQualifiedAs(QualType Other) const;
921
922 QualType getNonReferenceType() const;
923
924 /// Determine the type of a (typically non-lvalue) expression with the
925 /// specified result type.
926 ///
927 /// This routine should be used for expressions for which the return type is
928 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
929 /// an lvalue. It removes a top-level reference (since there are no
930 /// expressions of reference type) and deletes top-level cvr-qualifiers
931 /// from non-class types (in C++) or all types (in C).
932 QualType getNonLValueExprType(const ASTContext &Context) const;
933
934 /// Return the specified type with any "sugar" removed from
935 /// the type. This takes off typedefs, typeof's etc. If the outer level of
936 /// the type is already concrete, it returns it unmodified. This is similar
937 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
938 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
939 /// concrete.
940 ///
941 /// Qualifiers are left in place.
942 QualType getDesugaredType(const ASTContext &Context) const {
943 return getDesugaredType(*this, Context);
944 }
945
946 SplitQualType getSplitDesugaredType() const {
947 return getSplitDesugaredType(*this);
948 }
949
950 /// Return the specified type with one level of "sugar" removed from
951 /// the type.
952 ///
953 /// This routine takes off the first typedef, typeof, etc. If the outer level
954 /// of the type is already concrete, it returns it unmodified.
955 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
956 return getSingleStepDesugaredTypeImpl(*this, Context);
957 }
958
959 /// Returns the specified type after dropping any
960 /// outer-level parentheses.
961 QualType IgnoreParens() const {
962 if (isa<ParenType>(*this))
963 return QualType::IgnoreParens(*this);
964 return *this;
965 }
966
967 /// Indicate whether the specified types and qualifiers are identical.
968 friend bool operator==(const QualType &LHS, const QualType &RHS) {
969 return LHS.Value == RHS.Value;
970 }
971 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
972 return LHS.Value != RHS.Value;
973 }
974
975 static std::string getAsString(SplitQualType split,
976 const PrintingPolicy &Policy) {
977 return getAsString(split.Ty, split.Quals, Policy);
978 }
979 static std::string getAsString(const Type *ty, Qualifiers qs,
980 const PrintingPolicy &Policy);
981
982 std::string getAsString() const;
983 std::string getAsString(const PrintingPolicy &Policy) const;
984
985 void print(raw_ostream &OS, const PrintingPolicy &Policy,
986 const Twine &PlaceHolder = Twine(),
987 unsigned Indentation = 0) const {
988 print(split(), OS, Policy, PlaceHolder, Indentation);
989 }
990
991 static void print(SplitQualType split, raw_ostream &OS,
992 const PrintingPolicy &policy, const Twine &PlaceHolder,
993 unsigned Indentation = 0) {
994 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
995 }
996
997 static void print(const Type *ty, Qualifiers qs,
998 raw_ostream &OS, const PrintingPolicy &policy,
999 const Twine &PlaceHolder,
1000 unsigned Indentation = 0);
1001
1002 void getAsStringInternal(std::string &Str,
1003 const PrintingPolicy &Policy) const {
1004 return getAsStringInternal(split(), Str, Policy);
1005 }
1006
1007 static void getAsStringInternal(SplitQualType split, std::string &out,
1008 const PrintingPolicy &policy) {
1009 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1010 }
1011
1012 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1013 std::string &out,
1014 const PrintingPolicy &policy);
1015
1016 class StreamedQualTypeHelper {
1017 const QualType &T;
1018 const PrintingPolicy &Policy;
1019 const Twine &PlaceHolder;
1020 unsigned Indentation;
1021
1022 public:
1023 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1024 const Twine &PlaceHolder, unsigned Indentation)
1025 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1026 Indentation(Indentation) {}
1027
1028 friend raw_ostream &operator<<(raw_ostream &OS,
1029 const StreamedQualTypeHelper &SQT) {
1030 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1031 return OS;
1032 }
1033 };
1034
1035 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1036 const Twine &PlaceHolder = Twine(),
1037 unsigned Indentation = 0) const {
1038 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1039 }
1040
1041 void dump(const char *s) const;
1042 void dump() const;
1043 void dump(llvm::raw_ostream &OS) const;
1044
1045 void Profile(llvm::FoldingSetNodeID &ID) const {
1046 ID.AddPointer(getAsOpaquePtr());
1047 }
1048
1049 /// Return the address space of this type.
1050 inline LangAS getAddressSpace() const;
1051
1052 /// Returns gc attribute of this type.
1053 inline Qualifiers::GC getObjCGCAttr() const;
1054
1055 /// true when Type is objc's weak.
1056 bool isObjCGCWeak() const {
1057 return getObjCGCAttr() == Qualifiers::Weak;
1058 }
1059
1060 /// true when Type is objc's strong.
1061 bool isObjCGCStrong() const {
1062 return getObjCGCAttr() == Qualifiers::Strong;
1063 }
1064
1065 /// Returns lifetime attribute of this type.
1066 Qualifiers::ObjCLifetime getObjCLifetime() const {
1067 return getQualifiers().getObjCLifetime();
1068 }
1069
1070 bool hasNonTrivialObjCLifetime() const {
1071 return getQualifiers().hasNonTrivialObjCLifetime();
1072 }
1073
1074 bool hasStrongOrWeakObjCLifetime() const {
1075 return getQualifiers().hasStrongOrWeakObjCLifetime();
1076 }
1077
1078 // true when Type is objc's weak and weak is enabled but ARC isn't.
1079 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1080
1081 enum PrimitiveDefaultInitializeKind {
1082 /// The type does not fall into any of the following categories. Note that
1083 /// this case is zero-valued so that values of this enum can be used as a
1084 /// boolean condition for non-triviality.
1085 PDIK_Trivial,
1086
1087 /// The type is an Objective-C retainable pointer type that is qualified
1088 /// with the ARC __strong qualifier.
1089 PDIK_ARCStrong,
1090
1091 /// The type is an Objective-C retainable pointer type that is qualified
1092 /// with the ARC __weak qualifier.
1093 PDIK_ARCWeak,
1094
1095 /// The type is a struct containing a field whose type is not PCK_Trivial.
1096 PDIK_Struct
1097 };
1098
1099 /// Functions to query basic properties of non-trivial C struct types.
1100
1101 /// Check if this is a non-trivial type that would cause a C struct
1102 /// transitively containing this type to be non-trivial to default initialize
1103 /// and return the kind.
1104 PrimitiveDefaultInitializeKind
1105 isNonTrivialToPrimitiveDefaultInitialize() const;
1106
1107 enum PrimitiveCopyKind {
1108 /// The type does not fall into any of the following categories. Note that
1109 /// this case is zero-valued so that values of this enum can be used as a
1110 /// boolean condition for non-triviality.
1111 PCK_Trivial,
1112
1113 /// The type would be trivial except that it is volatile-qualified. Types
1114 /// that fall into one of the other non-trivial cases may additionally be
1115 /// volatile-qualified.
1116 PCK_VolatileTrivial,
1117
1118 /// The type is an Objective-C retainable pointer type that is qualified
1119 /// with the ARC __strong qualifier.
1120 PCK_ARCStrong,
1121
1122 /// The type is an Objective-C retainable pointer type that is qualified
1123 /// with the ARC __weak qualifier.
1124 PCK_ARCWeak,
1125
1126 /// The type is a struct containing a field whose type is neither
1127 /// PCK_Trivial nor PCK_VolatileTrivial.
1128 /// Note that a C++ struct type does not necessarily match this; C++ copying
1129 /// semantics are too complex to express here, in part because they depend
1130 /// on the exact constructor or assignment operator that is chosen by
1131 /// overload resolution to do the copy.
1132 PCK_Struct
1133 };
1134
1135 /// Check if this is a non-trivial type that would cause a C struct
1136 /// transitively containing this type to be non-trivial to copy and return the
1137 /// kind.
1138 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1139
1140 /// Check if this is a non-trivial type that would cause a C struct
1141 /// transitively containing this type to be non-trivial to destructively
1142 /// move and return the kind. Destructive move in this context is a C++-style
1143 /// move in which the source object is placed in a valid but unspecified state
1144 /// after it is moved, as opposed to a truly destructive move in which the
1145 /// source object is placed in an uninitialized state.
1146 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1147
1148 enum DestructionKind {
1149 DK_none,
1150 DK_cxx_destructor,
1151 DK_objc_strong_lifetime,
1152 DK_objc_weak_lifetime,
1153 DK_nontrivial_c_struct
1154 };
1155
1156 /// Returns a nonzero value if objects of this type require
1157 /// non-trivial work to clean up after. Non-zero because it's
1158 /// conceivable that qualifiers (objc_gc(weak)?) could make
1159 /// something require destruction.
1160 DestructionKind isDestructedType() const {
1161 return isDestructedTypeImpl(*this);
1162 }
1163
1164 /// Determine whether expressions of the given type are forbidden
1165 /// from being lvalues in C.
1166 ///
1167 /// The expression types that are forbidden to be lvalues are:
1168 /// - 'void', but not qualified void
1169 /// - function types
1170 ///
1171 /// The exact rule here is C99 6.3.2.1:
1172 /// An lvalue is an expression with an object type or an incomplete
1173 /// type other than void.
1174 bool isCForbiddenLValueType() const;
1175
1176 /// Substitute type arguments for the Objective-C type parameters used in the
1177 /// subject type.
1178 ///
1179 /// \param ctx ASTContext in which the type exists.
1180 ///
1181 /// \param typeArgs The type arguments that will be substituted for the
1182 /// Objective-C type parameters in the subject type, which are generally
1183 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1184 /// parameters will be replaced with their bounds or id/Class, as appropriate
1185 /// for the context.
1186 ///
1187 /// \param context The context in which the subject type was written.
1188 ///
1189 /// \returns the resulting type.
1190 QualType substObjCTypeArgs(ASTContext &ctx,
1191 ArrayRef<QualType> typeArgs,
1192 ObjCSubstitutionContext context) const;
1193
1194 /// Substitute type arguments from an object type for the Objective-C type
1195 /// parameters used in the subject type.
1196 ///
1197 /// This operation combines the computation of type arguments for
1198 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1199 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1200 /// callers that need to perform a single substitution in isolation.
1201 ///
1202 /// \param objectType The type of the object whose member type we're
1203 /// substituting into. For example, this might be the receiver of a message
1204 /// or the base of a property access.
1205 ///
1206 /// \param dc The declaration context from which the subject type was
1207 /// retrieved, which indicates (for example) which type parameters should
1208 /// be substituted.
1209 ///
1210 /// \param context The context in which the subject type was written.
1211 ///
1212 /// \returns the subject type after replacing all of the Objective-C type
1213 /// parameters with their corresponding arguments.
1214 QualType substObjCMemberType(QualType objectType,
1215 const DeclContext *dc,
1216 ObjCSubstitutionContext context) const;
1217
1218 /// Strip Objective-C "__kindof" types from the given type.
1219 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1220
1221 /// Remove all qualifiers including _Atomic.
1222 QualType getAtomicUnqualifiedType() const;
1223
1224private:
1225 // These methods are implemented in a separate translation unit;
1226 // "static"-ize them to avoid creating temporary QualTypes in the
1227 // caller.
1228 static bool isConstant(QualType T, const ASTContext& Ctx);
1229 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1230 static SplitQualType getSplitDesugaredType(QualType T);
1231 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1232 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1233 const ASTContext &C);
1234 static QualType IgnoreParens(QualType T);
1235 static DestructionKind isDestructedTypeImpl(QualType type);
1236};
1237
1238} // namespace clang
1239
1240namespace llvm {
1241
1242/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1243/// to a specific Type class.
1244template<> struct simplify_type< ::clang::QualType> {
1245 using SimpleType = const ::clang::Type *;
1246
1247 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1248 return Val.getTypePtr();
1249 }
1250};
1251
1252// Teach SmallPtrSet that QualType is "basically a pointer".
1253template<>
1254struct PointerLikeTypeTraits<clang::QualType> {
1255 static inline void *getAsVoidPointer(clang::QualType P) {
1256 return P.getAsOpaquePtr();
1257 }
1258
1259 static inline clang::QualType getFromVoidPointer(void *P) {
1260 return clang::QualType::getFromOpaquePtr(P);
1261 }
1262
1263 // Various qualifiers go in low bits.
1264 enum { NumLowBitsAvailable = 0 };
1265};
1266
1267} // namespace llvm
1268
1269namespace clang {
1270
1271/// Base class that is common to both the \c ExtQuals and \c Type
1272/// classes, which allows \c QualType to access the common fields between the
1273/// two.
1274class ExtQualsTypeCommonBase {
1275 friend class ExtQuals;
1276 friend class QualType;
1277 friend class Type;
1278
1279 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1280 /// a self-referential pointer (for \c Type).
1281 ///
1282 /// This pointer allows an efficient mapping from a QualType to its
1283 /// underlying type pointer.
1284 const Type *const BaseType;
1285
1286 /// The canonical type of this type. A QualType.
1287 QualType CanonicalType;
1288
1289 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1290 : BaseType(baseType), CanonicalType(canon) {}
1291};
1292
1293/// We can encode up to four bits in the low bits of a
1294/// type pointer, but there are many more type qualifiers that we want
1295/// to be able to apply to an arbitrary type. Therefore we have this
1296/// struct, intended to be heap-allocated and used by QualType to
1297/// store qualifiers.
1298///
1299/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1300/// in three low bits on the QualType pointer; a fourth bit records whether
1301/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1302/// Objective-C GC attributes) are much more rare.
1303class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1304 // NOTE: changing the fast qualifiers should be straightforward as
1305 // long as you don't make 'const' non-fast.
1306 // 1. Qualifiers:
1307 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1308 // Fast qualifiers must occupy the low-order bits.
1309 // b) Update Qualifiers::FastWidth and FastMask.
1310 // 2. QualType:
1311 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1312 // b) Update remove{Volatile,Restrict}, defined near the end of
1313 // this header.
1314 // 3. ASTContext:
1315 // a) Update get{Volatile,Restrict}Type.
1316
1317 /// The immutable set of qualifiers applied by this node. Always contains
1318 /// extended qualifiers.
1319 Qualifiers Quals;
1320
1321 ExtQuals *this_() { return this; }
1322
1323public:
1324 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1325 : ExtQualsTypeCommonBase(baseType,
1326 canon.isNull() ? QualType(this_(), 0) : canon),
1327 Quals(quals) {
1328 assert(Quals.hasNonFastQualifiers()
1329 && "ExtQuals created with no fast qualifiers");
1330 assert(!Quals.hasFastQualifiers()
1331 && "ExtQuals created with fast qualifiers");
1332 }
1333
1334 Qualifiers getQualifiers() const { return Quals; }
1335
1336 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1337 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1338
1339 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1340 Qualifiers::ObjCLifetime getObjCLifetime() const {
1341 return Quals.getObjCLifetime();
1342 }
1343
1344 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1345 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1346
1347 const Type *getBaseType() const { return BaseType; }
1348
1349public:
1350 void Profile(llvm::FoldingSetNodeID &ID) const {
1351 Profile(ID, getBaseType(), Quals);
1352 }
1353
1354 static void Profile(llvm::FoldingSetNodeID &ID,
1355 const Type *BaseType,
1356 Qualifiers Quals) {
1357 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1358 ID.AddPointer(BaseType);
1359 Quals.Profile(ID);
1360 }
1361};
1362
1363/// The kind of C++11 ref-qualifier associated with a function type.
1364/// This determines whether a member function's "this" object can be an
1365/// lvalue, rvalue, or neither.
1366enum RefQualifierKind {
1367 /// No ref-qualifier was provided.
1368 RQ_None = 0,
1369
1370 /// An lvalue ref-qualifier was provided (\c &).
1371 RQ_LValue,
1372
1373 /// An rvalue ref-qualifier was provided (\c &&).
1374 RQ_RValue
1375};
1376
1377/// Which keyword(s) were used to create an AutoType.
1378enum class AutoTypeKeyword {
1379 /// auto
1380 Auto,
1381
1382 /// decltype(auto)
1383 DecltypeAuto,
1384
1385 /// __auto_type (GNU extension)
1386 GNUAutoType
1387};
1388
1389/// The base class of the type hierarchy.
1390///
1391/// A central concept with types is that each type always has a canonical
1392/// type. A canonical type is the type with any typedef names stripped out
1393/// of it or the types it references. For example, consider:
1394///
1395/// typedef int foo;
1396/// typedef foo* bar;
1397/// 'int *' 'foo *' 'bar'
1398///
1399/// There will be a Type object created for 'int'. Since int is canonical, its
1400/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1401/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1402/// there is a PointerType that represents 'int*', which, like 'int', is
1403/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1404/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1405/// is also 'int*'.
1406///
1407/// Non-canonical types are useful for emitting diagnostics, without losing
1408/// information about typedefs being used. Canonical types are useful for type
1409/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1410/// about whether something has a particular form (e.g. is a function type),
1411/// because they implicitly, recursively, strip all typedefs out of a type.
1412///
1413/// Types, once created, are immutable.
1414///
1415class Type : public ExtQualsTypeCommonBase {
1416public:
1417 enum TypeClass {
1418#define TYPE(Class, Base) Class,
1419#define LAST_TYPE(Class) TypeLast = Class,
1420#define ABSTRACT_TYPE(Class, Base)
1421#include "clang/AST/TypeNodes.def"
1422 TagFirst = Record, TagLast = Enum
1423 };
1424
1425private:
1426 /// Bitfields required by the Type class.
1427 class TypeBitfields {
1428 friend class Type;
1429 template <class T> friend class TypePropertyCache;
1430
1431 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1432 unsigned TC : 8;
1433
1434 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1435 unsigned Dependent : 1;
1436
1437 /// Whether this type somehow involves a template parameter, even
1438 /// if the resolution of the type does not depend on a template parameter.
1439 unsigned InstantiationDependent : 1;
1440
1441 /// Whether this type is a variably-modified type (C99 6.7.5).
1442 unsigned VariablyModified : 1;
1443
1444 /// Whether this type contains an unexpanded parameter pack
1445 /// (for C++11 variadic templates).
1446 unsigned ContainsUnexpandedParameterPack : 1;
1447
1448 /// True if the cache (i.e. the bitfields here starting with
1449 /// 'Cache') is valid.
1450 mutable unsigned CacheValid : 1;
1451
1452 /// Linkage of this type.
1453 mutable unsigned CachedLinkage : 3;
1454
1455 /// Whether this type involves and local or unnamed types.
1456 mutable unsigned CachedLocalOrUnnamed : 1;
1457
1458 /// Whether this type comes from an AST file.
1459 mutable unsigned FromAST : 1;
1460
1461 bool isCacheValid() const {
1462 return CacheValid;
1463 }
1464
1465 Linkage getLinkage() const {
1466 assert(isCacheValid() && "getting linkage from invalid cache");
1467 return static_cast<Linkage>(CachedLinkage);
1468 }
1469
1470 bool hasLocalOrUnnamedType() const {
1471 assert(isCacheValid() && "getting linkage from invalid cache");
1472 return CachedLocalOrUnnamed;
1473 }
1474 };
1475 enum { NumTypeBits = 18 };
1476
1477protected:
1478 // These classes allow subclasses to somewhat cleanly pack bitfields
1479 // into Type.
1480
1481 class ArrayTypeBitfields {
1482 friend class ArrayType;
1483
1484 unsigned : NumTypeBits;
1485
1486 /// CVR qualifiers from declarations like
1487 /// 'int X[static restrict 4]'. For function parameters only.
1488 unsigned IndexTypeQuals : 3;
1489
1490 /// Storage class qualifiers from declarations like
1491 /// 'int X[static restrict 4]'. For function parameters only.
1492 /// Actually an ArrayType::ArraySizeModifier.
1493 unsigned SizeModifier : 3;
1494 };
1495
1496 class BuiltinTypeBitfields {
1497 friend class BuiltinType;
1498
1499 unsigned : NumTypeBits;
1500
1501 /// The kind (BuiltinType::Kind) of builtin type this is.
1502 unsigned Kind : 8;
1503 };
1504
1505 class FunctionTypeBitfields {
1506 friend class FunctionProtoType;
1507 friend class FunctionType;
1508
1509 unsigned : NumTypeBits;
1510
1511 /// Extra information which affects how the function is called, like
1512 /// regparm and the calling convention.
1513 unsigned ExtInfo : 12;
1514
1515 /// Used only by FunctionProtoType, put here to pack with the
1516 /// other bitfields.
1517 /// The qualifiers are part of FunctionProtoType because...
1518 ///
1519 /// C++ 8.3.5p4: The return type, the parameter type list and the
1520 /// cv-qualifier-seq, [...], are part of the function type.
1521 unsigned TypeQuals : 4;
1522
1523 /// The ref-qualifier associated with a \c FunctionProtoType.
1524 ///
1525 /// This is a value of type \c RefQualifierKind.
1526 unsigned RefQualifier : 2;
1527 };
1528
1529 class ObjCObjectTypeBitfields {
1530 friend class ObjCObjectType;
1531
1532 unsigned : NumTypeBits;
1533
1534 /// The number of type arguments stored directly on this object type.
1535 unsigned NumTypeArgs : 7;
1536
1537 /// The number of protocols stored directly on this object type.
1538 unsigned NumProtocols : 6;
1539
1540 /// Whether this is a "kindof" type.
1541 unsigned IsKindOf : 1;
1542 };
1543
1544 class ReferenceTypeBitfields {
1545 friend class ReferenceType;
1546
1547 unsigned : NumTypeBits;
1548
1549 /// True if the type was originally spelled with an lvalue sigil.
1550 /// This is never true of rvalue references but can also be false
1551 /// on lvalue references because of C++0x [dcl.typedef]p9,
1552 /// as follows:
1553 ///
1554 /// typedef int &ref; // lvalue, spelled lvalue
1555 /// typedef int &&rvref; // rvalue
1556 /// ref &a; // lvalue, inner ref, spelled lvalue
1557 /// ref &&a; // lvalue, inner ref
1558 /// rvref &a; // lvalue, inner ref, spelled lvalue
1559 /// rvref &&a; // rvalue, inner ref
1560 unsigned SpelledAsLValue : 1;
1561
1562 /// True if the inner type is a reference type. This only happens
1563 /// in non-canonical forms.
1564 unsigned InnerRef : 1;
1565 };
1566
1567 class TypeWithKeywordBitfields {
1568 friend class TypeWithKeyword;
1569
1570 unsigned : NumTypeBits;
1571
1572 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1573 unsigned Keyword : 8;
1574 };
1575
1576 enum { NumTypeWithKeywordBits = 8 };
1577
1578 class ElaboratedTypeBitfields {
1579 friend class ElaboratedType;
1580
1581 unsigned : NumTypeBits;
1582 unsigned : NumTypeWithKeywordBits;
1583
1584 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1585 unsigned HasOwnedTagDecl : 1;
1586 };
1587
1588 class VectorTypeBitfields {
1589 friend class VectorType;
1590 friend class DependentVectorType;
1591
1592 unsigned : NumTypeBits;
1593
1594 /// The kind of vector, either a generic vector type or some
1595 /// target-specific vector type such as for AltiVec or Neon.
1596 unsigned VecKind : 3;
1597
1598 /// The number of elements in the vector.
1599 unsigned NumElements : 29 - NumTypeBits;
1600
1601 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1602 };
1603
1604 class AttributedTypeBitfields {
1605 friend class AttributedType;
1606
1607 unsigned : NumTypeBits;
1608
1609 /// An AttributedType::Kind
1610 unsigned AttrKind : 32 - NumTypeBits;
1611 };
1612
1613 class AutoTypeBitfields {
1614 friend class AutoType;
1615
1616 unsigned : NumTypeBits;
1617
1618 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1619 /// or '__auto_type'? AutoTypeKeyword value.
1620 unsigned Keyword : 2;
1621 };
1622
1623 class SubstTemplateTypeParmPackTypeBitfields {
1624 friend class SubstTemplateTypeParmPackType;
1625
1626 unsigned : NumTypeBits;
1627
1628 /// The number of template arguments in \c Arguments, which is
1629 /// expected to be able to hold at least 1024 according to [implimits].
1630 /// However as this limit is somewhat easy to hit with template
1631 /// metaprogramming we'd prefer to keep it as large as possible.
1632 /// At the moment it has been left as a non-bitfield since this type
1633 /// safely fits in 64 bits as an unsigned, so there is no reason to
1634 /// introduce the performance impact of a bitfield.
1635 unsigned NumArgs;
1636 };
1637
1638 class TemplateSpecializationTypeBitfields {
1639 friend class TemplateSpecializationType;
1640
1641 unsigned : NumTypeBits;
1642
1643 /// Whether this template specialization type is a substituted type alias.
1644 unsigned TypeAlias : 1;
1645
1646 /// The number of template arguments named in this class template
1647 /// specialization, which is expected to be able to hold at least 1024
1648 /// according to [implimits]. However, as this limit is somewhat easy to
1649 /// hit with template metaprogramming we'd prefer to keep it as large
1650 /// as possible. At the moment it has been left as a non-bitfield since
1651 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1652 /// to introduce the performance impact of a bitfield.
1653 unsigned NumArgs;
1654 };
1655
1656 class DependentTemplateSpecializationTypeBitfields {
1657 friend class DependentTemplateSpecializationType;
1658
1659 unsigned : NumTypeBits;
1660 unsigned : NumTypeWithKeywordBits;
1661
1662 /// The number of template arguments named in this class template
1663 /// specialization, which is expected to be able to hold at least 1024
1664 /// according to [implimits]. However, as this limit is somewhat easy to
1665 /// hit with template metaprogramming we'd prefer to keep it as large
1666 /// as possible. At the moment it has been left as a non-bitfield since
1667 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1668 /// to introduce the performance impact of a bitfield.
1669 unsigned NumArgs;
1670 };
1671
1672 class PackExpansionTypeBitfields {
1673 friend class PackExpansionType;
1674
1675 unsigned : NumTypeBits;
1676
1677 /// The number of expansions that this pack expansion will
1678 /// generate when substituted (+1), which is expected to be able to
1679 /// hold at least 1024 according to [implimits]. However, as this limit
1680 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1681 /// keep it as large as possible. At the moment it has been left as a
1682 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1683 /// there is no reason to introduce the performance impact of a bitfield.
1684 ///
1685 /// This field will only have a non-zero value when some of the parameter
1686 /// packs that occur within the pattern have been substituted but others
1687 /// have not.
1688 unsigned NumExpansions;
1689 };
1690
1691 union {
1692 TypeBitfields TypeBits;
1693 ArrayTypeBitfields ArrayTypeBits;
1694 AttributedTypeBitfields AttributedTypeBits;
1695 AutoTypeBitfields AutoTypeBits;
1696 BuiltinTypeBitfields BuiltinTypeBits;
1697 FunctionTypeBitfields FunctionTypeBits;
1698 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1699 ReferenceTypeBitfields ReferenceTypeBits;
1700 TypeWithKeywordBitfields TypeWithKeywordBits;
1701 ElaboratedTypeBitfields ElaboratedTypeBits;
1702 VectorTypeBitfields VectorTypeBits;
1703 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1704 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1705 DependentTemplateSpecializationTypeBitfields
1706 DependentTemplateSpecializationTypeBits;
1707 PackExpansionTypeBitfields PackExpansionTypeBits;
1708
1709 static_assert(sizeof(TypeBitfields) <= 8,
1710 "TypeBitfields is larger than 8 bytes!");
1711 static_assert(sizeof(ArrayTypeBitfields) <= 8,
1712 "ArrayTypeBitfields is larger than 8 bytes!");
1713 static_assert(sizeof(AttributedTypeBitfields) <= 8,
1714 "AttributedTypeBitfields is larger than 8 bytes!");
1715 static_assert(sizeof(AutoTypeBitfields) <= 8,
1716 "AutoTypeBitfields is larger than 8 bytes!");
1717 static_assert(sizeof(BuiltinTypeBitfields) <= 8,
1718 "BuiltinTypeBitfields is larger than 8 bytes!");
1719 static_assert(sizeof(FunctionTypeBitfields) <= 8,
1720 "FunctionTypeBitfields is larger than 8 bytes!");
1721 static_assert(sizeof(ObjCObjectTypeBitfields) <= 8,
1722 "ObjCObjectTypeBitfields is larger than 8 bytes!");
1723 static_assert(sizeof(ReferenceTypeBitfields) <= 8,
1724 "ReferenceTypeBitfields is larger than 8 bytes!");
1725 static_assert(sizeof(TypeWithKeywordBitfields) <= 8,
1726 "TypeWithKeywordBitfields is larger than 8 bytes!");
1727 static_assert(sizeof(ElaboratedTypeBitfields) <= 8,
1728 "ElaboratedTypeBitfields is larger than 8 bytes!");
1729 static_assert(sizeof(VectorTypeBitfields) <= 8,
1730 "VectorTypeBitfields is larger than 8 bytes!");
1731 static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8,
1732 "SubstTemplateTypeParmPackTypeBitfields is larger"
1733 " than 8 bytes!");
1734 static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8,
1735 "TemplateSpecializationTypeBitfields is larger"
1736 " than 8 bytes!");
1737 static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8,
1738 "DependentTemplateSpecializationTypeBitfields is larger"
1739 " than 8 bytes!");
1740 static_assert(sizeof(PackExpansionTypeBitfields) <= 8,
1741 "PackExpansionTypeBitfields is larger than 8 bytes");
1742 };
1743
1744private:
1745 template <class T> friend class TypePropertyCache;
1746
1747 /// Set whether this type comes from an AST file.
1748 void setFromAST(bool V = true) const {
1749 TypeBits.FromAST = V;
1750 }
1751
1752protected:
1753 friend class ASTContext;
1754
1755 Type(TypeClass tc, QualType canon, bool Dependent,
1756 bool InstantiationDependent, bool VariablyModified,
1757 bool ContainsUnexpandedParameterPack)
1758 : ExtQualsTypeCommonBase(this,
1759 canon.isNull() ? QualType(this_(), 0) : canon) {
1760 TypeBits.TC = tc;
1761 TypeBits.Dependent = Dependent;
1762 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1763 TypeBits.VariablyModified = VariablyModified;
1764 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1765 TypeBits.CacheValid = false;
1766 TypeBits.CachedLocalOrUnnamed = false;
1767 TypeBits.CachedLinkage = NoLinkage;
1768 TypeBits.FromAST = false;
1769 }
1770
1771 // silence VC++ warning C4355: 'this' : used in base member initializer list
1772 Type *this_() { return this; }
1773
1774 void setDependent(bool D = true) {
1775 TypeBits.Dependent = D;
1776 if (D)
1777 TypeBits.InstantiationDependent = true;
1778 }
1779
1780 void setInstantiationDependent(bool D = true) {
1781 TypeBits.InstantiationDependent = D; }
1782
1783 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1784
1785 void setContainsUnexpandedParameterPack(bool PP = true) {
1786 TypeBits.ContainsUnexpandedParameterPack = PP;
1787 }
1788
1789public:
1790 friend class ASTReader;
1791 friend class ASTWriter;
1792
1793 Type(const Type &) = delete;
1794 Type &operator=(const Type &) = delete;
1795
1796 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1797
1798 /// Whether this type comes from an AST file.
1799 bool isFromAST() const { return TypeBits.FromAST; }
1800
1801 /// Whether this type is or contains an unexpanded parameter
1802 /// pack, used to support C++0x variadic templates.
1803 ///
1804 /// A type that contains a parameter pack shall be expanded by the
1805 /// ellipsis operator at some point. For example, the typedef in the
1806 /// following example contains an unexpanded parameter pack 'T':
1807 ///
1808 /// \code
1809 /// template<typename ...T>
1810 /// struct X {
1811 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1812 /// };
1813 /// \endcode
1814 ///
1815 /// Note that this routine does not specify which
1816 bool containsUnexpandedParameterPack() const {
1817 return TypeBits.ContainsUnexpandedParameterPack;
1818 }
1819
1820 /// Determines if this type would be canonical if it had no further
1821 /// qualification.
1822 bool isCanonicalUnqualified() const {
1823 return CanonicalType == QualType(this, 0);
1824 }
1825
1826 /// Pull a single level of sugar off of this locally-unqualified type.
1827 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1828 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1829 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1830
1831 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1832 /// object types, function types, and incomplete types.
1833
1834 /// Return true if this is an incomplete type.
1835 /// A type that can describe objects, but which lacks information needed to
1836 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1837 /// routine will need to determine if the size is actually required.
1838 ///
1839 /// Def If non-null, and the type refers to some kind of declaration
1840 /// that can be completed (such as a C struct, C++ class, or Objective-C
1841 /// class), will be set to the declaration.
1842 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1843
1844 /// Return true if this is an incomplete or object
1845 /// type, in other words, not a function type.
1846 bool isIncompleteOrObjectType() const {
1847 return !isFunctionType();
1848 }
1849
1850 /// Determine whether this type is an object type.
1851 bool isObjectType() const {
1852 // C++ [basic.types]p8:
1853 // An object type is a (possibly cv-qualified) type that is not a
1854 // function type, not a reference type, and not a void type.
1855 return !isReferenceType() && !isFunctionType() && !isVoidType();
1856 }
1857
1858 /// Return true if this is a literal type
1859 /// (C++11 [basic.types]p10)
1860 bool isLiteralType(const ASTContext &Ctx) const;
1861
1862 /// Test if this type is a standard-layout type.
1863 /// (C++0x [basic.type]p9)
1864 bool isStandardLayoutType() const;
1865
1866 /// Helper methods to distinguish type categories. All type predicates
1867 /// operate on the canonical type, ignoring typedefs and qualifiers.
1868
1869 /// Returns true if the type is a builtin type.
1870 bool isBuiltinType() const;
1871
1872 /// Test for a particular builtin type.
1873 bool isSpecificBuiltinType(unsigned K) const;
1874
1875 /// Test for a type which does not represent an actual type-system type but
1876 /// is instead used as a placeholder for various convenient purposes within
1877 /// Clang. All such types are BuiltinTypes.
1878 bool isPlaceholderType() const;
1879 const BuiltinType *getAsPlaceholderType() const;
1880
1881 /// Test for a specific placeholder type.
1882 bool isSpecificPlaceholderType(unsigned K) const;
1883
1884 /// Test for a placeholder type other than Overload; see
1885 /// BuiltinType::isNonOverloadPlaceholderType.
1886 bool isNonOverloadPlaceholderType() const;
1887
1888 /// isIntegerType() does *not* include complex integers (a GCC extension).
1889 /// isComplexIntegerType() can be used to test for complex integers.
1890 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1891 bool isEnumeralType() const;
1892
1893 /// Determine whether this type is a scoped enumeration type.
1894 bool isScopedEnumeralType() const;
1895 bool isBooleanType() const;
1896 bool isCharType() const;
1897 bool isWideCharType() const;
1898 bool isChar8Type() const;
1899 bool isChar16Type() const;
1900 bool isChar32Type() const;
1901 bool isAnyCharacterType() const;
1902 bool isIntegralType(const ASTContext &Ctx) const;
1903
1904 /// Determine whether this type is an integral or enumeration type.
1905 bool isIntegralOrEnumerationType() const;
1906
1907 /// Determine whether this type is an integral or unscoped enumeration type.
1908 bool isIntegralOrUnscopedEnumerationType() const;
1909
1910 /// Floating point categories.
1911 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1912 /// isComplexType() does *not* include complex integers (a GCC extension).
1913 /// isComplexIntegerType() can be used to test for complex integers.
1914 bool isComplexType() const; // C99 6.2.5p11 (complex)
1915 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1916 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1917 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1918 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1919 bool isFloat128Type() const;
1920 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1921 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1922 bool isVoidType() const; // C99 6.2.5p19
1923 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1924 bool isAggregateType() const;
1925 bool isFundamentalType() const;
1926 bool isCompoundType() const;
1927
1928 // Type Predicates: Check to see if this type is structurally the specified
1929 // type, ignoring typedefs and qualifiers.
1930 bool isFunctionType() const;
1931 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1932 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1933 bool isPointerType() const;
1934 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1935 bool isBlockPointerType() const;
1936 bool isVoidPointerType() const;
1937 bool isReferenceType() const;
1938 bool isLValueReferenceType() const;
1939 bool isRValueReferenceType() const;
1940 bool isFunctionPointerType() const;
1941 bool isMemberPointerType() const;
1942 bool isMemberFunctionPointerType() const;
1943 bool isMemberDataPointerType() const;
1944 bool isArrayType() const;
1945 bool isConstantArrayType() const;
1946 bool isIncompleteArrayType() const;
1947 bool isVariableArrayType() const;
1948 bool isDependentSizedArrayType() const;
1949 bool isRecordType() const;
1950 bool isClassType() const;
1951 bool isStructureType() const;
1952 bool isObjCBoxableRecordType() const;
1953 bool isInterfaceType() const;
1954 bool isStructureOrClassType() const;
1955 bool isUnionType() const;
1956 bool isComplexIntegerType() const; // GCC _Complex integer type.
1957 bool isVectorType() const; // GCC vector type.
1958 bool isExtVectorType() const; // Extended vector type.
1959 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
1960 bool isObjCObjectPointerType() const; // pointer to ObjC object
1961 bool isObjCRetainableType() const; // ObjC object or block pointer
1962 bool isObjCLifetimeType() const; // (array of)* retainable type
1963 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
1964 bool isObjCNSObjectType() const; // __attribute__((NSObject))
1965 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
1966 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1967 // for the common case.
1968 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
1969 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
1970 bool isObjCQualifiedIdType() const; // id<foo>
1971 bool isObjCQualifiedClassType() const; // Class<foo>
1972 bool isObjCObjectOrInterfaceType() const;
1973 bool isObjCIdType() const; // id
1974
1975 /// Was this type written with the special inert-in-ARC __unsafe_unretained
1976 /// qualifier?
1977 ///
1978 /// This approximates the answer to the following question: if this
1979 /// translation unit were compiled in ARC, would this type be qualified
1980 /// with __unsafe_unretained?
1981 bool isObjCInertUnsafeUnretainedType() const {
1982 return hasAttr(attr::ObjCInertUnsafeUnretained);
1983 }
1984
1985 /// Whether the type is Objective-C 'id' or a __kindof type of an
1986 /// object type, e.g., __kindof NSView * or __kindof id
1987 /// <NSCopying>.
1988 ///
1989 /// \param bound Will be set to the bound on non-id subtype types,
1990 /// which will be (possibly specialized) Objective-C class type, or
1991 /// null for 'id.
1992 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
1993 const ObjCObjectType *&bound) const;
1994
1995 bool isObjCClassType() const; // Class
1996
1997 /// Whether the type is Objective-C 'Class' or a __kindof type of an
1998 /// Class type, e.g., __kindof Class <NSCopying>.
1999 ///
2000 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2001 /// here because Objective-C's type system cannot express "a class
2002 /// object for a subclass of NSFoo".
2003 bool isObjCClassOrClassKindOfType() const;
2004
2005 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2006 bool isObjCSelType() const; // Class
2007 bool isObjCBuiltinType() const; // 'id' or 'Class'
2008 bool isObjCARCBridgableType() const;
2009 bool isCARCBridgableType() const;
2010 bool isTemplateTypeParmType() const; // C++ template type parameter
2011 bool isNullPtrType() const; // C++11 std::nullptr_t
2012 bool isAlignValT() const; // C++17 std::align_val_t
2013 bool isStdByteType() const; // C++17 std::byte
2014 bool isAtomicType() const; // C11 _Atomic()
2015
2016#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2017 bool is##Id##Type() const;
2018#include "clang/Basic/OpenCLImageTypes.def"
2019
2020 bool isImageType() const; // Any OpenCL image type
2021
2022 bool isSamplerT() const; // OpenCL sampler_t
2023 bool isEventT() const; // OpenCL event_t
2024 bool isClkEventT() const; // OpenCL clk_event_t
2025 bool isQueueT() const; // OpenCL queue_t
2026 bool isReserveIDT() const; // OpenCL reserve_id_t
2027
2028 bool isPipeType() const; // OpenCL pipe type
2029 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2030
2031 /// Determines if this type, which must satisfy
2032 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2033 /// than implicitly __strong.
2034 bool isObjCARCImplicitlyUnretainedType() const;
2035
2036 /// Return the implicit lifetime for this type, which must not be dependent.
2037 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2038
2039 enum ScalarTypeKind {
2040 STK_CPointer,
2041 STK_BlockPointer,
2042 STK_ObjCObjectPointer,
2043 STK_MemberPointer,
2044 STK_Bool,
2045 STK_Integral,
2046 STK_Floating,
2047 STK_IntegralComplex,
2048 STK_FloatingComplex
2049 };
2050
2051 /// Given that this is a scalar type, classify it.
2052 ScalarTypeKind getScalarTypeKind() const;
2053
2054 /// Whether this type is a dependent type, meaning that its definition
2055 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2056 bool isDependentType() const { return TypeBits.Dependent; }
2057
2058 /// Determine whether this type is an instantiation-dependent type,
2059 /// meaning that the type involves a template parameter (even if the
2060 /// definition does not actually depend on the type substituted for that
2061 /// template parameter).
2062 bool isInstantiationDependentType() const {
2063 return TypeBits.InstantiationDependent;
2064 }
2065
2066 /// Determine whether this type is an undeduced type, meaning that
2067 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2068 /// deduced.
2069 bool isUndeducedType() const;
2070
2071 /// Whether this type is a variably-modified type (C99 6.7.5).
2072 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
2073
2074 /// Whether this type involves a variable-length array type
2075 /// with a definite size.
2076 bool hasSizedVLAType() const;
2077
2078 /// Whether this type is or contains a local or unnamed type.
2079 bool hasUnnamedOrLocalType() const;
2080
2081 bool isOverloadableType() const;
2082
2083 /// Determine wither this type is a C++ elaborated-type-specifier.
2084 bool isElaboratedTypeSpecifier() const;
2085
2086 bool canDecayToPointerType() const;
2087
2088 /// Whether this type is represented natively as a pointer. This includes
2089 /// pointers, references, block pointers, and Objective-C interface,
2090 /// qualified id, and qualified interface types, as well as nullptr_t.
2091 bool hasPointerRepresentation() const;
2092
2093 /// Whether this type can represent an objective pointer type for the
2094 /// purpose of GC'ability
2095 bool hasObjCPointerRepresentation() const;
2096
2097 /// Determine whether this type has an integer representation
2098 /// of some sort, e.g., it is an integer type or a vector.
2099 bool hasIntegerRepresentation() const;
2100
2101 /// Determine whether this type has an signed integer representation
2102 /// of some sort, e.g., it is an signed integer type or a vector.
2103 bool hasSignedIntegerRepresentation() const;
2104
2105 /// Determine whether this type has an unsigned integer representation
2106 /// of some sort, e.g., it is an unsigned integer type or a vector.
2107 bool hasUnsignedIntegerRepresentation() const;
2108
2109 /// Determine whether this type has a floating-point representation
2110 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2111 bool hasFloatingRepresentation() const;
2112
2113 // Type Checking Functions: Check to see if this type is structurally the
2114 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2115 // the best type we can.
2116 const RecordType *getAsStructureType() const;
2117 /// NOTE: getAs*ArrayType are methods on ASTContext.
2118 const RecordType *getAsUnionType() const;
2119 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2120 const ObjCObjectType *getAsObjCInterfaceType() const;
2121
2122 // The following is a convenience method that returns an ObjCObjectPointerType
2123 // for object declared using an interface.
2124 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2125 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2126 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2127 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2128
2129 /// Retrieves the CXXRecordDecl that this type refers to, either
2130 /// because the type is a RecordType or because it is the injected-class-name
2131 /// type of a class template or class template partial specialization.
2132 CXXRecordDecl *getAsCXXRecordDecl() const;
2133
2134 /// Retrieves the RecordDecl this type refers to.
2135 RecordDecl *getAsRecordDecl() const;
2136
2137 /// Retrieves the TagDecl that this type refers to, either
2138 /// because the type is a TagType or because it is the injected-class-name
2139 /// type of a class template or class template partial specialization.
2140 TagDecl *getAsTagDecl() const;
2141
2142 /// If this is a pointer or reference to a RecordType, return the
2143 /// CXXRecordDecl that the type refers to.
2144 ///
2145 /// If this is not a pointer or reference, or the type being pointed to does
2146 /// not refer to a CXXRecordDecl, returns NULL.
2147 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2148
2149 /// Get the DeducedType whose type will be deduced for a variable with
2150 /// an initializer of this type. This looks through declarators like pointer
2151 /// types, but not through decltype or typedefs.
2152 DeducedType *getContainedDeducedType() const;
2153
2154 /// Get the AutoType whose type will be deduced for a variable with
2155 /// an initializer of this type. This looks through declarators like pointer
2156 /// types, but not through decltype or typedefs.
2157 AutoType *getContainedAutoType() const {
2158 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2159 }
2160
2161 /// Determine whether this type was written with a leading 'auto'
2162 /// corresponding to a trailing return type (possibly for a nested
2163 /// function type within a pointer to function type or similar).
2164 bool hasAutoForTrailingReturnType() const;
2165
2166 /// Member-template getAs<specific type>'. Look through sugar for
2167 /// an instance of \<specific type>. This scheme will eventually
2168 /// replace the specific getAsXXXX methods above.
2169 ///
2170 /// There are some specializations of this member template listed
2171 /// immediately following this class.
2172 template <typename T> const T *getAs() const;
2173
2174 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2175 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2176 /// This is used when you need to walk over sugar nodes that represent some
2177 /// kind of type adjustment from a type that was written as a \<specific type>
2178 /// to another type that is still canonically a \<specific type>.
2179 template <typename T> const T *getAsAdjusted() const;
2180
2181 /// A variant of getAs<> for array types which silently discards
2182 /// qualifiers from the outermost type.
2183 const ArrayType *getAsArrayTypeUnsafe() const;
2184
2185 /// Member-template castAs<specific type>. Look through sugar for
2186 /// the underlying instance of \<specific type>.
2187 ///
2188 /// This method has the same relationship to getAs<T> as cast<T> has
2189 /// to dyn_cast<T>; which is to say, the underlying type *must*
2190 /// have the intended type, and this method will never return null.
2191 template <typename T> const T *castAs() const;
2192
2193 /// A variant of castAs<> for array type which silently discards
2194 /// qualifiers from the outermost type.
2195 const ArrayType *castAsArrayTypeUnsafe() const;
2196
2197 /// Determine whether this type had the specified attribute applied to it
2198 /// (looking through top-level type sugar).
2199 bool hasAttr(attr::Kind AK) const;
2200
2201 /// Get the base element type of this type, potentially discarding type
2202 /// qualifiers. This should never be used when type qualifiers
2203 /// are meaningful.
2204 const Type *getBaseElementTypeUnsafe() const;
2205
2206 /// If this is an array type, return the element type of the array,
2207 /// potentially with type qualifiers missing.
2208 /// This should never be used when type qualifiers are meaningful.
2209 const Type *getArrayElementTypeNoTypeQual() const;
2210
2211 /// If this is a pointer type, return the pointee type.
2212 /// If this is an array type, return the array element type.
2213 /// This should never be used when type qualifiers are meaningful.
2214 const Type *getPointeeOrArrayElementType() const;
2215
2216 /// If this is a pointer, ObjC object pointer, or block
2217 /// pointer, this returns the respective pointee.
2218 QualType getPointeeType() const;
2219
2220 /// Return the specified type with any "sugar" removed from the type,
2221 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2222 const Type *getUnqualifiedDesugaredType() const;
2223
2224 /// More type predicates useful for type checking/promotion
2225 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2226
2227 /// Return true if this is an integer type that is
2228 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2229 /// or an enum decl which has a signed representation.
2230 bool isSignedIntegerType() const;
2231
2232 /// Return true if this is an integer type that is
2233 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2234 /// or an enum decl which has an unsigned representation.
2235 bool isUnsignedIntegerType() const;
2236
2237 /// Determines whether this is an integer type that is signed or an
2238 /// enumeration types whose underlying type is a signed integer type.
2239 bool isSignedIntegerOrEnumerationType() const;
2240
2241 /// Determines whether this is an integer type that is unsigned or an
2242 /// enumeration types whose underlying type is a unsigned integer type.
2243 bool isUnsignedIntegerOrEnumerationType() const;
2244
2245 /// Return true if this is a fixed point type according to
2246 /// ISO/IEC JTC1 SC22 WG14 N1169.
2247 bool isFixedPointType() const;
2248
2249 /// Return true if this is a saturated fixed point type according to
2250 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2251 bool isSaturatedFixedPointType() const;
2252
2253 /// Return true if this is a saturated fixed point type according to
2254 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2255 bool isUnsaturatedFixedPointType() const;
2256
2257 /// Return true if this is a fixed point type that is signed according
2258 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2259 bool isSignedFixedPointType() const;
2260
2261 /// Return true if this is a fixed point type that is unsigned according
2262 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2263 bool isUnsignedFixedPointType() const;
2264
2265 /// Return true if this is not a variable sized type,
2266 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2267 /// incomplete types.
2268 bool isConstantSizeType() const;
2269
2270 /// Returns true if this type can be represented by some
2271 /// set of type specifiers.
2272 bool isSpecifierType() const;
2273
2274 /// Determine the linkage of this type.
2275 Linkage getLinkage() const;
2276
2277 /// Determine the visibility of this type.
2278 Visibility getVisibility() const {
2279 return getLinkageAndVisibility().getVisibility();
2280 }
2281
2282 /// Return true if the visibility was explicitly set is the code.
2283 bool isVisibilityExplicit() const {
2284 return getLinkageAndVisibility().isVisibilityExplicit();
2285 }
2286
2287 /// Determine the linkage and visibility of this type.
2288 LinkageInfo getLinkageAndVisibility() const;
2289
2290 /// True if the computed linkage is valid. Used for consistency
2291 /// checking. Should always return true.
2292 bool isLinkageValid() const;
2293
2294 /// Determine the nullability of the given type.
2295 ///
2296 /// Note that nullability is only captured as sugar within the type
2297 /// system, not as part of the canonical type, so nullability will
2298 /// be lost by canonicalization and desugaring.
2299 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2300
2301 /// Determine whether the given type can have a nullability
2302 /// specifier applied to it, i.e., if it is any kind of pointer type.
2303 ///
2304 /// \param ResultIfUnknown The value to return if we don't yet know whether
2305 /// this type can have nullability because it is dependent.
2306 bool canHaveNullability(bool ResultIfUnknown = true) const;
2307
2308 /// Retrieve the set of substitutions required when accessing a member
2309 /// of the Objective-C receiver type that is declared in the given context.
2310 ///
2311 /// \c *this is the type of the object we're operating on, e.g., the
2312 /// receiver for a message send or the base of a property access, and is
2313 /// expected to be of some object or object pointer type.
2314 ///
2315 /// \param dc The declaration context for which we are building up a
2316 /// substitution mapping, which should be an Objective-C class, extension,
2317 /// category, or method within.
2318 ///
2319 /// \returns an array of type arguments that can be substituted for
2320 /// the type parameters of the given declaration context in any type described
2321 /// within that context, or an empty optional to indicate that no
2322 /// substitution is required.
2323 Optional<ArrayRef<QualType>>
2324 getObjCSubstitutions(const DeclContext *dc) const;
2325
2326 /// Determines if this is an ObjC interface type that may accept type
2327 /// parameters.
2328 bool acceptsObjCTypeParams() const;
2329
2330 const char *getTypeClassName() const;
2331
2332 QualType getCanonicalTypeInternal() const {
2333 return CanonicalType;
2334 }
2335
2336 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2337 void dump() const;
2338 void dump(llvm::raw_ostream &OS) const;
2339};
2340
2341/// This will check for a TypedefType by removing any existing sugar
2342/// until it reaches a TypedefType or a non-sugared type.
2343template <> const TypedefType *Type::getAs() const;
2344
2345/// This will check for a TemplateSpecializationType by removing any
2346/// existing sugar until it reaches a TemplateSpecializationType or a
2347/// non-sugared type.
2348template <> const TemplateSpecializationType *Type::getAs() const;
2349
2350/// This will check for an AttributedType by removing any existing sugar
2351/// until it reaches an AttributedType or a non-sugared type.
2352template <> const AttributedType *Type::getAs() const;
2353
2354// We can do canonical leaf types faster, because we don't have to
2355// worry about preserving child type decoration.
2356#define TYPE(Class, Base)
2357#define LEAF_TYPE(Class) \
2358template <> inline const Class##Type *Type::getAs() const { \
2359 return dyn_cast<Class##Type>(CanonicalType); \
2360} \
2361template <> inline const Class##Type *Type::castAs() const { \
2362 return cast<Class##Type>(CanonicalType); \
2363}
2364#include "clang/AST/TypeNodes.def"
2365
2366/// This class is used for builtin types like 'int'. Builtin
2367/// types are always canonical and have a literal name field.
2368class BuiltinType : public Type {
2369public:
2370 enum Kind {
2371// OpenCL image types
2372#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2373#include "clang/Basic/OpenCLImageTypes.def"
2374// All other builtin types
2375#define BUILTIN_TYPE(Id, SingletonId) Id,
2376#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2377#include "clang/AST/BuiltinTypes.def"
2378 };
2379
2380private:
2381 friend class ASTContext; // ASTContext creates these.
2382
2383 BuiltinType(Kind K)
2384 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2385 /*InstantiationDependent=*/(K == Dependent),
2386 /*VariablyModified=*/false,
2387 /*Unexpanded parameter pack=*/false) {
2388 BuiltinTypeBits.Kind = K;
2389 }
2390
2391public:
2392 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2393 StringRef getName(const PrintingPolicy &Policy) const;
2394
2395 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2396 // The StringRef is null-terminated.
2397 StringRef str = getName(Policy);
2398 assert(!str.empty() && str.data()[str.size()] == '\0');
2399 return str.data();
2400 }
2401
2402 bool isSugared() const { return false; }
2403 QualType desugar() const { return QualType(this, 0); }
2404
2405 bool isInteger() const {
2406 return getKind() >= Bool && getKind() <= Int128;
2407 }
2408
2409 bool isSignedInteger() const {
2410 return getKind() >= Char_S && getKind() <= Int128;
2411 }
2412
2413 bool isUnsignedInteger() const {
2414 return getKind() >= Bool && getKind() <= UInt128;
2415 }
2416
2417 bool isFloatingPoint() const {
2418 return getKind() >= Half && getKind() <= Float128;
2419 }
2420
2421 /// Determines whether the given kind corresponds to a placeholder type.
2422 static bool isPlaceholderTypeKind(Kind K) {
2423 return K >= Overload;
2424 }
2425
2426 /// Determines whether this type is a placeholder type, i.e. a type
2427 /// which cannot appear in arbitrary positions in a fully-formed
2428 /// expression.
2429 bool isPlaceholderType() const {
2430 return isPlaceholderTypeKind(getKind());
2431 }
2432
2433 /// Determines whether this type is a placeholder type other than
2434 /// Overload. Most placeholder types require only syntactic
2435 /// information about their context in order to be resolved (e.g.
2436 /// whether it is a call expression), which means they can (and
2437 /// should) be resolved in an earlier "phase" of analysis.
2438 /// Overload expressions sometimes pick up further information
2439 /// from their context, like whether the context expects a
2440 /// specific function-pointer type, and so frequently need
2441 /// special treatment.
2442 bool isNonOverloadPlaceholderType() const {
2443 return getKind() > Overload;
2444 }
2445
2446 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2447};
2448
2449/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2450/// types (_Complex float etc) as well as the GCC integer complex extensions.
2451class ComplexType : public Type, public llvm::FoldingSetNode {
2452 friend class ASTContext; // ASTContext creates these.
2453
2454 QualType ElementType;
2455
2456 ComplexType(QualType Element, QualType CanonicalPtr)
2457 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2458 Element->isInstantiationDependentType(),
2459 Element->isVariablyModifiedType(),
2460 Element->containsUnexpandedParameterPack()),
2461 ElementType(Element) {}
2462
2463public:
2464 QualType getElementType() const { return ElementType; }
2465
2466 bool isSugared() const { return false; }
2467 QualType desugar() const { return QualType(this, 0); }
2468
2469 void Profile(llvm::FoldingSetNodeID &ID) {
2470 Profile(ID, getElementType());
2471 }
2472
2473 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2474 ID.AddPointer(Element.getAsOpaquePtr());
2475 }
2476
2477 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2478};
2479
2480/// Sugar for parentheses used when specifying types.
2481class ParenType : public Type, public llvm::FoldingSetNode {
2482 friend class ASTContext; // ASTContext creates these.
2483
2484 QualType Inner;
2485
2486 ParenType(QualType InnerType, QualType CanonType)
2487 : Type(Paren, CanonType, InnerType->isDependentType(),
2488 InnerType->isInstantiationDependentType(),
2489 InnerType->isVariablyModifiedType(),
2490 InnerType->containsUnexpandedParameterPack()),
2491 Inner(InnerType) {}
2492
2493public:
2494 QualType getInnerType() const { return Inner; }
2495
2496 bool isSugared() const { return true; }
2497 QualType desugar() const { return getInnerType(); }
2498
2499 void Profile(llvm::FoldingSetNodeID &ID) {
2500 Profile(ID, getInnerType());
2501 }
2502
2503 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2504 Inner.Profile(ID);
2505 }
2506
2507 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2508};
2509
2510/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2511class PointerType : public Type, public llvm::FoldingSetNode {
2512 friend class ASTContext; // ASTContext creates these.
2513
2514 QualType PointeeType;
2515
2516 PointerType(QualType Pointee, QualType CanonicalPtr)
2517 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2518 Pointee->isInstantiationDependentType(),
2519 Pointee->isVariablyModifiedType(),
2520 Pointee->containsUnexpandedParameterPack()),
2521 PointeeType(Pointee) {}
2522
2523public:
2524 QualType getPointeeType() const { return PointeeType; }
2525
2526 /// Returns true if address spaces of pointers overlap.
2527 /// OpenCL v2.0 defines conversion rules for pointers to different
2528 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2529 /// address spaces.
2530 /// CL1.1 or CL1.2:
2531 /// address spaces overlap iff they are they same.
2532 /// CL2.0 adds:
2533 /// __generic overlaps with any address space except for __constant.
2534 bool isAddressSpaceOverlapping(const PointerType &other) const {
2535 Qualifiers thisQuals = PointeeType.getQualifiers();
2536 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2537 // Address spaces overlap if at least one of them is a superset of another
2538 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2539 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2540 }
2541
2542 bool isSugared() const { return false; }
2543 QualType desugar() const { return QualType(this, 0); }
2544
2545 void Profile(llvm::FoldingSetNodeID &ID) {
2546 Profile(ID, getPointeeType());
2547 }
2548
2549 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2550 ID.AddPointer(Pointee.getAsOpaquePtr());
2551 }
2552
2553 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2554};
2555
2556/// Represents a type which was implicitly adjusted by the semantic
2557/// engine for arbitrary reasons. For example, array and function types can
2558/// decay, and function types can have their calling conventions adjusted.
2559class AdjustedType : public Type, public llvm::FoldingSetNode {
2560 QualType OriginalTy;
2561 QualType AdjustedTy;
2562
2563protected:
2564 friend class ASTContext; // ASTContext creates these.
2565
2566 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2567 QualType CanonicalPtr)
2568 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2569 OriginalTy->isInstantiationDependentType(),
2570 OriginalTy->isVariablyModifiedType(),
2571 OriginalTy->containsUnexpandedParameterPack()),
2572 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2573
2574public:
2575 QualType getOriginalType() const { return OriginalTy; }
2576 QualType getAdjustedType() const { return AdjustedTy; }
2577
2578 bool isSugared() const { return true; }
2579 QualType desugar() const { return AdjustedTy; }
2580
2581 void Profile(llvm::FoldingSetNodeID &ID) {
2582 Profile(ID, OriginalTy, AdjustedTy);
2583 }
2584
2585 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2586 ID.AddPointer(Orig.getAsOpaquePtr());
2587 ID.AddPointer(New.getAsOpaquePtr());
2588 }
2589
2590 static bool classof(const Type *T) {
2591 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2592 }
2593};
2594
2595/// Represents a pointer type decayed from an array or function type.
2596class DecayedType : public AdjustedType {
2597 friend class ASTContext; // ASTContext creates these.
2598
2599 inline
2600 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2601
2602public:
2603 QualType getDecayedType() const { return getAdjustedType(); }
2604
2605 inline QualType getPointeeType() const;
2606
2607 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2608};
2609
2610/// Pointer to a block type.
2611/// This type is to represent types syntactically represented as
2612/// "void (^)(int)", etc. Pointee is required to always be a function type.
2613class BlockPointerType : public Type, public llvm::FoldingSetNode {
2614 friend class ASTContext; // ASTContext creates these.
2615
2616 // Block is some kind of pointer type
2617 QualType PointeeType;
2618
2619 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2620 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2621 Pointee->isInstantiationDependentType(),
2622 Pointee->isVariablyModifiedType(),
2623 Pointee->containsUnexpandedParameterPack()),
2624 PointeeType(Pointee) {}
2625
2626public:
2627 // Get the pointee type. Pointee is required to always be a function type.
2628 QualType getPointeeType() const { return PointeeType; }
2629
2630 bool isSugared() const { return false; }
2631 QualType desugar() const { return QualType(this, 0); }
2632
2633 void Profile(llvm::FoldingSetNodeID &ID) {
2634 Profile(ID, getPointeeType());
2635 }
2636
2637 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2638 ID.AddPointer(Pointee.getAsOpaquePtr());
2639 }
2640
2641 static bool classof(const Type *T) {
2642 return T->getTypeClass() == BlockPointer;
2643 }
2644};
2645
2646/// Base for LValueReferenceType and RValueReferenceType
2647class ReferenceType : public Type, public llvm::FoldingSetNode {
2648 QualType PointeeType;
2649
2650protected:
2651 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2652 bool SpelledAsLValue)
2653 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2654 Referencee->isInstantiationDependentType(),
2655 Referencee->isVariablyModifiedType(),
2656 Referencee->containsUnexpandedParameterPack()),
2657 PointeeType(Referencee) {
2658 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2659 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2660 }
2661
2662public:
2663 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2664 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2665
2666 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2667
2668 QualType getPointeeType() const {
2669 // FIXME: this might strip inner qualifiers; okay?
2670 const ReferenceType *T = this;
2671 while (T->isInnerRef())
2672 T = T->PointeeType->castAs<ReferenceType>();
2673 return T->PointeeType;
2674 }
2675
2676 void Profile(llvm::FoldingSetNodeID &ID) {
2677 Profile(ID, PointeeType, isSpelledAsLValue());
2678 }
2679
2680 static void Profile(llvm::FoldingSetNodeID &ID,
2681 QualType Referencee,
2682 bool SpelledAsLValue) {
2683 ID.AddPointer(Referencee.getAsOpaquePtr());
2684 ID.AddBoolean(SpelledAsLValue);
2685 }
2686
2687 static bool classof(const Type *T) {
2688 return T->getTypeClass() == LValueReference ||
2689 T->getTypeClass() == RValueReference;
2690 }
2691};
2692
2693/// An lvalue reference type, per C++11 [dcl.ref].
2694class LValueReferenceType : public ReferenceType {
2695 friend class ASTContext; // ASTContext creates these
2696
2697 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2698 bool SpelledAsLValue)
2699 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2700 SpelledAsLValue) {}
2701
2702public:
2703 bool isSugared() const { return false; }
2704 QualType desugar() const { return QualType(this, 0); }
2705
2706 static bool classof(const Type *T) {
2707 return T->getTypeClass() == LValueReference;
2708 }
2709};
2710
2711/// An rvalue reference type, per C++11 [dcl.ref].
2712class RValueReferenceType : public ReferenceType {
2713 friend class ASTContext; // ASTContext creates these
2714
2715 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2716 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2717
2718public:
2719 bool isSugared() const { return false; }
2720 QualType desugar() const { return QualType(this, 0); }
2721
2722 static bool classof(const Type *T) {
2723 return T->getTypeClass() == RValueReference;
2724 }
2725};
2726
2727/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2728///
2729/// This includes both pointers to data members and pointer to member functions.
2730class MemberPointerType : public Type, public llvm::FoldingSetNode {
2731 friend class ASTContext; // ASTContext creates these.
2732
2733 QualType PointeeType;
2734
2735 /// The class of which the pointee is a member. Must ultimately be a
2736 /// RecordType, but could be a typedef or a template parameter too.
2737 const Type *Class;
2738
2739 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2740 : Type(MemberPointer, CanonicalPtr,
2741 Cls->isDependentType() || Pointee->isDependentType(),
2742 (Cls->isInstantiationDependentType() ||
2743 Pointee->isInstantiationDependentType()),
2744 Pointee->isVariablyModifiedType(),
2745 (Cls->containsUnexpandedParameterPack() ||
2746 Pointee->containsUnexpandedParameterPack())),
2747 PointeeType(Pointee), Class(Cls) {}
2748
2749public:
2750 QualType getPointeeType() const { return PointeeType; }
2751
2752 /// Returns true if the member type (i.e. the pointee type) is a
2753 /// function type rather than a data-member type.
2754 bool isMemberFunctionPointer() const {
2755 return PointeeType->isFunctionProtoType();
2756 }
2757
2758 /// Returns true if the member type (i.e. the pointee type) is a
2759 /// data type rather than a function type.
2760 bool isMemberDataPointer() const {
2761 return !PointeeType->isFunctionProtoType();
2762 }
2763
2764 const Type *getClass() const { return Class; }
2765 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2766
2767 bool isSugared() const { return false; }
2768 QualType desugar() const { return QualType(this, 0); }
2769
2770 void Profile(llvm::FoldingSetNodeID &ID) {
2771 Profile(ID, getPointeeType(), getClass());
2772 }
2773
2774 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2775 const Type *Class) {
2776 ID.AddPointer(Pointee.getAsOpaquePtr());
2777 ID.AddPointer(Class);
2778 }
2779
2780 static bool classof(const Type *T) {
2781 return T->getTypeClass() == MemberPointer;
2782 }
2783};
2784
2785/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2786class ArrayType : public Type, public llvm::FoldingSetNode {
2787public:
2788 /// Capture whether this is a normal array (e.g. int X[4])
2789 /// an array with a static size (e.g. int X[static 4]), or an array
2790 /// with a star size (e.g. int X[*]).
2791 /// 'static' is only allowed on function parameters.
2792 enum ArraySizeModifier {
2793 Normal, Static, Star
2794 };
2795
2796private:
2797 /// The element type of the array.
2798 QualType ElementType;
2799
2800protected:
2801 friend class ASTContext; // ASTContext creates these.
2802
2803 // C++ [temp.dep.type]p1:
2804 // A type is dependent if it is...
2805 // - an array type constructed from any dependent type or whose
2806 // size is specified by a constant expression that is
2807 // value-dependent,
2808 ArrayType(TypeClass tc, QualType et, QualType can,
2809 ArraySizeModifier sm, unsigned tq,
2810 bool ContainsUnexpandedParameterPack)
2811 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2812 et->isInstantiationDependentType() || tc == DependentSizedArray,
2813 (tc == VariableArray || et->isVariablyModifiedType()),
2814 ContainsUnexpandedParameterPack),
2815 ElementType(et) {
2816 ArrayTypeBits.IndexTypeQuals = tq;
2817 ArrayTypeBits.SizeModifier = sm;
2818 }
2819
2820public:
2821 QualType getElementType() const { return ElementType; }
2822
2823 ArraySizeModifier getSizeModifier() const {
2824 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2825 }
2826
2827 Qualifiers getIndexTypeQualifiers() const {
2828 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2829 }
2830
2831 unsigned getIndexTypeCVRQualifiers() const {
2832 return ArrayTypeBits.IndexTypeQuals;
2833 }
2834
2835 static bool classof(const Type *T) {
2836 return T->getTypeClass() == ConstantArray ||
2837 T->getTypeClass() == VariableArray ||
2838 T->getTypeClass() == IncompleteArray ||
2839 T->getTypeClass() == DependentSizedArray;
2840 }
2841};
2842
2843/// Represents the canonical version of C arrays with a specified constant size.
2844/// For example, the canonical type for 'int A[4 + 4*100]' is a
2845/// ConstantArrayType where the element type is 'int' and the size is 404.
2846class ConstantArrayType : public ArrayType {
2847 llvm::APInt Size; // Allows us to unique the type.
2848
2849 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2850 ArraySizeModifier sm, unsigned tq)
2851 : ArrayType(ConstantArray, et, can, sm, tq,
2852 et->containsUnexpandedParameterPack()),
2853 Size(size) {}
2854
2855protected:
2856 friend class ASTContext; // ASTContext creates these.
2857
2858 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2859 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2860 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2861 Size(size) {}
2862
2863public:
2864 const llvm::APInt &getSize() const { return Size; }
2865 bool isSugared() const { return false; }
2866 QualType desugar() const { return QualType(this, 0); }
2867
2868 /// Determine the number of bits required to address a member of
2869 // an array with the given element type and number of elements.
2870 static unsigned getNumAddressingBits(const ASTContext &Context,
2871 QualType ElementType,
2872 const llvm::APInt &NumElements);
2873
2874 /// Determine the maximum number of active bits that an array's size
2875 /// can require, which limits the maximum size of the array.
2876 static unsigned getMaxSizeBits(const ASTContext &Context);
2877
2878 void Profile(llvm::FoldingSetNodeID &ID) {
2879 Profile(ID, getElementType(), getSize(),
2880 getSizeModifier(), getIndexTypeCVRQualifiers());
2881 }
2882
2883 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2884 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2885 unsigned TypeQuals) {
2886 ID.AddPointer(ET.getAsOpaquePtr());
2887 ID.AddInteger(ArraySize.getZExtValue());
2888 ID.AddInteger(SizeMod);
2889 ID.AddInteger(TypeQuals);
2890 }
2891
2892 static bool classof(const Type *T) {
2893 return T->getTypeClass() == ConstantArray;
2894 }
2895};
2896
2897/// Represents a C array with an unspecified size. For example 'int A[]' has
2898/// an IncompleteArrayType where the element type is 'int' and the size is
2899/// unspecified.
2900class IncompleteArrayType : public ArrayType {
2901 friend class ASTContext; // ASTContext creates these.
2902
2903 IncompleteArrayType(QualType et, QualType can,
2904 ArraySizeModifier sm, unsigned tq)
2905 : ArrayType(IncompleteArray, et, can, sm, tq,
2906 et->containsUnexpandedParameterPack()) {}
2907
2908public:
2909 friend class StmtIteratorBase;
2910
2911 bool isSugared() const { return false; }
2912 QualType desugar() const { return QualType(this, 0); }
2913
2914 static bool classof(const Type *T) {
2915 return T->getTypeClass() == IncompleteArray;
2916 }
2917
2918 void Profile(llvm::FoldingSetNodeID &ID) {
2919 Profile(ID, getElementType(), getSizeModifier(),
2920 getIndexTypeCVRQualifiers());
2921 }
2922
2923 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2924 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2925 ID.AddPointer(ET.getAsOpaquePtr());
2926 ID.AddInteger(SizeMod);
2927 ID.AddInteger(TypeQuals);
2928 }
2929};
2930
2931/// Represents a C array with a specified size that is not an
2932/// integer-constant-expression. For example, 'int s[x+foo()]'.
2933/// Since the size expression is an arbitrary expression, we store it as such.
2934///
2935/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2936/// should not be: two lexically equivalent variable array types could mean
2937/// different things, for example, these variables do not have the same type
2938/// dynamically:
2939///
2940/// void foo(int x) {
2941/// int Y[x];
2942/// ++x;
2943/// int Z[x];
2944/// }
2945class VariableArrayType : public ArrayType {
2946 friend class ASTContext; // ASTContext creates these.
2947
2948 /// An assignment-expression. VLA's are only permitted within
2949 /// a function block.
2950 Stmt *SizeExpr;
2951
2952 /// The range spanned by the left and right array brackets.
2953 SourceRange Brackets;
2954
2955 VariableArrayType(QualType et, QualType can, Expr *e,
2956 ArraySizeModifier sm, unsigned tq,
2957 SourceRange brackets)
2958 : ArrayType(VariableArray, et, can, sm, tq,
2959 et->containsUnexpandedParameterPack()),
2960 SizeExpr((Stmt*) e), Brackets(brackets) {}
2961
2962public:
2963 friend class StmtIteratorBase;
2964
2965 Expr *getSizeExpr() const {
2966 // We use C-style casts instead of cast<> here because we do not wish
2967 // to have a dependency of Type.h on Stmt.h/Expr.h.
2968 return (Expr*) SizeExpr;
2969 }
2970
2971 SourceRange getBracketsRange() const { return Brackets; }
2972 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2973 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2974
2975 bool isSugared() const { return false; }
2976 QualType desugar() const { return QualType(this, 0); }
2977
2978 static bool classof(const Type *T) {
2979 return T->getTypeClass() == VariableArray;
2980 }
2981
2982 void Profile(llvm::FoldingSetNodeID &ID) {
2983 llvm_unreachable("Cannot unique VariableArrayTypes.");
2984 }
2985};
2986
2987/// Represents an array type in C++ whose size is a value-dependent expression.
2988///
2989/// For example:
2990/// \code
2991/// template<typename T, int Size>
2992/// class array {
2993/// T data[Size];
2994/// };
2995/// \endcode
2996///
2997/// For these types, we won't actually know what the array bound is
2998/// until template instantiation occurs, at which point this will
2999/// become either a ConstantArrayType or a VariableArrayType.
3000class DependentSizedArrayType : public ArrayType {
3001 friend class ASTContext; // ASTContext creates these.
3002
3003 const ASTContext &Context;
3004
3005 /// An assignment expression that will instantiate to the
3006 /// size of the array.
3007 ///
3008 /// The expression itself might be null, in which case the array
3009 /// type will have its size deduced from an initializer.
3010 Stmt *SizeExpr;
3011
3012 /// The range spanned by the left and right array brackets.
3013 SourceRange Brackets;
3014
3015 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3016 Expr *e, ArraySizeModifier sm, unsigned tq,
3017 SourceRange brackets);
3018
3019public:
3020 friend class StmtIteratorBase;
3021
3022 Expr *getSizeExpr() const {
3023 // We use C-style casts instead of cast<> here because we do not wish
3024 // to have a dependency of Type.h on Stmt.h/Expr.h.
3025 return (Expr*) SizeExpr;
3026 }
3027
3028 SourceRange getBracketsRange() const { return Brackets; }
3029 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3030 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3031
3032 bool isSugared() const { return false; }
3033 QualType desugar() const { return QualType(this, 0); }
3034
3035 static bool classof(const Type *T) {
3036 return T->getTypeClass() == DependentSizedArray;
3037 }
3038
3039 void Profile(llvm::FoldingSetNodeID &ID) {
3040 Profile(ID, Context, getElementType(),
3041 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3042 }
3043
3044 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3045 QualType ET, ArraySizeModifier SizeMod,
3046 unsigned TypeQuals, Expr *E);
3047};
3048
3049/// Represents an extended address space qualifier where the input address space
3050/// value is dependent. Non-dependent address spaces are not represented with a
3051/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3052///
3053/// For example:
3054/// \code
3055/// template<typename T, int AddrSpace>
3056/// class AddressSpace {
3057/// typedef T __attribute__((address_space(AddrSpace))) type;
3058/// }
3059/// \endcode
3060class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3061 friend class ASTContext;
3062
3063 const ASTContext &Context;
3064 Expr *AddrSpaceExpr;
3065 QualType PointeeType;
3066 SourceLocation loc;
3067
3068 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3069 QualType can, Expr *AddrSpaceExpr,
3070 SourceLocation loc);
3071
3072public:
3073 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3074 QualType getPointeeType() const { return PointeeType; }
3075 SourceLocation getAttributeLoc() const { return loc; }
3076
3077 bool isSugared() const { return false; }
3078 QualType desugar() const { return QualType(this, 0); }
3079
3080 static bool classof(const Type *T) {
3081 return T->getTypeClass() == DependentAddressSpace;
3082 }
3083
3084 void Profile(llvm::FoldingSetNodeID &ID) {
3085 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3086 }
3087
3088 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3089 QualType PointeeType, Expr *AddrSpaceExpr);
3090};
3091
3092/// Represents an extended vector type where either the type or size is
3093/// dependent.
3094///
3095/// For example:
3096/// \code
3097/// template<typename T, int Size>
3098/// class vector {
3099/// typedef T __attribute__((ext_vector_type(Size))) type;
3100/// }
3101/// \endcode
3102class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3103 friend class ASTContext;
3104
3105 const ASTContext &Context;
3106 Expr *SizeExpr;
3107
3108 /// The element type of the array.
3109 QualType ElementType;
3110
3111 SourceLocation loc;
3112
3113 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3114 QualType can, Expr *SizeExpr, SourceLocation loc);
3115
3116public:
3117 Expr *getSizeExpr() const { return SizeExpr; }
3118 QualType getElementType() const { return ElementType; }
3119 SourceLocation getAttributeLoc() const { return loc; }
3120
3121 bool isSugared() const { return false; }
3122 QualType desugar() const { return QualType(this, 0); }
3123
3124 static bool classof(const Type *T) {
3125 return T->getTypeClass() == DependentSizedExtVector;
3126 }
3127
3128 void Profile(llvm::FoldingSetNodeID &ID) {
3129 Profile(ID, Context, getElementType(), getSizeExpr());
3130 }
3131
3132 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3133 QualType ElementType, Expr *SizeExpr);
3134};
3135
3136
3137/// Represents a GCC generic vector type. This type is created using
3138/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3139/// bytes; or from an Altivec __vector or vector declaration.
3140/// Since the constructor takes the number of vector elements, the
3141/// client is responsible for converting the size into the number of elements.
3142class VectorType : public Type, public llvm::FoldingSetNode {
3143public:
3144 enum VectorKind {
3145 /// not a target-specific vector type
3146 GenericVector,
3147
3148 /// is AltiVec vector
3149 AltiVecVector,
3150
3151 /// is AltiVec 'vector Pixel'
3152 AltiVecPixel,
3153
3154 /// is AltiVec 'vector bool ...'
3155 AltiVecBool,
3156
3157 /// is ARM Neon vector
3158 NeonVector,
3159
3160 /// is ARM Neon polynomial vector
3161 NeonPolyVector
3162 };
3163
3164protected:
3165 friend class ASTContext; // ASTContext creates these.
3166
3167 /// The element type of the vector.
3168 QualType ElementType;
3169
3170 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3171 VectorKind vecKind);
3172
3173 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3174 QualType canonType, VectorKind vecKind);
3175
3176public:
3177 QualType getElementType() const { return ElementType; }
3178 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3179
3180 static bool isVectorSizeTooLarge(unsigned NumElements) {
3181 return NumElements > VectorTypeBitfields::MaxNumElements;
3182 }
3183
3184 bool isSugared() const { return false; }
3185 QualType desugar() const { return QualType(this, 0); }
3186
3187 VectorKind getVectorKind() const {
3188 return VectorKind(VectorTypeBits.VecKind);
3189 }
3190
3191 void Profile(llvm::FoldingSetNodeID &ID) {
3192 Profile(ID, getElementType(), getNumElements(),
3193 getTypeClass(), getVectorKind());
3194 }
3195
3196 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3197 unsigned NumElements, TypeClass TypeClass,
3198 VectorKind VecKind) {
3199 ID.AddPointer(ElementType.getAsOpaquePtr());
3200 ID.AddInteger(NumElements);
3201 ID.AddInteger(TypeClass);
3202 ID.AddInteger(VecKind);
3203 }
3204
3205 static bool classof(const Type *T) {
3206 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3207 }
3208};
3209
3210/// Represents a vector type where either the type or size is dependent.
3211////
3212/// For example:
3213/// \code
3214/// template<typename T, int Size>
3215/// class vector {
3216/// typedef T __attribute__((vector_size(Size))) type;
3217/// }
3218/// \endcode
3219class DependentVectorType : public Type, public llvm::FoldingSetNode {
3220 friend class ASTContext;
3221
3222 const ASTContext &Context;
3223 QualType ElementType;
3224 Expr *SizeExpr;
3225 SourceLocation Loc;
3226
3227 DependentVectorType(const ASTContext &Context, QualType ElementType,
3228 QualType CanonType, Expr *SizeExpr,
3229 SourceLocation Loc, VectorType::VectorKind vecKind);
3230
3231public:
3232 Expr *getSizeExpr() const { return SizeExpr; }
3233 QualType getElementType() const { return ElementType; }
3234 SourceLocation getAttributeLoc() const { return Loc; }
3235 VectorType::VectorKind getVectorKind() const {
3236 return VectorType::VectorKind(VectorTypeBits.VecKind);
3237 }
3238
3239 bool isSugared() const { return false; }
3240 QualType desugar() const { return QualType(this, 0); }
3241
3242 static bool classof(const Type *T) {
3243 return T->getTypeClass() == DependentVector;
3244 }
3245
3246 void Profile(llvm::FoldingSetNodeID &ID) {
3247 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3248 }
3249
3250 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3251 QualType ElementType, const Expr *SizeExpr,
3252 VectorType::VectorKind VecKind);
3253};
3254
3255/// ExtVectorType - Extended vector type. This type is created using
3256/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3257/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3258/// class enables syntactic extensions, like Vector Components for accessing
3259/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3260/// Shading Language).
3261class ExtVectorType : public VectorType {
3262 friend class ASTContext; // ASTContext creates these.
3263
3264 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3265 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3266
3267public:
3268 static int getPointAccessorIdx(char c) {
3269 switch (c) {
3270 default: return -1;
3271 case 'x': case 'r': return 0;
3272 case 'y': case 'g': return 1;
3273 case 'z': case 'b': return 2;
3274 case 'w': case 'a': return 3;
3275 }
3276 }
3277
3278 static int getNumericAccessorIdx(char c) {
3279 switch (c) {
3280 default: return -1;
3281 case '0': return 0;
3282 case '1': return 1;
3283 case '2': return 2;
3284 case '3': return 3;
3285 case '4': return 4;
3286 case '5': return 5;
3287 case '6': return 6;
3288 case '7': return 7;
3289 case '8': return 8;
3290 case '9': return 9;
3291 case 'A':
3292 case 'a': return 10;
3293 case 'B':
3294 case 'b': return 11;
3295 case 'C':
3296 case 'c': return 12;
3297 case 'D':
3298 case 'd': return 13;
3299 case 'E':
3300 case 'e': return 14;
3301 case 'F':
3302 case 'f': return 15;
3303 }
3304 }
3305
3306 static int getAccessorIdx(char c, bool isNumericAccessor) {
3307 if (isNumericAccessor)
3308 return getNumericAccessorIdx(c);
3309 else
3310 return getPointAccessorIdx(c);
3311 }
3312
3313 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3314 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3315 return unsigned(idx-1) < getNumElements();
3316 return false;
3317 }
3318
3319 bool isSugared() const { return false; }
3320 QualType desugar() const { return QualType(this, 0); }
3321
3322 static bool classof(const Type *T) {
3323 return T->getTypeClass() == ExtVector;
3324 }
3325};
3326
3327/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3328/// class of FunctionNoProtoType and FunctionProtoType.
3329class FunctionType : public Type {
3330 // The type returned by the function.
3331 QualType ResultType;
3332
3333public:
3334 /// A class which abstracts out some details necessary for
3335 /// making a call.
3336 ///
3337 /// It is not actually used directly for storing this information in
3338 /// a FunctionType, although FunctionType does currently use the
3339 /// same bit-pattern.
3340 ///
3341 // If you add a field (say Foo), other than the obvious places (both,
3342 // constructors, compile failures), what you need to update is
3343 // * Operator==
3344 // * getFoo
3345 // * withFoo
3346 // * functionType. Add Foo, getFoo.
3347 // * ASTContext::getFooType
3348 // * ASTContext::mergeFunctionTypes
3349 // * FunctionNoProtoType::Profile
3350 // * FunctionProtoType::Profile
3351 // * TypePrinter::PrintFunctionProto
3352 // * AST read and write
3353 // * Codegen
3354 class ExtInfo {
3355 friend class FunctionType;
3356
3357 // Feel free to rearrange or add bits, but if you go over 12,
3358 // you'll need to adjust both the Bits field below and
3359 // Type::FunctionTypeBitfields.
3360
3361 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3362 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3363 //
3364 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3365 enum { CallConvMask = 0x1F };
3366 enum { NoReturnMask = 0x20 };
3367 enum { ProducesResultMask = 0x40 };
3368 enum { NoCallerSavedRegsMask = 0x80 };
3369 enum { NoCfCheckMask = 0x800 };
3370 enum {
3371 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3372 NoCallerSavedRegsMask | NoCfCheckMask),
3373 RegParmOffset = 8
3374 }; // Assumed to be the last field
3375 uint16_t Bits = CC_C;
3376
3377 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3378
3379 public:
3380 // Constructor with no defaults. Use this when you know that you
3381 // have all the elements (when reading an AST file for example).
3382 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3383 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3384 assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
3385 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3386 (producesResult ? ProducesResultMask : 0) |
3387 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3388 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3389 (NoCfCheck ? NoCfCheckMask : 0);
3390 }
3391
3392 // Constructor with all defaults. Use when for example creating a
3393 // function known to use defaults.
3394 ExtInfo() = default;
3395
3396 // Constructor with just the calling convention, which is an important part
3397 // of the canonical type.
3398 ExtInfo(CallingConv CC) : Bits(CC) {}
3399
3400 bool getNoReturn() const { return Bits & NoReturnMask; }
3401 bool getProducesResult() const { return Bits & ProducesResultMask; }
3402 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3403 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3404 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3405
3406 unsigned getRegParm() const {
3407 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3408 if (RegParm > 0)
3409 --RegParm;
3410 return RegParm;
3411 }
3412
3413 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3414
3415 bool operator==(ExtInfo Other) const {
3416 return Bits == Other.Bits;
3417 }
3418 bool operator!=(ExtInfo Other) const {
3419 return Bits != Other.Bits;
3420 }
3421
3422 // Note that we don't have setters. That is by design, use
3423 // the following with methods instead of mutating these objects.
3424
3425 ExtInfo withNoReturn(bool noReturn) const {
3426 if (noReturn)
3427 return ExtInfo(Bits | NoReturnMask);
3428 else
3429 return ExtInfo(Bits & ~NoReturnMask);
3430 }
3431
3432 ExtInfo withProducesResult(bool producesResult) const {
3433 if (producesResult)
3434 return ExtInfo(Bits | ProducesResultMask);
3435 else
3436 return ExtInfo(Bits & ~ProducesResultMask);
3437 }
3438
3439 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3440 if (noCallerSavedRegs)
3441 return ExtInfo(Bits | NoCallerSavedRegsMask);
3442 else
3443 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3444 }
3445
3446 ExtInfo withNoCfCheck(bool noCfCheck) const {
3447 if (noCfCheck)
3448 return ExtInfo(Bits | NoCfCheckMask);
3449 else
3450 return ExtInfo(Bits & ~NoCfCheckMask);
3451 }
3452
3453 ExtInfo withRegParm(unsigned RegParm) const {
3454 assert(RegParm < 7 && "Invalid regparm value");
3455 return ExtInfo((Bits & ~RegParmMask) |
3456 ((RegParm + 1) << RegParmOffset));
3457 }
3458
3459 ExtInfo withCallingConv(CallingConv cc) const {
3460 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3461 }
3462
3463 void Profile(llvm::FoldingSetNodeID &ID) const {
3464 ID.AddInteger(Bits);
3465 }
3466 };
3467
3468protected:
3469 FunctionType(TypeClass tc, QualType res,
3470 QualType Canonical, bool Dependent,
3471 bool InstantiationDependent,
3472 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3473 ExtInfo Info)
3474 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3475 ContainsUnexpandedParameterPack),
3476 ResultType(res) {
3477 FunctionTypeBits.ExtInfo = Info.Bits;
3478 }
3479
3480 unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
3481
3482public:
3483 QualType getReturnType() const { return ResultType; }
3484
3485 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3486 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3487
3488 /// Determine whether this function type includes the GNU noreturn
3489 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3490 /// type.
3491 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3492
3493 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3494 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3495 bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
3496 bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
3497 bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
3498
3499 /// Determine the type of an expression that calls a function of
3500 /// this type.
3501 QualType getCallResultType(const ASTContext &Context) const {
3502 return getReturnType().getNonLValueExprType(Context);
3503 }
3504
3505 static StringRef getNameForCallConv(CallingConv CC);
3506
3507 static bool classof(const Type *T) {
3508 return T->getTypeClass() == FunctionNoProto ||
3509 T->getTypeClass() == FunctionProto;
3510 }
3511};
3512
3513/// Represents a K&R-style 'int foo()' function, which has
3514/// no information available about its arguments.
3515class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3516 friend class ASTContext; // ASTContext creates these.
3517
3518 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3519 : FunctionType(FunctionNoProto, Result, Canonical,
3520 /*Dependent=*/false, /*InstantiationDependent=*/false,
3521 Result->isVariablyModifiedType(),
3522 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3523
3524public:
3525 // No additional state past what FunctionType provides.
3526
3527 bool isSugared() const { return false; }
3528 QualType desugar() const { return QualType(this, 0); }
3529
3530 void Profile(llvm::FoldingSetNodeID &ID) {
3531 Profile(ID, getReturnType(), getExtInfo());
3532 }
3533
3534 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3535 ExtInfo Info) {
3536 Info.Profile(ID);
3537 ID.AddPointer(ResultType.getAsOpaquePtr());
3538 }
3539
3540 static bool classof(const Type *T) {
3541 return T->getTypeClass() == FunctionNoProto;
3542 }
3543};
3544
3545/// Represents a prototype with parameter type info, e.g.
3546/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3547/// parameters, not as having a single void parameter. Such a type can have an
3548/// exception specification, but this specification is not part of the canonical
3549/// type.
3550class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
3551public:
3552 /// Interesting information about a specific parameter that can't simply
3553 /// be reflected in parameter's type.
3554 ///
3555 /// It makes sense to model language features this way when there's some
3556 /// sort of parameter-specific override (such as an attribute) that
3557 /// affects how the function is called. For example, the ARC ns_consumed
3558 /// attribute changes whether a parameter is passed at +0 (the default)
3559 /// or +1 (ns_consumed). This must be reflected in the function type,
3560 /// but isn't really a change to the parameter type.
3561 ///
3562 /// One serious disadvantage of modelling language features this way is
3563 /// that they generally do not work with language features that attempt
3564 /// to destructure types. For example, template argument deduction will
3565 /// not be able to match a parameter declared as
3566 /// T (*)(U)
3567 /// against an argument of type
3568 /// void (*)(__attribute__((ns_consumed)) id)
3569 /// because the substitution of T=void, U=id into the former will
3570 /// not produce the latter.
3571 class ExtParameterInfo {
3572 enum {
3573 ABIMask = 0x0F,
3574 IsConsumed = 0x10,
3575 HasPassObjSize = 0x20,
3576 IsNoEscape = 0x40,
3577 };
3578 unsigned char Data = 0;
3579
3580 public:
3581 ExtParameterInfo() = default;
3582
3583 /// Return the ABI treatment of this parameter.
3584 ParameterABI getABI() const {
3585 return ParameterABI(Data & ABIMask);
3586 }
3587 ExtParameterInfo withABI(ParameterABI kind) const {
3588 ExtParameterInfo copy = *this;
3589 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3590 return copy;
3591 }
3592
3593 /// Is this parameter considered "consumed" by Objective-C ARC?
3594 /// Consumed parameters must have retainable object type.
3595 bool isConsumed() const {
3596 return (Data & IsConsumed);
3597 }
3598 ExtParameterInfo withIsConsumed(bool consumed) const {
3599 ExtParameterInfo copy = *this;
3600 if (consumed) {
3601 copy.Data |= IsConsumed;
3602 } else {
3603 copy.