1 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ASTContext interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Comment.h"
20 #include "clang/AST/CommentCommandTraits.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/Mangle.h"
28 #include "clang/AST/MangleNumberingContext.h"
29 #include "clang/AST/RecordLayout.h"
30 #include "clang/AST/RecursiveASTVisitor.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/AST/VTableBuilder.h"
33 #include "clang/Basic/Builtins.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/Triple.h"
39 #include "llvm/Support/Capacity.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
44 using namespace clang;
46 unsigned ASTContext::NumImplicitDefaultConstructors;
47 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
48 unsigned ASTContext::NumImplicitCopyConstructors;
49 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
50 unsigned ASTContext::NumImplicitMoveConstructors;
51 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
52 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
54 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
56 unsigned ASTContext::NumImplicitDestructors;
57 unsigned ASTContext::NumImplicitDestructorsDeclared;
60 HalfRank, FloatRank, DoubleRank, LongDoubleRank
63 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
64 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
73 CommentsLoaded = true;
78 // User can not attach documentation to implicit declarations.
82 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
88 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
99 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
121 // TODO: we could look up template parameter documentation in the template
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
128 ArrayRef<RawComment *> RawComments = Comments.getComments();
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
142 isa<ObjCPropertyDecl>(D) ||
143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
145 DeclLoc = D->getLocStart();
147 DeclLoc = D->getLocation();
148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
172 // Find the comment that occurs just after this declaration.
173 ArrayRef<RawComment *>::iterator Comment;
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
200 // Decompose the location for the declaration and find the beginning of the
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
209 std::pair<FileID, unsigned> CommentBeginDecomp
210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
227 // Check that we actually have a non-member Doxygen comment.
228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
235 // If the comment and the declaration aren't in the same file, then they
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
253 if (Text.find_first_of(";{}#@") != StringRef::npos)
260 /// If we have a 'templated' declaration for a template, adjust 'D' to
261 /// refer to the actual template.
262 /// If we have an implicit instantiation, adjust 'D' to refer to template.
263 const Decl *adjustDeclToTemplate(const Decl *D) {
264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
265 // Is this function declaration part of a function template?
266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
298 // Class is an implicit instantiation of a class template or partial
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
327 // FIXME: Adjust alias templates?
330 } // unnamed namespace
332 const RawComment *ASTContext::getRawCommentForAnyRedecl(
334 const Decl **OriginalDecl) const {
335 D = adjustDeclToTemplate(D);
337 // Check whether we have cached a comment for this declaration already.
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
345 *OriginalDecl = Raw.getOriginalDecl();
351 // Search for comments attached to declarations in the redeclaration chain.
352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
354 for (auto I : D->redecls()) {
355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
356 RedeclComments.find(I);
357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
361 OriginalDeclForRC = Raw.getOriginalDecl();
365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
367 RawCommentAndCacheFlags Raw;
370 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
372 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
373 Raw.setOriginalDecl(I);
374 RedeclComments[I] = Raw;
380 // If we found a comment, it should be a documentation comment.
381 assert(!RC || RC->isDocumentation());
384 *OriginalDecl = OriginalDeclForRC;
386 // Update cache for every declaration in the redeclaration chain.
387 RawCommentAndCacheFlags Raw;
389 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
390 Raw.setOriginalDecl(OriginalDeclForRC);
392 for (auto I : D->redecls()) {
393 RawCommentAndCacheFlags &R = RedeclComments[I];
394 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
401 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
402 SmallVectorImpl<const NamedDecl *> &Redeclared) {
403 const DeclContext *DC = ObjCMethod->getDeclContext();
404 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
405 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
408 // Add redeclared method here.
409 for (const auto *Ext : ID->known_extensions()) {
410 if (ObjCMethodDecl *RedeclaredMethod =
411 Ext->getMethod(ObjCMethod->getSelector(),
412 ObjCMethod->isInstanceMethod()))
413 Redeclared.push_back(RedeclaredMethod);
418 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
419 const Decl *D) const {
420 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
421 ThisDeclInfo->CommentDecl = D;
422 ThisDeclInfo->IsFilled = false;
423 ThisDeclInfo->fill();
424 ThisDeclInfo->CommentDecl = FC->getDecl();
425 if (!ThisDeclInfo->TemplateParameters)
426 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
427 comments::FullComment *CFC =
428 new (*this) comments::FullComment(FC->getBlocks(),
434 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
435 const RawComment *RC = getRawCommentForDeclNoCache(D);
436 return RC ? RC->parse(*this, nullptr, D) : nullptr;
439 comments::FullComment *ASTContext::getCommentForDecl(
441 const Preprocessor *PP) const {
442 if (D->isInvalidDecl())
444 D = adjustDeclToTemplate(D);
446 const Decl *Canonical = D->getCanonicalDecl();
447 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
448 ParsedComments.find(Canonical);
450 if (Pos != ParsedComments.end()) {
451 if (Canonical != D) {
452 comments::FullComment *FC = Pos->second;
453 comments::FullComment *CFC = cloneFullComment(FC, D);
459 const Decl *OriginalDecl;
461 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
463 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
464 SmallVector<const NamedDecl*, 8> Overridden;
465 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
466 if (OMD && OMD->isPropertyAccessor())
467 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
468 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
469 return cloneFullComment(FC, D);
471 addRedeclaredMethods(OMD, Overridden);
472 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
473 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
474 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
475 return cloneFullComment(FC, D);
477 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
478 // Attach any tag type's documentation to its typedef if latter
479 // does not have one of its own.
480 QualType QT = TD->getUnderlyingType();
481 if (const TagType *TT = QT->getAs<TagType>())
482 if (const Decl *TD = TT->getDecl())
483 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
484 return cloneFullComment(FC, D);
486 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
487 while (IC->getSuperClass()) {
488 IC = IC->getSuperClass();
489 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
490 return cloneFullComment(FC, D);
493 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
494 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
495 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
496 return cloneFullComment(FC, D);
498 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
499 if (!(RD = RD->getDefinition()))
501 // Check non-virtual bases.
502 for (const auto &I : RD->bases()) {
503 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
505 QualType Ty = I.getType();
508 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
509 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
512 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
513 return cloneFullComment(FC, D);
516 // Check virtual bases.
517 for (const auto &I : RD->vbases()) {
518 if (I.getAccessSpecifier() != AS_public)
520 QualType Ty = I.getType();
523 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
524 if (!(VirtualBase= VirtualBase->getDefinition()))
526 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
527 return cloneFullComment(FC, D);
534 // If the RawComment was attached to other redeclaration of this Decl, we
535 // should parse the comment in context of that other Decl. This is important
536 // because comments can contain references to parameter names which can be
537 // different across redeclarations.
538 if (D != OriginalDecl)
539 return getCommentForDecl(OriginalDecl, PP);
541 comments::FullComment *FC = RC->parse(*this, PP, D);
542 ParsedComments[Canonical] = FC;
547 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
548 TemplateTemplateParmDecl *Parm) {
549 ID.AddInteger(Parm->getDepth());
550 ID.AddInteger(Parm->getPosition());
551 ID.AddBoolean(Parm->isParameterPack());
553 TemplateParameterList *Params = Parm->getTemplateParameters();
554 ID.AddInteger(Params->size());
555 for (TemplateParameterList::const_iterator P = Params->begin(),
556 PEnd = Params->end();
558 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
560 ID.AddBoolean(TTP->isParameterPack());
564 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
566 ID.AddBoolean(NTTP->isParameterPack());
567 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
568 if (NTTP->isExpandedParameterPack()) {
570 ID.AddInteger(NTTP->getNumExpansionTypes());
571 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
572 QualType T = NTTP->getExpansionType(I);
573 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
576 ID.AddBoolean(false);
580 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
586 TemplateTemplateParmDecl *
587 ASTContext::getCanonicalTemplateTemplateParmDecl(
588 TemplateTemplateParmDecl *TTP) const {
589 // Check if we already have a canonical template template parameter.
590 llvm::FoldingSetNodeID ID;
591 CanonicalTemplateTemplateParm::Profile(ID, TTP);
592 void *InsertPos = nullptr;
593 CanonicalTemplateTemplateParm *Canonical
594 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
596 return Canonical->getParam();
598 // Build a canonical template parameter list.
599 TemplateParameterList *Params = TTP->getTemplateParameters();
600 SmallVector<NamedDecl *, 4> CanonParams;
601 CanonParams.reserve(Params->size());
602 for (TemplateParameterList::const_iterator P = Params->begin(),
603 PEnd = Params->end();
605 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
606 CanonParams.push_back(
607 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
611 TTP->getIndex(), nullptr, false,
612 TTP->isParameterPack()));
613 else if (NonTypeTemplateParmDecl *NTTP
614 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
615 QualType T = getCanonicalType(NTTP->getType());
616 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
617 NonTypeTemplateParmDecl *Param;
618 if (NTTP->isExpandedParameterPack()) {
619 SmallVector<QualType, 2> ExpandedTypes;
620 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
621 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
623 ExpandedTInfos.push_back(
624 getTrivialTypeSourceInfo(ExpandedTypes.back()));
627 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
631 NTTP->getPosition(), nullptr,
634 ExpandedTypes.data(),
635 ExpandedTypes.size(),
636 ExpandedTInfos.data());
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
642 NTTP->getPosition(), nullptr,
644 NTTP->isParameterPack(),
647 CanonParams.push_back(Param);
650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
654 TemplateTemplateParmDecl *CanonTTP
655 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
656 SourceLocation(), TTP->getDepth(),
658 TTP->isParameterPack(),
660 TemplateParameterList::Create(*this, SourceLocation(),
666 // Get the new insert position for the node we care about.
667 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
668 assert(!Canonical && "Shouldn't be in the map!");
671 // Create the canonical template template parameter entry.
672 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
673 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
677 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
678 if (!LangOpts.CPlusPlus) return nullptr;
680 switch (T.getCXXABI().getKind()) {
681 case TargetCXXABI::GenericARM: // Same as Itanium at this level
682 case TargetCXXABI::iOS:
683 case TargetCXXABI::iOS64:
684 case TargetCXXABI::GenericAArch64:
685 case TargetCXXABI::GenericMIPS:
686 case TargetCXXABI::GenericItanium:
687 return CreateItaniumCXXABI(*this);
688 case TargetCXXABI::Microsoft:
689 return CreateMicrosoftCXXABI(*this);
691 llvm_unreachable("Invalid CXXABI type!");
694 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
695 const LangOptions &LOpts) {
696 if (LOpts.FakeAddressSpaceMap) {
697 // The fake address space map must have a distinct entry for each
698 // language-specific address space.
699 static const unsigned FakeAddrSpaceMap[] = {
702 3, // opencl_constant
708 return &FakeAddrSpaceMap;
710 return &T.getAddressSpaceMap();
714 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
715 const LangOptions &LangOpts) {
716 switch (LangOpts.getAddressSpaceMapMangling()) {
717 case LangOptions::ASMM_Target:
718 return TI.useAddressSpaceMapMangling();
719 case LangOptions::ASMM_On:
721 case LangOptions::ASMM_Off:
724 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
727 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
728 IdentifierTable &idents, SelectorTable &sels,
729 Builtin::Context &builtins)
730 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
731 DependentTemplateSpecializationTypes(this_()),
732 SubstTemplateTemplateParmPacks(this_()),
733 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
734 UInt128Decl(nullptr), Float128StubDecl(nullptr),
735 BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
736 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
737 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
738 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
739 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
740 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
741 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
742 SourceMgr(SM), LangOpts(LOpts),
743 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
744 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
745 Idents(idents), Selectors(sels), BuiltinInfo(builtins),
746 DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
747 Comments(SM), CommentsLoaded(false),
748 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
749 TUDecl = TranslationUnitDecl::Create(*this);
752 ASTContext::~ASTContext() {
753 ReleaseParentMapEntries();
755 // Release the DenseMaps associated with DeclContext objects.
756 // FIXME: Is this the ideal solution?
757 ReleaseDeclContextMaps();
759 // Call all of the deallocation functions on all of their targets.
760 for (DeallocationMap::const_iterator I = Deallocations.begin(),
761 E = Deallocations.end(); I != E; ++I)
762 for (unsigned J = 0, N = I->second.size(); J != N; ++J)
763 (I->first)((I->second)[J]);
765 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
766 // because they can contain DenseMaps.
767 for (llvm::DenseMap<const ObjCContainerDecl*,
768 const ASTRecordLayout*>::iterator
769 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
770 // Increment in loop to prevent using deallocated memory.
771 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
774 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
775 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
776 // Increment in loop to prevent using deallocated memory.
777 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
781 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
782 AEnd = DeclAttrs.end();
784 A->second->~AttrVec();
786 llvm::DeleteContainerSeconds(MangleNumberingContexts);
789 void ASTContext::ReleaseParentMapEntries() {
790 if (!AllParents) return;
791 for (const auto &Entry : *AllParents) {
792 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
793 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
795 assert(Entry.second.is<ParentVector *>());
796 delete Entry.second.get<ParentVector *>();
801 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
802 Deallocations[Callback].push_back(Data);
806 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
807 ExternalSource = Source;
810 void ASTContext::PrintStats() const {
811 llvm::errs() << "\n*** AST Context Stats:\n";
812 llvm::errs() << " " << Types.size() << " types total.\n";
814 unsigned counts[] = {
815 #define TYPE(Name, Parent) 0,
816 #define ABSTRACT_TYPE(Name, Parent)
817 #include "clang/AST/TypeNodes.def"
821 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
823 counts[(unsigned)T->getTypeClass()]++;
827 unsigned TotalBytes = 0;
828 #define TYPE(Name, Parent) \
830 llvm::errs() << " " << counts[Idx] << " " << #Name \
832 TotalBytes += counts[Idx] * sizeof(Name##Type); \
834 #define ABSTRACT_TYPE(Name, Parent)
835 #include "clang/AST/TypeNodes.def"
837 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
839 // Implicit special member functions.
840 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
841 << NumImplicitDefaultConstructors
842 << " implicit default constructors created\n";
843 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
844 << NumImplicitCopyConstructors
845 << " implicit copy constructors created\n";
846 if (getLangOpts().CPlusPlus)
847 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
848 << NumImplicitMoveConstructors
849 << " implicit move constructors created\n";
850 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
851 << NumImplicitCopyAssignmentOperators
852 << " implicit copy assignment operators created\n";
853 if (getLangOpts().CPlusPlus)
854 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
855 << NumImplicitMoveAssignmentOperators
856 << " implicit move assignment operators created\n";
857 llvm::errs() << NumImplicitDestructorsDeclared << "/"
858 << NumImplicitDestructors
859 << " implicit destructors created\n";
861 if (ExternalSource) {
862 llvm::errs() << "\n";
863 ExternalSource->PrintStats();
866 BumpAlloc.PrintStats();
869 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
870 bool NotifyListeners) {
872 if (auto *Listener = getASTMutationListener())
873 Listener->RedefinedHiddenDefinition(ND, M);
875 if (getLangOpts().ModulesLocalVisibility)
876 MergedDefModules[ND].push_back(M);
878 ND->setHidden(false);
881 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
882 auto It = MergedDefModules.find(ND);
883 if (It == MergedDefModules.end())
886 auto &Merged = It->second;
887 llvm::DenseSet<Module*> Found;
888 for (Module *&M : Merged)
889 if (!Found.insert(M).second)
891 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
894 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
896 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
898 return ExternCContext;
901 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
902 RecordDecl::TagKind TK) const {
905 if (getLangOpts().CPlusPlus)
906 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
907 Loc, &Idents.get(Name));
909 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
911 NewDecl->setImplicit();
912 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
913 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
917 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
918 StringRef Name) const {
919 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
920 TypedefDecl *NewDecl = TypedefDecl::Create(
921 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
922 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
923 NewDecl->setImplicit();
927 TypedefDecl *ASTContext::getInt128Decl() const {
929 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
933 TypedefDecl *ASTContext::getUInt128Decl() const {
935 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
939 TypeDecl *ASTContext::getFloat128StubType() const {
940 assert(LangOpts.CPlusPlus && "should only be called for c++");
941 if (!Float128StubDecl)
942 Float128StubDecl = buildImplicitRecord("__float128");
944 return Float128StubDecl;
947 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
948 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
949 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
953 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
954 assert((!this->Target || this->Target == &Target) &&
955 "Incorrect target reinitialization");
956 assert(VoidTy.isNull() && "Context reinitialized?");
958 this->Target = &Target;
960 ABI.reset(createCXXABI(Target));
961 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
962 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
965 InitBuiltinType(VoidTy, BuiltinType::Void);
968 InitBuiltinType(BoolTy, BuiltinType::Bool);
970 if (LangOpts.CharIsSigned)
971 InitBuiltinType(CharTy, BuiltinType::Char_S);
973 InitBuiltinType(CharTy, BuiltinType::Char_U);
975 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
976 InitBuiltinType(ShortTy, BuiltinType::Short);
977 InitBuiltinType(IntTy, BuiltinType::Int);
978 InitBuiltinType(LongTy, BuiltinType::Long);
979 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
982 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
983 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
984 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
985 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
986 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
989 InitBuiltinType(FloatTy, BuiltinType::Float);
990 InitBuiltinType(DoubleTy, BuiltinType::Double);
991 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
993 // GNU extension, 128-bit integers.
994 InitBuiltinType(Int128Ty, BuiltinType::Int128);
995 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
998 if (TargetInfo::isTypeSigned(Target.getWCharType()))
999 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1000 else // -fshort-wchar makes wchar_t be unsigned.
1001 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1002 if (LangOpts.CPlusPlus && LangOpts.WChar)
1003 WideCharTy = WCharTy;
1005 // C99 (or C++ using -fno-wchar).
1006 WideCharTy = getFromTargetType(Target.getWCharType());
1009 WIntTy = getFromTargetType(Target.getWIntType());
1011 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1012 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1014 Char16Ty = getFromTargetType(Target.getChar16Type());
1016 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1017 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1019 Char32Ty = getFromTargetType(Target.getChar32Type());
1021 // Placeholder type for type-dependent expressions whose type is
1022 // completely unknown. No code should ever check a type against
1023 // DependentTy and users should never see it; however, it is here to
1024 // help diagnose failures to properly check for type-dependent
1026 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1028 // Placeholder type for functions.
1029 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1031 // Placeholder type for bound members.
1032 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1034 // Placeholder type for pseudo-objects.
1035 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1037 // "any" type; useful for debugger-like clients.
1038 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1040 // Placeholder type for unbridged ARC casts.
1041 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1043 // Placeholder type for builtin functions.
1044 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1047 FloatComplexTy = getComplexType(FloatTy);
1048 DoubleComplexTy = getComplexType(DoubleTy);
1049 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1051 // Builtin types for 'id', 'Class', and 'SEL'.
1052 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1053 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1054 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1056 if (LangOpts.OpenCL) {
1057 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1058 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1059 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1060 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1061 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1062 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
1064 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1065 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1068 // Builtin type for __objc_yes and __objc_no
1069 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1070 SignedCharTy : BoolTy);
1072 ObjCConstantStringType = QualType();
1074 ObjCSuperType = QualType();
1077 VoidPtrTy = getPointerType(VoidTy);
1079 // nullptr type (C++0x 2.14.7)
1080 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1082 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1083 InitBuiltinType(HalfTy, BuiltinType::Half);
1085 // Builtin type used to help define __builtin_va_list.
1086 VaListTagTy = QualType();
1089 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1090 return SourceMgr.getDiagnostics();
1093 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1094 AttrVec *&Result = DeclAttrs[D];
1096 void *Mem = Allocate(sizeof(AttrVec));
1097 Result = new (Mem) AttrVec;
1103 /// \brief Erase the attributes corresponding to the given declaration.
1104 void ASTContext::eraseDeclAttrs(const Decl *D) {
1105 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1106 if (Pos != DeclAttrs.end()) {
1107 Pos->second->~AttrVec();
1108 DeclAttrs.erase(Pos);
1113 MemberSpecializationInfo *
1114 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1115 assert(Var->isStaticDataMember() && "Not a static data member");
1116 return getTemplateOrSpecializationInfo(Var)
1117 .dyn_cast<MemberSpecializationInfo *>();
1120 ASTContext::TemplateOrSpecializationInfo
1121 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1122 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1123 TemplateOrInstantiation.find(Var);
1124 if (Pos == TemplateOrInstantiation.end())
1125 return TemplateOrSpecializationInfo();
1131 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1132 TemplateSpecializationKind TSK,
1133 SourceLocation PointOfInstantiation) {
1134 assert(Inst->isStaticDataMember() && "Not a static data member");
1135 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1136 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1137 Tmpl, TSK, PointOfInstantiation));
1141 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1142 TemplateOrSpecializationInfo TSI) {
1143 assert(!TemplateOrInstantiation[Inst] &&
1144 "Already noted what the variable was instantiated from");
1145 TemplateOrInstantiation[Inst] = TSI;
1148 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1149 const FunctionDecl *FD){
1150 assert(FD && "Specialization is 0");
1151 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1152 = ClassScopeSpecializationPattern.find(FD);
1153 if (Pos == ClassScopeSpecializationPattern.end())
1159 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1160 FunctionDecl *Pattern) {
1161 assert(FD && "Specialization is 0");
1162 assert(Pattern && "Class scope specialization pattern is 0");
1163 ClassScopeSpecializationPattern[FD] = Pattern;
1167 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
1168 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
1169 = InstantiatedFromUsingDecl.find(UUD);
1170 if (Pos == InstantiatedFromUsingDecl.end())
1177 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1178 assert((isa<UsingDecl>(Pattern) ||
1179 isa<UnresolvedUsingValueDecl>(Pattern) ||
1180 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1181 "pattern decl is not a using decl");
1182 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1183 InstantiatedFromUsingDecl[Inst] = Pattern;
1187 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1188 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1189 = InstantiatedFromUsingShadowDecl.find(Inst);
1190 if (Pos == InstantiatedFromUsingShadowDecl.end())
1197 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1198 UsingShadowDecl *Pattern) {
1199 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1200 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1203 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1204 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1205 = InstantiatedFromUnnamedFieldDecl.find(Field);
1206 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1212 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1214 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1215 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1216 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1217 "Already noted what unnamed field was instantiated from");
1219 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1222 ASTContext::overridden_cxx_method_iterator
1223 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1224 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1225 = OverriddenMethods.find(Method->getCanonicalDecl());
1226 if (Pos == OverriddenMethods.end())
1229 return Pos->second.begin();
1232 ASTContext::overridden_cxx_method_iterator
1233 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1234 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1235 = OverriddenMethods.find(Method->getCanonicalDecl());
1236 if (Pos == OverriddenMethods.end())
1239 return Pos->second.end();
1243 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1244 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1245 = OverriddenMethods.find(Method->getCanonicalDecl());
1246 if (Pos == OverriddenMethods.end())
1249 return Pos->second.size();
1252 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1253 const CXXMethodDecl *Overridden) {
1254 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1255 OverriddenMethods[Method].push_back(Overridden);
1258 void ASTContext::getOverriddenMethods(
1260 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1263 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1264 Overridden.append(overridden_methods_begin(CXXMethod),
1265 overridden_methods_end(CXXMethod));
1269 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1273 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1274 Method->getOverriddenMethods(OverDecls);
1275 Overridden.append(OverDecls.begin(), OverDecls.end());
1278 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1279 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1280 assert(!Import->isFromASTFile() && "Non-local import declaration");
1281 if (!FirstLocalImport) {
1282 FirstLocalImport = Import;
1283 LastLocalImport = Import;
1287 LastLocalImport->NextLocalImport = Import;
1288 LastLocalImport = Import;
1291 //===----------------------------------------------------------------------===//
1292 // Type Sizing and Analysis
1293 //===----------------------------------------------------------------------===//
1295 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1296 /// scalar floating point type.
1297 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1298 const BuiltinType *BT = T->getAs<BuiltinType>();
1299 assert(BT && "Not a floating point type!");
1300 switch (BT->getKind()) {
1301 default: llvm_unreachable("Not a floating point type!");
1302 case BuiltinType::Half: return Target->getHalfFormat();
1303 case BuiltinType::Float: return Target->getFloatFormat();
1304 case BuiltinType::Double: return Target->getDoubleFormat();
1305 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1309 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1310 unsigned Align = Target->getCharWidth();
1312 bool UseAlignAttrOnly = false;
1313 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1314 Align = AlignFromAttr;
1316 // __attribute__((aligned)) can increase or decrease alignment
1317 // *except* on a struct or struct member, where it only increases
1318 // alignment unless 'packed' is also specified.
1320 // It is an error for alignas to decrease alignment, so we can
1321 // ignore that possibility; Sema should diagnose it.
1322 if (isa<FieldDecl>(D)) {
1323 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1324 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1326 UseAlignAttrOnly = true;
1329 else if (isa<FieldDecl>(D))
1331 D->hasAttr<PackedAttr>() ||
1332 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1334 // If we're using the align attribute only, just ignore everything
1335 // else about the declaration and its type.
1336 if (UseAlignAttrOnly) {
1339 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1340 QualType T = VD->getType();
1341 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
1343 T = RT->getPointeeType();
1345 T = getPointerType(RT->getPointeeType());
1347 QualType BaseT = getBaseElementType(T);
1348 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
1349 // Adjust alignments of declarations with array type by the
1350 // large-array alignment on the target.
1351 if (const ArrayType *arrayType = getAsArrayType(T)) {
1352 unsigned MinWidth = Target->getLargeArrayMinWidth();
1353 if (!ForAlignof && MinWidth) {
1354 if (isa<VariableArrayType>(arrayType))
1355 Align = std::max(Align, Target->getLargeArrayAlign());
1356 else if (isa<ConstantArrayType>(arrayType) &&
1357 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1358 Align = std::max(Align, Target->getLargeArrayAlign());
1361 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1362 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1363 if (VD->hasGlobalStorage() && !ForAlignof)
1364 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1368 // Fields can be subject to extra alignment constraints, like if
1369 // the field is packed, the struct is packed, or the struct has a
1370 // a max-field-alignment constraint (#pragma pack). So calculate
1371 // the actual alignment of the field within the struct, and then
1372 // (as we're expected to) constrain that by the alignment of the type.
1373 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1374 const RecordDecl *Parent = Field->getParent();
1375 // We can only produce a sensible answer if the record is valid.
1376 if (!Parent->isInvalidDecl()) {
1377 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1379 // Start with the record's overall alignment.
1380 unsigned FieldAlign = toBits(Layout.getAlignment());
1382 // Use the GCD of that and the offset within the record.
1383 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1385 // Alignment is always a power of 2, so the GCD will be a power of 2,
1386 // which means we get to do this crazy thing instead of Euclid's.
1387 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1388 if (LowBitOfOffset < FieldAlign)
1389 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1392 Align = std::min(Align, FieldAlign);
1397 return toCharUnitsFromBits(Align);
1400 // getTypeInfoDataSizeInChars - Return the size of a type, in
1401 // chars. If the type is a record, its data size is returned. This is
1402 // the size of the memcpy that's performed when assigning this type
1403 // using a trivial copy/move assignment operator.
1404 std::pair<CharUnits, CharUnits>
1405 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1406 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1408 // In C++, objects can sometimes be allocated into the tail padding
1409 // of a base-class subobject. We decide whether that's possible
1410 // during class layout, so here we can just trust the layout results.
1411 if (getLangOpts().CPlusPlus) {
1412 if (const RecordType *RT = T->getAs<RecordType>()) {
1413 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1414 sizeAndAlign.first = layout.getDataSize();
1418 return sizeAndAlign;
1421 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1422 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1423 std::pair<CharUnits, CharUnits>
1424 static getConstantArrayInfoInChars(const ASTContext &Context,
1425 const ConstantArrayType *CAT) {
1426 std::pair<CharUnits, CharUnits> EltInfo =
1427 Context.getTypeInfoInChars(CAT->getElementType());
1428 uint64_t Size = CAT->getSize().getZExtValue();
1429 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1430 (uint64_t)(-1)/Size) &&
1431 "Overflow in array type char size evaluation");
1432 uint64_t Width = EltInfo.first.getQuantity() * Size;
1433 unsigned Align = EltInfo.second.getQuantity();
1434 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1435 Context.getTargetInfo().getPointerWidth(0) == 64)
1436 Width = llvm::RoundUpToAlignment(Width, Align);
1437 return std::make_pair(CharUnits::fromQuantity(Width),
1438 CharUnits::fromQuantity(Align));
1441 std::pair<CharUnits, CharUnits>
1442 ASTContext::getTypeInfoInChars(const Type *T) const {
1443 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1444 return getConstantArrayInfoInChars(*this, CAT);
1445 TypeInfo Info = getTypeInfo(T);
1446 return std::make_pair(toCharUnitsFromBits(Info.Width),
1447 toCharUnitsFromBits(Info.Align));
1450 std::pair<CharUnits, CharUnits>
1451 ASTContext::getTypeInfoInChars(QualType T) const {
1452 return getTypeInfoInChars(T.getTypePtr());
1455 bool ASTContext::isAlignmentRequired(const Type *T) const {
1456 return getTypeInfo(T).AlignIsRequired;
1459 bool ASTContext::isAlignmentRequired(QualType T) const {
1460 return isAlignmentRequired(T.getTypePtr());
1463 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1464 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1465 if (I != MemoizedTypeInfo.end())
1468 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1469 TypeInfo TI = getTypeInfoImpl(T);
1470 MemoizedTypeInfo[T] = TI;
1474 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1475 /// method does not work on incomplete types.
1477 /// FIXME: Pointers into different addr spaces could have different sizes and
1478 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1479 /// should take a QualType, &c.
1480 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1483 bool AlignIsRequired = false;
1484 switch (T->getTypeClass()) {
1485 #define TYPE(Class, Base)
1486 #define ABSTRACT_TYPE(Class, Base)
1487 #define NON_CANONICAL_TYPE(Class, Base)
1488 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1489 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1491 assert(!T->isDependentType() && "should not see dependent types here"); \
1492 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1493 #include "clang/AST/TypeNodes.def"
1494 llvm_unreachable("Should not see dependent types");
1496 case Type::FunctionNoProto:
1497 case Type::FunctionProto:
1498 // GCC extension: alignof(function) = 32 bits
1503 case Type::IncompleteArray:
1504 case Type::VariableArray:
1506 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1509 case Type::ConstantArray: {
1510 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1512 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1513 uint64_t Size = CAT->getSize().getZExtValue();
1514 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1515 "Overflow in array type bit size evaluation");
1516 Width = EltInfo.Width * Size;
1517 Align = EltInfo.Align;
1518 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1519 getTargetInfo().getPointerWidth(0) == 64)
1520 Width = llvm::RoundUpToAlignment(Width, Align);
1523 case Type::ExtVector:
1524 case Type::Vector: {
1525 const VectorType *VT = cast<VectorType>(T);
1526 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1527 Width = EltInfo.Width * VT->getNumElements();
1529 // If the alignment is not a power of 2, round up to the next power of 2.
1530 // This happens for non-power-of-2 length vectors.
1531 if (Align & (Align-1)) {
1532 Align = llvm::NextPowerOf2(Align);
1533 Width = llvm::RoundUpToAlignment(Width, Align);
1535 // Adjust the alignment based on the target max.
1536 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1537 if (TargetVectorAlign && TargetVectorAlign < Align)
1538 Align = TargetVectorAlign;
1543 switch (cast<BuiltinType>(T)->getKind()) {
1544 default: llvm_unreachable("Unknown builtin type!");
1545 case BuiltinType::Void:
1546 // GCC extension: alignof(void) = 8 bits.
1551 case BuiltinType::Bool:
1552 Width = Target->getBoolWidth();
1553 Align = Target->getBoolAlign();
1555 case BuiltinType::Char_S:
1556 case BuiltinType::Char_U:
1557 case BuiltinType::UChar:
1558 case BuiltinType::SChar:
1559 Width = Target->getCharWidth();
1560 Align = Target->getCharAlign();
1562 case BuiltinType::WChar_S:
1563 case BuiltinType::WChar_U:
1564 Width = Target->getWCharWidth();
1565 Align = Target->getWCharAlign();
1567 case BuiltinType::Char16:
1568 Width = Target->getChar16Width();
1569 Align = Target->getChar16Align();
1571 case BuiltinType::Char32:
1572 Width = Target->getChar32Width();
1573 Align = Target->getChar32Align();
1575 case BuiltinType::UShort:
1576 case BuiltinType::Short:
1577 Width = Target->getShortWidth();
1578 Align = Target->getShortAlign();
1580 case BuiltinType::UInt:
1581 case BuiltinType::Int:
1582 Width = Target->getIntWidth();
1583 Align = Target->getIntAlign();
1585 case BuiltinType::ULong:
1586 case BuiltinType::Long:
1587 Width = Target->getLongWidth();
1588 Align = Target->getLongAlign();
1590 case BuiltinType::ULongLong:
1591 case BuiltinType::LongLong:
1592 Width = Target->getLongLongWidth();
1593 Align = Target->getLongLongAlign();
1595 case BuiltinType::Int128:
1596 case BuiltinType::UInt128:
1598 Align = 128; // int128_t is 128-bit aligned on all targets.
1600 case BuiltinType::Half:
1601 Width = Target->getHalfWidth();
1602 Align = Target->getHalfAlign();
1604 case BuiltinType::Float:
1605 Width = Target->getFloatWidth();
1606 Align = Target->getFloatAlign();
1608 case BuiltinType::Double:
1609 Width = Target->getDoubleWidth();
1610 Align = Target->getDoubleAlign();
1612 case BuiltinType::LongDouble:
1613 Width = Target->getLongDoubleWidth();
1614 Align = Target->getLongDoubleAlign();
1616 case BuiltinType::NullPtr:
1617 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1618 Align = Target->getPointerAlign(0); // == sizeof(void*)
1620 case BuiltinType::ObjCId:
1621 case BuiltinType::ObjCClass:
1622 case BuiltinType::ObjCSel:
1623 Width = Target->getPointerWidth(0);
1624 Align = Target->getPointerAlign(0);
1626 case BuiltinType::OCLSampler:
1627 // Samplers are modeled as integers.
1628 Width = Target->getIntWidth();
1629 Align = Target->getIntAlign();
1631 case BuiltinType::OCLEvent:
1632 case BuiltinType::OCLImage1d:
1633 case BuiltinType::OCLImage1dArray:
1634 case BuiltinType::OCLImage1dBuffer:
1635 case BuiltinType::OCLImage2d:
1636 case BuiltinType::OCLImage2dArray:
1637 case BuiltinType::OCLImage3d:
1638 // Currently these types are pointers to opaque types.
1639 Width = Target->getPointerWidth(0);
1640 Align = Target->getPointerAlign(0);
1644 case Type::ObjCObjectPointer:
1645 Width = Target->getPointerWidth(0);
1646 Align = Target->getPointerAlign(0);
1648 case Type::BlockPointer: {
1649 unsigned AS = getTargetAddressSpace(
1650 cast<BlockPointerType>(T)->getPointeeType());
1651 Width = Target->getPointerWidth(AS);
1652 Align = Target->getPointerAlign(AS);
1655 case Type::LValueReference:
1656 case Type::RValueReference: {
1657 // alignof and sizeof should never enter this code path here, so we go
1658 // the pointer route.
1659 unsigned AS = getTargetAddressSpace(
1660 cast<ReferenceType>(T)->getPointeeType());
1661 Width = Target->getPointerWidth(AS);
1662 Align = Target->getPointerAlign(AS);
1665 case Type::Pointer: {
1666 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1667 Width = Target->getPointerWidth(AS);
1668 Align = Target->getPointerAlign(AS);
1671 case Type::MemberPointer: {
1672 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1673 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1676 case Type::Complex: {
1677 // Complex types have the same alignment as their elements, but twice the
1679 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1680 Width = EltInfo.Width * 2;
1681 Align = EltInfo.Align;
1684 case Type::ObjCObject:
1685 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1686 case Type::Adjusted:
1688 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1689 case Type::ObjCInterface: {
1690 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1691 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1692 Width = toBits(Layout.getSize());
1693 Align = toBits(Layout.getAlignment());
1698 const TagType *TT = cast<TagType>(T);
1700 if (TT->getDecl()->isInvalidDecl()) {
1706 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1707 const EnumDecl *ED = ET->getDecl();
1709 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1710 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1711 Info.Align = AttrAlign;
1712 Info.AlignIsRequired = true;
1717 const RecordType *RT = cast<RecordType>(TT);
1718 const RecordDecl *RD = RT->getDecl();
1719 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
1720 Width = toBits(Layout.getSize());
1721 Align = toBits(Layout.getAlignment());
1722 AlignIsRequired = RD->hasAttr<AlignedAttr>();
1726 case Type::SubstTemplateTypeParm:
1727 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1728 getReplacementType().getTypePtr());
1731 const AutoType *A = cast<AutoType>(T);
1732 assert(!A->getDeducedType().isNull() &&
1733 "cannot request the size of an undeduced or dependent auto type");
1734 return getTypeInfo(A->getDeducedType().getTypePtr());
1738 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1740 case Type::Typedef: {
1741 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1742 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1743 // If the typedef has an aligned attribute on it, it overrides any computed
1744 // alignment we have. This violates the GCC documentation (which says that
1745 // attribute(aligned) can only round up) but matches its implementation.
1746 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
1748 AlignIsRequired = true;
1751 AlignIsRequired = Info.AlignIsRequired;
1757 case Type::Elaborated:
1758 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1760 case Type::Attributed:
1762 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1764 case Type::Atomic: {
1765 // Start with the base type information.
1766 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1770 // If the size of the type doesn't exceed the platform's max
1771 // atomic promotion width, make the size and alignment more
1772 // favorable to atomic operations:
1773 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1774 // Round the size up to a power of 2.
1775 if (!llvm::isPowerOf2_64(Width))
1776 Width = llvm::NextPowerOf2(Width);
1778 // Set the alignment equal to the size.
1779 Align = static_cast<unsigned>(Width);
1785 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1786 return TypeInfo(Width, Align, AlignIsRequired);
1789 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1790 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1791 return CharUnits::fromQuantity(BitSize / getCharWidth());
1794 /// toBits - Convert a size in characters to a size in characters.
1795 int64_t ASTContext::toBits(CharUnits CharSize) const {
1796 return CharSize.getQuantity() * getCharWidth();
1799 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1800 /// This method does not work on incomplete types.
1801 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1802 return getTypeInfoInChars(T).first;
1804 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1805 return getTypeInfoInChars(T).first;
1808 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1809 /// characters. This method does not work on incomplete types.
1810 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1811 return toCharUnitsFromBits(getTypeAlign(T));
1813 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1814 return toCharUnitsFromBits(getTypeAlign(T));
1817 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1818 /// type for the current target in bits. This can be different than the ABI
1819 /// alignment in cases where it is beneficial for performance to overalign
1821 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1822 TypeInfo TI = getTypeInfo(T);
1823 unsigned ABIAlign = TI.Align;
1825 T = T->getBaseElementTypeUnsafe();
1827 // The preferred alignment of member pointers is that of a pointer.
1828 if (T->isMemberPointerType())
1829 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1831 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1832 return ABIAlign; // Never overalign on XCore.
1834 // Double and long long should be naturally aligned if possible.
1835 if (const ComplexType *CT = T->getAs<ComplexType>())
1836 T = CT->getElementType().getTypePtr();
1837 if (const EnumType *ET = T->getAs<EnumType>())
1838 T = ET->getDecl()->getIntegerType().getTypePtr();
1839 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1840 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1841 T->isSpecificBuiltinType(BuiltinType::ULongLong))
1842 // Don't increase the alignment if an alignment attribute was specified on a
1843 // typedef declaration.
1844 if (!TI.AlignIsRequired)
1845 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1850 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1851 /// for __attribute__((aligned)) on this target, to be used if no alignment
1852 /// value is specified.
1853 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned(void) const {
1854 return getTargetInfo().getDefaultAlignForAttributeAligned();
1857 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
1858 /// to a global variable of the specified type.
1859 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1860 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1863 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
1864 /// should be given to a global variable of the specified type.
1865 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1866 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1869 /// DeepCollectObjCIvars -
1870 /// This routine first collects all declared, but not synthesized, ivars in
1871 /// super class and then collects all ivars, including those synthesized for
1872 /// current class. This routine is used for implementation of current class
1873 /// when all ivars, declared and synthesized are known.
1875 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1877 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1878 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1879 DeepCollectObjCIvars(SuperClass, false, Ivars);
1881 for (const auto *I : OI->ivars())
1884 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1885 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1886 Iv= Iv->getNextIvar())
1887 Ivars.push_back(Iv);
1891 /// CollectInheritedProtocols - Collect all protocols in current class and
1892 /// those inherited by it.
1893 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1894 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1895 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1896 // We can use protocol_iterator here instead of
1897 // all_referenced_protocol_iterator since we are walking all categories.
1898 for (auto *Proto : OI->all_referenced_protocols()) {
1899 Protocols.insert(Proto->getCanonicalDecl());
1900 for (auto *P : Proto->protocols()) {
1901 Protocols.insert(P->getCanonicalDecl());
1902 CollectInheritedProtocols(P, Protocols);
1906 // Categories of this Interface.
1907 for (const auto *Cat : OI->visible_categories())
1908 CollectInheritedProtocols(Cat, Protocols);
1910 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1912 CollectInheritedProtocols(SD, Protocols);
1913 SD = SD->getSuperClass();
1915 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1916 for (auto *Proto : OC->protocols()) {
1917 Protocols.insert(Proto->getCanonicalDecl());
1918 for (const auto *P : Proto->protocols())
1919 CollectInheritedProtocols(P, Protocols);
1921 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1922 for (auto *Proto : OP->protocols()) {
1923 Protocols.insert(Proto->getCanonicalDecl());
1924 for (const auto *P : Proto->protocols())
1925 CollectInheritedProtocols(P, Protocols);
1930 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1932 // Count ivars declared in class extension.
1933 for (const auto *Ext : OI->known_extensions())
1934 count += Ext->ivar_size();
1936 // Count ivar defined in this class's implementation. This
1937 // includes synthesized ivars.
1938 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1939 count += ImplDecl->ivar_size();
1944 bool ASTContext::isSentinelNullExpr(const Expr *E) {
1948 // nullptr_t is always treated as null.
1949 if (E->getType()->isNullPtrType()) return true;
1951 if (E->getType()->isAnyPointerType() &&
1952 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1953 Expr::NPC_ValueDependentIsNull))
1956 // Unfortunately, __null has type 'int'.
1957 if (isa<GNUNullExpr>(E)) return true;
1962 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1963 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1964 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1965 I = ObjCImpls.find(D);
1966 if (I != ObjCImpls.end())
1967 return cast<ObjCImplementationDecl>(I->second);
1970 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1971 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1972 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1973 I = ObjCImpls.find(D);
1974 if (I != ObjCImpls.end())
1975 return cast<ObjCCategoryImplDecl>(I->second);
1979 /// \brief Set the implementation of ObjCInterfaceDecl.
1980 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1981 ObjCImplementationDecl *ImplD) {
1982 assert(IFaceD && ImplD && "Passed null params");
1983 ObjCImpls[IFaceD] = ImplD;
1985 /// \brief Set the implementation of ObjCCategoryDecl.
1986 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1987 ObjCCategoryImplDecl *ImplD) {
1988 assert(CatD && ImplD && "Passed null params");
1989 ObjCImpls[CatD] = ImplD;
1992 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1993 const NamedDecl *ND) const {
1994 if (const ObjCInterfaceDecl *ID =
1995 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1997 if (const ObjCCategoryDecl *CD =
1998 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1999 return CD->getClassInterface();
2000 if (const ObjCImplDecl *IMD =
2001 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2002 return IMD->getClassInterface();
2007 /// \brief Get the copy initialization expression of VarDecl,or NULL if
2009 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
2010 assert(VD && "Passed null params");
2011 assert(VD->hasAttr<BlocksAttr>() &&
2012 "getBlockVarCopyInits - not __block var");
2013 llvm::DenseMap<const VarDecl*, Expr*>::iterator
2014 I = BlockVarCopyInits.find(VD);
2015 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
2018 /// \brief Set the copy inialization expression of a block var decl.
2019 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2020 assert(VD && Init && "Passed null params");
2021 assert(VD->hasAttr<BlocksAttr>() &&
2022 "setBlockVarCopyInits - not __block var");
2023 BlockVarCopyInits[VD] = Init;
2026 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2027 unsigned DataSize) const {
2029 DataSize = TypeLoc::getFullDataSizeForType(T);
2031 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2032 "incorrect data size provided to CreateTypeSourceInfo!");
2034 TypeSourceInfo *TInfo =
2035 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2036 new (TInfo) TypeSourceInfo(T);
2040 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2041 SourceLocation L) const {
2042 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2043 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2047 const ASTRecordLayout &
2048 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2049 return getObjCLayout(D, nullptr);
2052 const ASTRecordLayout &
2053 ASTContext::getASTObjCImplementationLayout(
2054 const ObjCImplementationDecl *D) const {
2055 return getObjCLayout(D->getClassInterface(), D);
2058 //===----------------------------------------------------------------------===//
2059 // Type creation/memoization methods
2060 //===----------------------------------------------------------------------===//
2063 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2064 unsigned fastQuals = quals.getFastQualifiers();
2065 quals.removeFastQualifiers();
2067 // Check if we've already instantiated this type.
2068 llvm::FoldingSetNodeID ID;
2069 ExtQuals::Profile(ID, baseType, quals);
2070 void *insertPos = nullptr;
2071 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2072 assert(eq->getQualifiers() == quals);
2073 return QualType(eq, fastQuals);
2076 // If the base type is not canonical, make the appropriate canonical type.
2078 if (!baseType->isCanonicalUnqualified()) {
2079 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2080 canonSplit.Quals.addConsistentQualifiers(quals);
2081 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2083 // Re-find the insert position.
2084 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2087 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2088 ExtQualNodes.InsertNode(eq, insertPos);
2089 return QualType(eq, fastQuals);
2093 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2094 QualType CanT = getCanonicalType(T);
2095 if (CanT.getAddressSpace() == AddressSpace)
2098 // If we are composing extended qualifiers together, merge together
2099 // into one ExtQuals node.
2100 QualifierCollector Quals;
2101 const Type *TypeNode = Quals.strip(T);
2103 // If this type already has an address space specified, it cannot get
2105 assert(!Quals.hasAddressSpace() &&
2106 "Type cannot be in multiple addr spaces!");
2107 Quals.addAddressSpace(AddressSpace);
2109 return getExtQualType(TypeNode, Quals);
2112 QualType ASTContext::getObjCGCQualType(QualType T,
2113 Qualifiers::GC GCAttr) const {
2114 QualType CanT = getCanonicalType(T);
2115 if (CanT.getObjCGCAttr() == GCAttr)
2118 if (const PointerType *ptr = T->getAs<PointerType>()) {
2119 QualType Pointee = ptr->getPointeeType();
2120 if (Pointee->isAnyPointerType()) {
2121 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2122 return getPointerType(ResultType);
2126 // If we are composing extended qualifiers together, merge together
2127 // into one ExtQuals node.
2128 QualifierCollector Quals;
2129 const Type *TypeNode = Quals.strip(T);
2131 // If this type already has an ObjCGC specified, it cannot get
2133 assert(!Quals.hasObjCGCAttr() &&
2134 "Type cannot have multiple ObjCGCs!");
2135 Quals.addObjCGCAttr(GCAttr);
2137 return getExtQualType(TypeNode, Quals);
2140 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2141 FunctionType::ExtInfo Info) {
2142 if (T->getExtInfo() == Info)
2146 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2147 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2149 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2150 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2152 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2155 return cast<FunctionType>(Result.getTypePtr());
2158 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2159 QualType ResultType) {
2160 FD = FD->getMostRecentDecl();
2162 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2163 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2164 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2165 if (FunctionDecl *Next = FD->getPreviousDecl())
2170 if (ASTMutationListener *L = getASTMutationListener())
2171 L->DeducedReturnType(FD, ResultType);
2174 /// Get a function type and produce the equivalent function type with the
2175 /// specified exception specification. Type sugar that can be present on a
2176 /// declaration of a function with an exception specification is permitted
2177 /// and preserved. Other type sugar (for instance, typedefs) is not.
2178 static QualType getFunctionTypeWithExceptionSpec(
2179 ASTContext &Context, QualType Orig,
2180 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2181 // Might have some parens.
2182 if (auto *PT = dyn_cast<ParenType>(Orig))
2183 return Context.getParenType(
2184 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2186 // Might have a calling-convention attribute.
2187 if (auto *AT = dyn_cast<AttributedType>(Orig))
2188 return Context.getAttributedType(
2190 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2191 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2194 // Anything else must be a function type. Rebuild it with the new exception
2196 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2197 return Context.getFunctionType(
2198 Proto->getReturnType(), Proto->getParamTypes(),
2199 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2202 void ASTContext::adjustExceptionSpec(
2203 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2207 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2208 FD->setType(Updated);
2213 // Update the type in the type source information too.
2214 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2215 // If the type and the type-as-written differ, we may need to update
2216 // the type-as-written too.
2217 if (TSInfo->getType() != FD->getType())
2218 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2220 // FIXME: When we get proper type location information for exceptions,
2221 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2222 // up the TypeSourceInfo;
2223 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2224 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2225 "TypeLoc size mismatch from updating exception specification");
2226 TSInfo->overrideType(Updated);
2230 /// getComplexType - Return the uniqued reference to the type for a complex
2231 /// number with the specified element type.
2232 QualType ASTContext::getComplexType(QualType T) const {
2233 // Unique pointers, to guarantee there is only one pointer of a particular
2235 llvm::FoldingSetNodeID ID;
2236 ComplexType::Profile(ID, T);
2238 void *InsertPos = nullptr;
2239 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2240 return QualType(CT, 0);
2242 // If the pointee type isn't canonical, this won't be a canonical type either,
2243 // so fill in the canonical type field.
2245 if (!T.isCanonical()) {
2246 Canonical = getComplexType(getCanonicalType(T));
2248 // Get the new insert position for the node we care about.
2249 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2250 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2252 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2253 Types.push_back(New);
2254 ComplexTypes.InsertNode(New, InsertPos);
2255 return QualType(New, 0);
2258 /// getPointerType - Return the uniqued reference to the type for a pointer to
2259 /// the specified type.
2260 QualType ASTContext::getPointerType(QualType T) const {
2261 // Unique pointers, to guarantee there is only one pointer of a particular
2263 llvm::FoldingSetNodeID ID;
2264 PointerType::Profile(ID, T);
2266 void *InsertPos = nullptr;
2267 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2268 return QualType(PT, 0);
2270 // If the pointee type isn't canonical, this won't be a canonical type either,
2271 // so fill in the canonical type field.
2273 if (!T.isCanonical()) {
2274 Canonical = getPointerType(getCanonicalType(T));
2276 // Get the new insert position for the node we care about.
2277 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2278 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2280 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2281 Types.push_back(New);
2282 PointerTypes.InsertNode(New, InsertPos);
2283 return QualType(New, 0);
2286 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2287 llvm::FoldingSetNodeID ID;
2288 AdjustedType::Profile(ID, Orig, New);
2289 void *InsertPos = nullptr;
2290 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2292 return QualType(AT, 0);
2294 QualType Canonical = getCanonicalType(New);
2296 // Get the new insert position for the node we care about.
2297 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2298 assert(!AT && "Shouldn't be in the map!");
2300 AT = new (*this, TypeAlignment)
2301 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2302 Types.push_back(AT);
2303 AdjustedTypes.InsertNode(AT, InsertPos);
2304 return QualType(AT, 0);
2307 QualType ASTContext::getDecayedType(QualType T) const {
2308 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2313 // A declaration of a parameter as "array of type" shall be
2314 // adjusted to "qualified pointer to type", where the type
2315 // qualifiers (if any) are those specified within the [ and ] of
2316 // the array type derivation.
2317 if (T->isArrayType())
2318 Decayed = getArrayDecayedType(T);
2321 // A declaration of a parameter as "function returning type"
2322 // shall be adjusted to "pointer to function returning type", as
2324 if (T->isFunctionType())
2325 Decayed = getPointerType(T);
2327 llvm::FoldingSetNodeID ID;
2328 AdjustedType::Profile(ID, T, Decayed);
2329 void *InsertPos = nullptr;
2330 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2332 return QualType(AT, 0);
2334 QualType Canonical = getCanonicalType(Decayed);
2336 // Get the new insert position for the node we care about.
2337 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2338 assert(!AT && "Shouldn't be in the map!");
2340 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2341 Types.push_back(AT);
2342 AdjustedTypes.InsertNode(AT, InsertPos);
2343 return QualType(AT, 0);
2346 /// getBlockPointerType - Return the uniqued reference to the type for
2347 /// a pointer to the specified block.
2348 QualType ASTContext::getBlockPointerType(QualType T) const {
2349 assert(T->isFunctionType() && "block of function types only");
2350 // Unique pointers, to guarantee there is only one block of a particular
2352 llvm::FoldingSetNodeID ID;
2353 BlockPointerType::Profile(ID, T);
2355 void *InsertPos = nullptr;
2356 if (BlockPointerType *PT =
2357 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2358 return QualType(PT, 0);
2360 // If the block pointee type isn't canonical, this won't be a canonical
2361 // type either so fill in the canonical type field.
2363 if (!T.isCanonical()) {
2364 Canonical = getBlockPointerType(getCanonicalType(T));
2366 // Get the new insert position for the node we care about.
2367 BlockPointerType *NewIP =
2368 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2369 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2371 BlockPointerType *New
2372 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2373 Types.push_back(New);
2374 BlockPointerTypes.InsertNode(New, InsertPos);
2375 return QualType(New, 0);
2378 /// getLValueReferenceType - Return the uniqued reference to the type for an
2379 /// lvalue reference to the specified type.
2381 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2382 assert(getCanonicalType(T) != OverloadTy &&
2383 "Unresolved overloaded function type");
2385 // Unique pointers, to guarantee there is only one pointer of a particular
2387 llvm::FoldingSetNodeID ID;
2388 ReferenceType::Profile(ID, T, SpelledAsLValue);
2390 void *InsertPos = nullptr;
2391 if (LValueReferenceType *RT =
2392 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2393 return QualType(RT, 0);
2395 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2397 // If the referencee type isn't canonical, this won't be a canonical type
2398 // either, so fill in the canonical type field.
2400 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2401 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2402 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2404 // Get the new insert position for the node we care about.
2405 LValueReferenceType *NewIP =
2406 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2407 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2410 LValueReferenceType *New
2411 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2413 Types.push_back(New);
2414 LValueReferenceTypes.InsertNode(New, InsertPos);
2416 return QualType(New, 0);
2419 /// getRValueReferenceType - Return the uniqued reference to the type for an
2420 /// rvalue reference to the specified type.
2421 QualType ASTContext::getRValueReferenceType(QualType T) const {
2422 // Unique pointers, to guarantee there is only one pointer of a particular
2424 llvm::FoldingSetNodeID ID;
2425 ReferenceType::Profile(ID, T, false);
2427 void *InsertPos = nullptr;
2428 if (RValueReferenceType *RT =
2429 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2430 return QualType(RT, 0);
2432 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2434 // If the referencee type isn't canonical, this won't be a canonical type
2435 // either, so fill in the canonical type field.
2437 if (InnerRef || !T.isCanonical()) {
2438 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2439 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2441 // Get the new insert position for the node we care about.
2442 RValueReferenceType *NewIP =
2443 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2444 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2447 RValueReferenceType *New
2448 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2449 Types.push_back(New);
2450 RValueReferenceTypes.InsertNode(New, InsertPos);
2451 return QualType(New, 0);
2454 /// getMemberPointerType - Return the uniqued reference to the type for a
2455 /// member pointer to the specified type, in the specified class.
2456 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2457 // Unique pointers, to guarantee there is only one pointer of a particular
2459 llvm::FoldingSetNodeID ID;
2460 MemberPointerType::Profile(ID, T, Cls);
2462 void *InsertPos = nullptr;
2463 if (MemberPointerType *PT =
2464 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2465 return QualType(PT, 0);
2467 // If the pointee or class type isn't canonical, this won't be a canonical
2468 // type either, so fill in the canonical type field.
2470 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2471 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2473 // Get the new insert position for the node we care about.
2474 MemberPointerType *NewIP =
2475 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2476 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2478 MemberPointerType *New
2479 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2480 Types.push_back(New);
2481 MemberPointerTypes.InsertNode(New, InsertPos);
2482 return QualType(New, 0);
2485 /// getConstantArrayType - Return the unique reference to the type for an
2486 /// array of the specified element type.
2487 QualType ASTContext::getConstantArrayType(QualType EltTy,
2488 const llvm::APInt &ArySizeIn,
2489 ArrayType::ArraySizeModifier ASM,
2490 unsigned IndexTypeQuals) const {
2491 assert((EltTy->isDependentType() ||
2492 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2493 "Constant array of VLAs is illegal!");
2495 // Convert the array size into a canonical width matching the pointer size for
2497 llvm::APInt ArySize(ArySizeIn);
2499 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2501 llvm::FoldingSetNodeID ID;
2502 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2504 void *InsertPos = nullptr;
2505 if (ConstantArrayType *ATP =
2506 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2507 return QualType(ATP, 0);
2509 // If the element type isn't canonical or has qualifiers, this won't
2510 // be a canonical type either, so fill in the canonical type field.
2512 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2513 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2514 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2515 ASM, IndexTypeQuals);
2516 Canon = getQualifiedType(Canon, canonSplit.Quals);
2518 // Get the new insert position for the node we care about.
2519 ConstantArrayType *NewIP =
2520 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2521 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2524 ConstantArrayType *New = new(*this,TypeAlignment)
2525 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2526 ConstantArrayTypes.InsertNode(New, InsertPos);
2527 Types.push_back(New);
2528 return QualType(New, 0);
2531 /// getVariableArrayDecayedType - Turns the given type, which may be
2532 /// variably-modified, into the corresponding type with all the known
2533 /// sizes replaced with [*].
2534 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2535 // Vastly most common case.
2536 if (!type->isVariablyModifiedType()) return type;
2540 SplitQualType split = type.getSplitDesugaredType();
2541 const Type *ty = split.Ty;
2542 switch (ty->getTypeClass()) {
2543 #define TYPE(Class, Base)
2544 #define ABSTRACT_TYPE(Class, Base)
2545 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2546 #include "clang/AST/TypeNodes.def"
2547 llvm_unreachable("didn't desugar past all non-canonical types?");
2549 // These types should never be variably-modified.
2553 case Type::ExtVector:
2554 case Type::DependentSizedExtVector:
2555 case Type::ObjCObject:
2556 case Type::ObjCInterface:
2557 case Type::ObjCObjectPointer:
2560 case Type::UnresolvedUsing:
2561 case Type::TypeOfExpr:
2563 case Type::Decltype:
2564 case Type::UnaryTransform:
2565 case Type::DependentName:
2566 case Type::InjectedClassName:
2567 case Type::TemplateSpecialization:
2568 case Type::DependentTemplateSpecialization:
2569 case Type::TemplateTypeParm:
2570 case Type::SubstTemplateTypeParmPack:
2572 case Type::PackExpansion:
2573 llvm_unreachable("type should never be variably-modified");
2575 // These types can be variably-modified but should never need to
2577 case Type::FunctionNoProto:
2578 case Type::FunctionProto:
2579 case Type::BlockPointer:
2580 case Type::MemberPointer:
2583 // These types can be variably-modified. All these modifications
2584 // preserve structure except as noted by comments.
2585 // TODO: if we ever care about optimizing VLAs, there are no-op
2586 // optimizations available here.
2588 result = getPointerType(getVariableArrayDecayedType(
2589 cast<PointerType>(ty)->getPointeeType()));
2592 case Type::LValueReference: {
2593 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2594 result = getLValueReferenceType(
2595 getVariableArrayDecayedType(lv->getPointeeType()),
2596 lv->isSpelledAsLValue());
2600 case Type::RValueReference: {
2601 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2602 result = getRValueReferenceType(
2603 getVariableArrayDecayedType(lv->getPointeeType()));
2607 case Type::Atomic: {
2608 const AtomicType *at = cast<AtomicType>(ty);
2609 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2613 case Type::ConstantArray: {
2614 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2615 result = getConstantArrayType(
2616 getVariableArrayDecayedType(cat->getElementType()),
2618 cat->getSizeModifier(),
2619 cat->getIndexTypeCVRQualifiers());
2623 case Type::DependentSizedArray: {
2624 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2625 result = getDependentSizedArrayType(
2626 getVariableArrayDecayedType(dat->getElementType()),
2628 dat->getSizeModifier(),
2629 dat->getIndexTypeCVRQualifiers(),
2630 dat->getBracketsRange());
2634 // Turn incomplete types into [*] types.
2635 case Type::IncompleteArray: {
2636 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2637 result = getVariableArrayType(
2638 getVariableArrayDecayedType(iat->getElementType()),
2641 iat->getIndexTypeCVRQualifiers(),
2646 // Turn VLA types into [*] types.
2647 case Type::VariableArray: {
2648 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2649 result = getVariableArrayType(
2650 getVariableArrayDecayedType(vat->getElementType()),
2653 vat->getIndexTypeCVRQualifiers(),
2654 vat->getBracketsRange());
2659 // Apply the top-level qualifiers from the original.
2660 return getQualifiedType(result, split.Quals);
2663 /// getVariableArrayType - Returns a non-unique reference to the type for a
2664 /// variable array of the specified element type.
2665 QualType ASTContext::getVariableArrayType(QualType EltTy,
2667 ArrayType::ArraySizeModifier ASM,
2668 unsigned IndexTypeQuals,
2669 SourceRange Brackets) const {
2670 // Since we don't unique expressions, it isn't possible to unique VLA's
2671 // that have an expression provided for their size.
2674 // Be sure to pull qualifiers off the element type.
2675 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2676 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2677 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2678 IndexTypeQuals, Brackets);
2679 Canon = getQualifiedType(Canon, canonSplit.Quals);
2682 VariableArrayType *New = new(*this, TypeAlignment)
2683 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2685 VariableArrayTypes.push_back(New);
2686 Types.push_back(New);
2687 return QualType(New, 0);
2690 /// getDependentSizedArrayType - Returns a non-unique reference to
2691 /// the type for a dependently-sized array of the specified element
2693 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2695 ArrayType::ArraySizeModifier ASM,
2696 unsigned elementTypeQuals,
2697 SourceRange brackets) const {
2698 assert((!numElements || numElements->isTypeDependent() ||
2699 numElements->isValueDependent()) &&
2700 "Size must be type- or value-dependent!");
2702 // Dependently-sized array types that do not have a specified number
2703 // of elements will have their sizes deduced from a dependent
2704 // initializer. We do no canonicalization here at all, which is okay
2705 // because they can't be used in most locations.
2707 DependentSizedArrayType *newType
2708 = new (*this, TypeAlignment)
2709 DependentSizedArrayType(*this, elementType, QualType(),
2710 numElements, ASM, elementTypeQuals,
2712 Types.push_back(newType);
2713 return QualType(newType, 0);
2716 // Otherwise, we actually build a new type every time, but we
2717 // also build a canonical type.
2719 SplitQualType canonElementType = getCanonicalType(elementType).split();
2721 void *insertPos = nullptr;
2722 llvm::FoldingSetNodeID ID;
2723 DependentSizedArrayType::Profile(ID, *this,
2724 QualType(canonElementType.Ty, 0),
2725 ASM, elementTypeQuals, numElements);
2727 // Look for an existing type with these properties.
2728 DependentSizedArrayType *canonTy =
2729 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2731 // If we don't have one, build one.
2733 canonTy = new (*this, TypeAlignment)
2734 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2735 QualType(), numElements, ASM, elementTypeQuals,
2737 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2738 Types.push_back(canonTy);
2741 // Apply qualifiers from the element type to the array.
2742 QualType canon = getQualifiedType(QualType(canonTy,0),
2743 canonElementType.Quals);
2745 // If we didn't need extra canonicalization for the element type,
2746 // then just use that as our result.
2747 if (QualType(canonElementType.Ty, 0) == elementType)
2750 // Otherwise, we need to build a type which follows the spelling
2751 // of the element type.
2752 DependentSizedArrayType *sugaredType
2753 = new (*this, TypeAlignment)
2754 DependentSizedArrayType(*this, elementType, canon, numElements,
2755 ASM, elementTypeQuals, brackets);
2756 Types.push_back(sugaredType);
2757 return QualType(sugaredType, 0);
2760 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2761 ArrayType::ArraySizeModifier ASM,
2762 unsigned elementTypeQuals) const {
2763 llvm::FoldingSetNodeID ID;
2764 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2766 void *insertPos = nullptr;
2767 if (IncompleteArrayType *iat =
2768 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2769 return QualType(iat, 0);
2771 // If the element type isn't canonical, this won't be a canonical type
2772 // either, so fill in the canonical type field. We also have to pull
2773 // qualifiers off the element type.
2776 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2777 SplitQualType canonSplit = getCanonicalType(elementType).split();
2778 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2779 ASM, elementTypeQuals);
2780 canon = getQualifiedType(canon, canonSplit.Quals);
2782 // Get the new insert position for the node we care about.
2783 IncompleteArrayType *existing =
2784 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2785 assert(!existing && "Shouldn't be in the map!"); (void) existing;
2788 IncompleteArrayType *newType = new (*this, TypeAlignment)
2789 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2791 IncompleteArrayTypes.InsertNode(newType, insertPos);
2792 Types.push_back(newType);
2793 return QualType(newType, 0);
2796 /// getVectorType - Return the unique reference to a vector type of
2797 /// the specified element type and size. VectorType must be a built-in type.
2798 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2799 VectorType::VectorKind VecKind) const {
2800 assert(vecType->isBuiltinType());
2802 // Check if we've already instantiated a vector of this type.
2803 llvm::FoldingSetNodeID ID;
2804 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2806 void *InsertPos = nullptr;
2807 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2808 return QualType(VTP, 0);
2810 // If the element type isn't canonical, this won't be a canonical type either,
2811 // so fill in the canonical type field.
2813 if (!vecType.isCanonical()) {
2814 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2816 // Get the new insert position for the node we care about.
2817 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2818 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2820 VectorType *New = new (*this, TypeAlignment)
2821 VectorType(vecType, NumElts, Canonical, VecKind);
2822 VectorTypes.InsertNode(New, InsertPos);
2823 Types.push_back(New);
2824 return QualType(New, 0);
2827 /// getExtVectorType - Return the unique reference to an extended vector type of
2828 /// the specified element type and size. VectorType must be a built-in type.
2830 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2831 assert(vecType->isBuiltinType() || vecType->isDependentType());
2833 // Check if we've already instantiated a vector of this type.
2834 llvm::FoldingSetNodeID ID;
2835 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2836 VectorType::GenericVector);
2837 void *InsertPos = nullptr;
2838 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2839 return QualType(VTP, 0);
2841 // If the element type isn't canonical, this won't be a canonical type either,
2842 // so fill in the canonical type field.
2844 if (!vecType.isCanonical()) {
2845 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2847 // Get the new insert position for the node we care about.
2848 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2849 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2851 ExtVectorType *New = new (*this, TypeAlignment)
2852 ExtVectorType(vecType, NumElts, Canonical);
2853 VectorTypes.InsertNode(New, InsertPos);
2854 Types.push_back(New);
2855 return QualType(New, 0);
2859 ASTContext::getDependentSizedExtVectorType(QualType vecType,
2861 SourceLocation AttrLoc) const {
2862 llvm::FoldingSetNodeID ID;
2863 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2866 void *InsertPos = nullptr;
2867 DependentSizedExtVectorType *Canon
2868 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2869 DependentSizedExtVectorType *New;
2871 // We already have a canonical version of this array type; use it as
2872 // the canonical type for a newly-built type.
2873 New = new (*this, TypeAlignment)
2874 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2877 QualType CanonVecTy = getCanonicalType(vecType);
2878 if (CanonVecTy == vecType) {
2879 New = new (*this, TypeAlignment)
2880 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2883 DependentSizedExtVectorType *CanonCheck
2884 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2885 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2887 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2889 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2891 New = new (*this, TypeAlignment)
2892 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2896 Types.push_back(New);
2897 return QualType(New, 0);
2900 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2903 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2904 const FunctionType::ExtInfo &Info) const {
2905 const CallingConv CallConv = Info.getCC();
2907 // Unique functions, to guarantee there is only one function of a particular
2909 llvm::FoldingSetNodeID ID;
2910 FunctionNoProtoType::Profile(ID, ResultTy, Info);
2912 void *InsertPos = nullptr;
2913 if (FunctionNoProtoType *FT =
2914 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2915 return QualType(FT, 0);
2918 if (!ResultTy.isCanonical()) {
2919 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
2921 // Get the new insert position for the node we care about.
2922 FunctionNoProtoType *NewIP =
2923 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2924 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2927 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
2928 FunctionNoProtoType *New = new (*this, TypeAlignment)
2929 FunctionNoProtoType(ResultTy, Canonical, newInfo);
2930 Types.push_back(New);
2931 FunctionNoProtoTypes.InsertNode(New, InsertPos);
2932 return QualType(New, 0);
2935 /// \brief Determine whether \p T is canonical as the result type of a function.
2936 static bool isCanonicalResultType(QualType T) {
2937 return T.isCanonical() &&
2938 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2939 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2943 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
2944 const FunctionProtoType::ExtProtoInfo &EPI) const {
2945 size_t NumArgs = ArgArray.size();
2947 // Unique functions, to guarantee there is only one function of a particular
2949 llvm::FoldingSetNodeID ID;
2950 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2953 void *InsertPos = nullptr;
2954 if (FunctionProtoType *FTP =
2955 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2956 return QualType(FTP, 0);
2958 // Determine whether the type being created is already canonical or not.
2960 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
2961 !EPI.HasTrailingReturn;
2962 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2963 if (!ArgArray[i].isCanonicalAsParam())
2964 isCanonical = false;
2966 // If this type isn't canonical, get the canonical version of it.
2967 // The exception spec is not part of the canonical type.
2970 SmallVector<QualType, 16> CanonicalArgs;
2971 CanonicalArgs.reserve(NumArgs);
2972 for (unsigned i = 0; i != NumArgs; ++i)
2973 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2975 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2976 CanonicalEPI.HasTrailingReturn = false;
2977 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
2979 // Result types do not have ARC lifetime qualifiers.
2980 QualType CanResultTy = getCanonicalType(ResultTy);
2981 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2982 Qualifiers Qs = CanResultTy.getQualifiers();
2983 Qs.removeObjCLifetime();
2984 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2987 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
2989 // Get the new insert position for the node we care about.
2990 FunctionProtoType *NewIP =
2991 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2992 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2995 // FunctionProtoType objects are allocated with extra bytes after
2996 // them for three variable size arrays at the end:
2997 // - parameter types
2998 // - exception types
2999 // - consumed-arguments flags
3000 // Instead of the exception types, there could be a noexcept
3001 // expression, or information used to resolve the exception
3003 size_t Size = sizeof(FunctionProtoType) +
3004 NumArgs * sizeof(QualType);
3005 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3006 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3007 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3008 Size += sizeof(Expr*);
3009 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3010 Size += 2 * sizeof(FunctionDecl*);
3011 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3012 Size += sizeof(FunctionDecl*);
3014 if (EPI.ConsumedParameters)
3015 Size += NumArgs * sizeof(bool);
3017 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
3018 FunctionProtoType::ExtProtoInfo newEPI = EPI;
3019 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3020 Types.push_back(FTP);
3021 FunctionProtoTypes.InsertNode(FTP, InsertPos);
3022 return QualType(FTP, 0);
3026 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3027 if (!isa<CXXRecordDecl>(D)) return false;
3028 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3029 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3031 if (RD->getDescribedClassTemplate() &&
3032 !isa<ClassTemplateSpecializationDecl>(RD))
3038 /// getInjectedClassNameType - Return the unique reference to the
3039 /// injected class name type for the specified templated declaration.
3040 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
3041 QualType TST) const {
3042 assert(NeedsInjectedClassNameType(Decl));
3043 if (Decl->TypeForDecl) {
3044 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3045 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
3046 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3047 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3048 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3051 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
3052 Decl->TypeForDecl = newType;
3053 Types.push_back(newType);
3055 return QualType(Decl->TypeForDecl, 0);
3058 /// getTypeDeclType - Return the unique reference to the type for the
3059 /// specified type declaration.
3060 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3061 assert(Decl && "Passed null for Decl param");
3062 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3064 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3065 return getTypedefType(Typedef);
3067 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3068 "Template type parameter types are always available.");
3070 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
3071 assert(Record->isFirstDecl() && "struct/union has previous declaration");
3072 assert(!NeedsInjectedClassNameType(Record));
3073 return getRecordType(Record);
3074 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
3075 assert(Enum->isFirstDecl() && "enum has previous declaration");
3076 return getEnumType(Enum);
3077 } else if (const UnresolvedUsingTypenameDecl *Using =
3078 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3079 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3080 Decl->TypeForDecl = newType;
3081 Types.push_back(newType);
3083 llvm_unreachable("TypeDecl without a type?");
3085 return QualType(Decl->TypeForDecl, 0);
3088 /// getTypedefType - Return the unique reference to the type for the
3089 /// specified typedef name decl.
3091 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3092 QualType Canonical) const {
3093 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3095 if (Canonical.isNull())
3096 Canonical = getCanonicalType(Decl->getUnderlyingType());
3097 TypedefType *newType = new(*this, TypeAlignment)
3098 TypedefType(Type::Typedef, Decl, Canonical);
3099 Decl->TypeForDecl = newType;
3100 Types.push_back(newType);
3101 return QualType(newType, 0);
3104 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
3105 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3107 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3108 if (PrevDecl->TypeForDecl)
3109 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3111 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3112 Decl->TypeForDecl = newType;
3113 Types.push_back(newType);
3114 return QualType(newType, 0);
3117 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3118 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3120 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3121 if (PrevDecl->TypeForDecl)
3122 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3124 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3125 Decl->TypeForDecl = newType;
3126 Types.push_back(newType);
3127 return QualType(newType, 0);
3130 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3131 QualType modifiedType,
3132 QualType equivalentType) {
3133 llvm::FoldingSetNodeID id;
3134 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3136 void *insertPos = nullptr;
3137 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3138 if (type) return QualType(type, 0);
3140 QualType canon = getCanonicalType(equivalentType);
3141 type = new (*this, TypeAlignment)
3142 AttributedType(canon, attrKind, modifiedType, equivalentType);
3144 Types.push_back(type);
3145 AttributedTypes.InsertNode(type, insertPos);
3147 return QualType(type, 0);
3151 /// \brief Retrieve a substitution-result type.
3153 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3154 QualType Replacement) const {
3155 assert(Replacement.isCanonical()
3156 && "replacement types must always be canonical");
3158 llvm::FoldingSetNodeID ID;
3159 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3160 void *InsertPos = nullptr;
3161 SubstTemplateTypeParmType *SubstParm
3162 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3165 SubstParm = new (*this, TypeAlignment)
3166 SubstTemplateTypeParmType(Parm, Replacement);
3167 Types.push_back(SubstParm);
3168 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3171 return QualType(SubstParm, 0);
3174 /// \brief Retrieve a
3175 QualType ASTContext::getSubstTemplateTypeParmPackType(
3176 const TemplateTypeParmType *Parm,
3177 const TemplateArgument &ArgPack) {
3179 for (const auto &P : ArgPack.pack_elements()) {
3180 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3181 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
3185 llvm::FoldingSetNodeID ID;
3186 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3187 void *InsertPos = nullptr;
3188 if (SubstTemplateTypeParmPackType *SubstParm
3189 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3190 return QualType(SubstParm, 0);
3193 if (!Parm->isCanonicalUnqualified()) {
3194 Canon = getCanonicalType(QualType(Parm, 0));
3195 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3197 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3200 SubstTemplateTypeParmPackType *SubstParm
3201 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3203 Types.push_back(SubstParm);
3204 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3205 return QualType(SubstParm, 0);
3208 /// \brief Retrieve the template type parameter type for a template
3209 /// parameter or parameter pack with the given depth, index, and (optionally)
3211 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3213 TemplateTypeParmDecl *TTPDecl) const {
3214 llvm::FoldingSetNodeID ID;
3215 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3216 void *InsertPos = nullptr;
3217 TemplateTypeParmType *TypeParm
3218 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3221 return QualType(TypeParm, 0);
3224 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3225 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3227 TemplateTypeParmType *TypeCheck
3228 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3229 assert(!TypeCheck && "Template type parameter canonical type broken");
3232 TypeParm = new (*this, TypeAlignment)
3233 TemplateTypeParmType(Depth, Index, ParameterPack);
3235 Types.push_back(TypeParm);
3236 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3238 return QualType(TypeParm, 0);
3242 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3243 SourceLocation NameLoc,
3244 const TemplateArgumentListInfo &Args,
3245 QualType Underlying) const {
3246 assert(!Name.getAsDependentTemplateName() &&
3247 "No dependent template names here!");
3248 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3250 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3251 TemplateSpecializationTypeLoc TL =
3252 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3253 TL.setTemplateKeywordLoc(SourceLocation());
3254 TL.setTemplateNameLoc(NameLoc);
3255 TL.setLAngleLoc(Args.getLAngleLoc());
3256 TL.setRAngleLoc(Args.getRAngleLoc());
3257 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3258 TL.setArgLocInfo(i, Args[i].getLocInfo());
3263 ASTContext::getTemplateSpecializationType(TemplateName Template,
3264 const TemplateArgumentListInfo &Args,
3265 QualType Underlying) const {
3266 assert(!Template.getAsDependentTemplateName() &&
3267 "No dependent template names here!");
3269 unsigned NumArgs = Args.size();
3271 SmallVector<TemplateArgument, 4> ArgVec;
3272 ArgVec.reserve(NumArgs);
3273 for (unsigned i = 0; i != NumArgs; ++i)
3274 ArgVec.push_back(Args[i].getArgument());
3276 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
3281 static bool hasAnyPackExpansions(const TemplateArgument *Args,
3283 for (unsigned I = 0; I != NumArgs; ++I)
3284 if (Args[I].isPackExpansion())
3292 ASTContext::getTemplateSpecializationType(TemplateName Template,
3293 const TemplateArgument *Args,
3295 QualType Underlying) const {
3296 assert(!Template.getAsDependentTemplateName() &&
3297 "No dependent template names here!");
3298 // Look through qualified template names.
3299 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3300 Template = TemplateName(QTN->getTemplateDecl());
3303 Template.getAsTemplateDecl() &&
3304 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3306 if (!Underlying.isNull())
3307 CanonType = getCanonicalType(Underlying);
3309 // We can get here with an alias template when the specialization contains
3310 // a pack expansion that does not match up with a parameter pack.
3311 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3312 "Caller must compute aliased type");
3313 IsTypeAlias = false;
3314 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3318 // Allocate the (non-canonical) template specialization type, but don't
3319 // try to unique it: these types typically have location information that
3320 // we don't unique and don't want to lose.
3321 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3322 sizeof(TemplateArgument) * NumArgs +
3323 (IsTypeAlias? sizeof(QualType) : 0),
3325 TemplateSpecializationType *Spec
3326 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3327 IsTypeAlias ? Underlying : QualType());
3329 Types.push_back(Spec);
3330 return QualType(Spec, 0);
3334 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3335 const TemplateArgument *Args,
3336 unsigned NumArgs) const {
3337 assert(!Template.getAsDependentTemplateName() &&
3338 "No dependent template names here!");
3340 // Look through qualified template names.
3341 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3342 Template = TemplateName(QTN->getTemplateDecl());
3344 // Build the canonical template specialization type.
3345 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3346 SmallVector<TemplateArgument, 4> CanonArgs;
3347 CanonArgs.reserve(NumArgs);
3348 for (unsigned I = 0; I != NumArgs; ++I)
3349 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3351 // Determine whether this canonical template specialization type already
3353 llvm::FoldingSetNodeID ID;
3354 TemplateSpecializationType::Profile(ID, CanonTemplate,
3355 CanonArgs.data(), NumArgs, *this);
3357 void *InsertPos = nullptr;
3358 TemplateSpecializationType *Spec
3359 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3362 // Allocate a new canonical template specialization type.
3363 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3364 sizeof(TemplateArgument) * NumArgs),
3366 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3367 CanonArgs.data(), NumArgs,
3368 QualType(), QualType());
3369 Types.push_back(Spec);
3370 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3373 assert(Spec->isDependentType() &&
3374 "Non-dependent template-id type must have a canonical type");
3375 return QualType(Spec, 0);
3379 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3380 NestedNameSpecifier *NNS,
3381 QualType NamedType) const {
3382 llvm::FoldingSetNodeID ID;
3383 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3385 void *InsertPos = nullptr;
3386 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3388 return QualType(T, 0);
3390 QualType Canon = NamedType;
3391 if (!Canon.isCanonical()) {
3392 Canon = getCanonicalType(NamedType);
3393 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3394 assert(!CheckT && "Elaborated canonical type broken");
3398 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
3400 ElaboratedTypes.InsertNode(T, InsertPos);
3401 return QualType(T, 0);
3405 ASTContext::getParenType(QualType InnerType) const {
3406 llvm::FoldingSetNodeID ID;
3407 ParenType::Profile(ID, InnerType);
3409 void *InsertPos = nullptr;
3410 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3412 return QualType(T, 0);
3414 QualType Canon = InnerType;
3415 if (!Canon.isCanonical()) {
3416 Canon = getCanonicalType(InnerType);
3417 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3418 assert(!CheckT && "Paren canonical type broken");
3422 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
3424 ParenTypes.InsertNode(T, InsertPos);
3425 return QualType(T, 0);
3428 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3429 NestedNameSpecifier *NNS,
3430 const IdentifierInfo *Name,
3431 QualType Canon) const {
3432 if (Canon.isNull()) {
3433 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3434 ElaboratedTypeKeyword CanonKeyword = Keyword;
3435 if (Keyword == ETK_None)
3436 CanonKeyword = ETK_Typename;
3438 if (CanonNNS != NNS || CanonKeyword != Keyword)
3439 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3442 llvm::FoldingSetNodeID ID;
3443 DependentNameType::Profile(ID, Keyword, NNS, Name);
3445 void *InsertPos = nullptr;
3446 DependentNameType *T
3447 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3449 return QualType(T, 0);
3451 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
3453 DependentNameTypes.InsertNode(T, InsertPos);
3454 return QualType(T, 0);
3458 ASTContext::getDependentTemplateSpecializationType(
3459 ElaboratedTypeKeyword Keyword,
3460 NestedNameSpecifier *NNS,
3461 const IdentifierInfo *Name,
3462 const TemplateArgumentListInfo &Args) const {
3463 // TODO: avoid this copy
3464 SmallVector<TemplateArgument, 16> ArgCopy;
3465 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3466 ArgCopy.push_back(Args[I].getArgument());
3467 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3473 ASTContext::getDependentTemplateSpecializationType(
3474 ElaboratedTypeKeyword Keyword,
3475 NestedNameSpecifier *NNS,
3476 const IdentifierInfo *Name,
3478 const TemplateArgument *Args) const {
3479 assert((!NNS || NNS->isDependent()) &&
3480 "nested-name-specifier must be dependent");
3482 llvm::FoldingSetNodeID ID;
3483 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3484 Name, NumArgs, Args);
3486 void *InsertPos = nullptr;
3487 DependentTemplateSpecializationType *T
3488 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3490 return QualType(T, 0);
3492 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3494 ElaboratedTypeKeyword CanonKeyword = Keyword;
3495 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3497 bool AnyNonCanonArgs = false;
3498 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3499 for (unsigned I = 0; I != NumArgs; ++I) {
3500 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3501 if (!CanonArgs[I].structurallyEquals(Args[I]))
3502 AnyNonCanonArgs = true;
3506 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3507 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3511 // Find the insert position again.
3512 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3515 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3516 sizeof(TemplateArgument) * NumArgs),
3518 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3519 Name, NumArgs, Args, Canon);
3521 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3522 return QualType(T, 0);
3525 QualType ASTContext::getPackExpansionType(QualType Pattern,
3526 Optional<unsigned> NumExpansions) {
3527 llvm::FoldingSetNodeID ID;
3528 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3530 assert(Pattern->containsUnexpandedParameterPack() &&
3531 "Pack expansions must expand one or more parameter packs");
3532 void *InsertPos = nullptr;
3533 PackExpansionType *T
3534 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3536 return QualType(T, 0);
3539 if (!Pattern.isCanonical()) {
3540 Canon = getCanonicalType(Pattern);
3541 // The canonical type might not contain an unexpanded parameter pack, if it
3542 // contains an alias template specialization which ignores one of its
3544 if (Canon->containsUnexpandedParameterPack()) {
3545 Canon = getPackExpansionType(Canon, NumExpansions);
3547 // Find the insert position again, in case we inserted an element into
3548 // PackExpansionTypes and invalidated our insert position.
3549 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3553 T = new (*this, TypeAlignment)
3554 PackExpansionType(Pattern, Canon, NumExpansions);
3556 PackExpansionTypes.InsertNode(T, InsertPos);
3557 return QualType(T, 0);
3560 /// CmpProtocolNames - Comparison predicate for sorting protocols
3562 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3563 ObjCProtocolDecl *const *RHS) {
3564 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
3567 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
3568 unsigned NumProtocols) {
3569 if (NumProtocols == 0) return true;
3571 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3574 for (unsigned i = 1; i != NumProtocols; ++i)
3575 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
3576 Protocols[i]->getCanonicalDecl() != Protocols[i])
3581 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
3582 unsigned &NumProtocols) {
3583 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
3585 // Sort protocols, keyed by name.
3586 llvm::array_pod_sort(Protocols, ProtocolsEnd, CmpProtocolNames);
3589 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3590 Protocols[I] = Protocols[I]->getCanonicalDecl();
3592 // Remove duplicates.
3593 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3594 NumProtocols = ProtocolsEnd-Protocols;
3597 QualType ASTContext::getObjCObjectType(QualType BaseType,
3598 ObjCProtocolDecl * const *Protocols,
3599 unsigned NumProtocols) const {
3600 // If the base type is an interface and there aren't any protocols
3601 // to add, then the interface type will do just fine.
3602 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3605 // Look in the folding set for an existing type.
3606 llvm::FoldingSetNodeID ID;
3607 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
3608 void *InsertPos = nullptr;
3609 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3610 return QualType(QT, 0);
3612 // Build the canonical type, which has the canonical base type and
3613 // a sorted-and-uniqued list of protocols.
3615 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3616 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3617 if (!ProtocolsSorted) {
3618 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
3619 Protocols + NumProtocols);
3620 unsigned UniqueCount = NumProtocols;
3622 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
3623 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3624 &Sorted[0], UniqueCount);
3626 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3627 Protocols, NumProtocols);
3630 // Regenerate InsertPos.
3631 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3634 unsigned Size = sizeof(ObjCObjectTypeImpl);
3635 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3636 void *Mem = Allocate(Size, TypeAlignment);
3637 ObjCObjectTypeImpl *T =
3638 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3641 ObjCObjectTypes.InsertNode(T, InsertPos);
3642 return QualType(T, 0);
3645 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3646 /// protocol list adopt all protocols in QT's qualified-id protocol
3648 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3649 ObjCInterfaceDecl *IC) {
3650 if (!QT->isObjCQualifiedIdType())
3653 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3654 // If both the right and left sides have qualifiers.
3655 for (auto *Proto : OPT->quals()) {
3656 if (!IC->ClassImplementsProtocol(Proto, false))
3664 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3665 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
3667 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3668 ObjCInterfaceDecl *IDecl) {
3669 if (!QT->isObjCQualifiedIdType())
3671 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3674 if (!IDecl->hasDefinition())
3676 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3677 CollectInheritedProtocols(IDecl, InheritedProtocols);
3678 if (InheritedProtocols.empty())
3680 // Check that if every protocol in list of id<plist> conforms to a protcol
3681 // of IDecl's, then bridge casting is ok.
3682 bool Conforms = false;
3683 for (auto *Proto : OPT->quals()) {
3685 for (auto *PI : InheritedProtocols) {
3686 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3697 for (auto *PI : InheritedProtocols) {
3698 // If both the right and left sides have qualifiers.
3699 bool Adopts = false;
3700 for (auto *Proto : OPT->quals()) {
3701 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
3702 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
3711 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3712 /// the given object type.
3713 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
3714 llvm::FoldingSetNodeID ID;
3715 ObjCObjectPointerType::Profile(ID, ObjectT);
3717 void *InsertPos = nullptr;
3718 if (ObjCObjectPointerType *QT =
3719 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3720 return QualType(QT, 0);
3722 // Find the canonical object type.
3724 if (!ObjectT.isCanonical()) {
3725 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3727 // Regenerate InsertPos.
3728 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3732 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3733 ObjCObjectPointerType *QType =
3734 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
3736 Types.push_back(QType);
3737 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
3738 return QualType(QType, 0);
3741 /// getObjCInterfaceType - Return the unique reference to the type for the
3742 /// specified ObjC interface decl. The list of protocols is optional.
3743 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3744 ObjCInterfaceDecl *PrevDecl) const {
3745 if (Decl->TypeForDecl)
3746 return QualType(Decl->TypeForDecl, 0);
3749 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3750 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3751 return QualType(PrevDecl->TypeForDecl, 0);
3754 // Prefer the definition, if there is one.
3755 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3758 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3759 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3760 Decl->TypeForDecl = T;
3762 return QualType(T, 0);
3765 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3766 /// TypeOfExprType AST's (since expression's are never shared). For example,
3767 /// multiple declarations that refer to "typeof(x)" all contain different
3768 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
3769 /// on canonical type's (which are always unique).
3770 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
3771 TypeOfExprType *toe;
3772 if (tofExpr->isTypeDependent()) {
3773 llvm::FoldingSetNodeID ID;
3774 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3776 void *InsertPos = nullptr;
3777 DependentTypeOfExprType *Canon
3778 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3780 // We already have a "canonical" version of an identical, dependent
3781 // typeof(expr) type. Use that as our canonical type.
3782 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3783 QualType((TypeOfExprType*)Canon, 0));
3785 // Build a new, canonical typeof(expr) type.
3787 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3788 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3792 QualType Canonical = getCanonicalType(tofExpr->getType());
3793 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3795 Types.push_back(toe);
3796 return QualType(toe, 0);
3799 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3800 /// TypeOfType nodes. The only motivation to unique these nodes would be
3801 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3802 /// an issue. This doesn't affect the type checker, since it operates
3803 /// on canonical types (which are always unique).
3804 QualType ASTContext::getTypeOfType(QualType tofType) const {
3805 QualType Canonical = getCanonicalType(tofType);
3806 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3807 Types.push_back(tot);
3808 return QualType(tot, 0);
3812 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3813 /// nodes. This would never be helpful, since each such type has its own
3814 /// expression, and would not give a significant memory saving, since there
3815 /// is an Expr tree under each such type.
3816 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3819 // C++11 [temp.type]p2:
3820 // If an expression e involves a template parameter, decltype(e) denotes a
3821 // unique dependent type. Two such decltype-specifiers refer to the same
3822 // type only if their expressions are equivalent (14.5.6.1).
3823 if (e->isInstantiationDependent()) {
3824 llvm::FoldingSetNodeID ID;
3825 DependentDecltypeType::Profile(ID, *this, e);
3827 void *InsertPos = nullptr;
3828 DependentDecltypeType *Canon
3829 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3831 // Build a new, canonical typeof(expr) type.
3832 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3833 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3835 dt = new (*this, TypeAlignment)
3836 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
3838 dt = new (*this, TypeAlignment)
3839 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
3841 Types.push_back(dt);
3842 return QualType(dt, 0);
3845 /// getUnaryTransformationType - We don't unique these, since the memory
3846 /// savings are minimal and these are rare.
3847 QualType ASTContext::getUnaryTransformType(QualType BaseType,
3848 QualType UnderlyingType,
3849 UnaryTransformType::UTTKind Kind)
3851 UnaryTransformType *Ty =
3852 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3854 UnderlyingType->isDependentType() ?
3855 QualType() : getCanonicalType(UnderlyingType));
3856 Types.push_back(Ty);
3857 return QualType(Ty, 0);
3860 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
3861 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3862 /// canonical deduced-but-dependent 'auto' type.
3863 QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
3864 bool IsDependent) const {
3865 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3866 return getAutoDeductType();
3868 // Look in the folding set for an existing type.
3869 void *InsertPos = nullptr;
3870 llvm::FoldingSetNodeID ID;
3871 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3872 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3873 return QualType(AT, 0);
3875 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
3878 Types.push_back(AT);
3880 AutoTypes.InsertNode(AT, InsertPos);
3881 return QualType(AT, 0);
3884 /// getAtomicType - Return the uniqued reference to the atomic type for
3885 /// the given value type.
3886 QualType ASTContext::getAtomicType(QualType T) const {
3887 // Unique pointers, to guarantee there is only one pointer of a particular
3889 llvm::FoldingSetNodeID ID;
3890 AtomicType::Profile(ID, T);
3892 void *InsertPos = nullptr;
3893 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3894 return QualType(AT, 0);
3896 // If the atomic value type isn't canonical, this won't be a canonical type
3897 // either, so fill in the canonical type field.
3899 if (!T.isCanonical()) {
3900 Canonical = getAtomicType(getCanonicalType(T));
3902 // Get the new insert position for the node we care about.
3903 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3904 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3906 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3907 Types.push_back(New);
3908 AtomicTypes.InsertNode(New, InsertPos);
3909 return QualType(New, 0);
3912 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
3913 QualType ASTContext::getAutoDeductType() const {
3914 if (AutoDeductTy.isNull())
3915 AutoDeductTy = QualType(
3916 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3917 /*dependent*/false),
3919 return AutoDeductTy;
3922 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3923 QualType ASTContext::getAutoRRefDeductType() const {
3924 if (AutoRRefDeductTy.isNull())
3925 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3926 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3927 return AutoRRefDeductTy;
3930 /// getTagDeclType - Return the unique reference to the type for the
3931 /// specified TagDecl (struct/union/class/enum) decl.
3932 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
3934 // FIXME: What is the design on getTagDeclType when it requires casting
3935 // away const? mutable?
3936 return getTypeDeclType(const_cast<TagDecl*>(Decl));
3939 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3940 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3941 /// needs to agree with the definition in <stddef.h>.
3942 CanQualType ASTContext::getSizeType() const {
3943 return getFromTargetType(Target->getSizeType());
3946 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3947 CanQualType ASTContext::getIntMaxType() const {
3948 return getFromTargetType(Target->getIntMaxType());
3951 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3952 CanQualType ASTContext::getUIntMaxType() const {
3953 return getFromTargetType(Target->getUIntMaxType());
3956 /// getSignedWCharType - Return the type of "signed wchar_t".
3957 /// Used when in C++, as a GCC extension.
3958 QualType ASTContext::getSignedWCharType() const {
3959 // FIXME: derive from "Target" ?
3963 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3964 /// Used when in C++, as a GCC extension.
3965 QualType ASTContext::getUnsignedWCharType() const {
3966 // FIXME: derive from "Target" ?
3967 return UnsignedIntTy;
3970 QualType ASTContext::getIntPtrType() const {
3971 return getFromTargetType(Target->getIntPtrType());
3974 QualType ASTContext::getUIntPtrType() const {
3975 return getCorrespondingUnsignedType(getIntPtrType());
3978 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
3979 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3980 QualType ASTContext::getPointerDiffType() const {
3981 return getFromTargetType(Target->getPtrDiffType(0));
3984 /// \brief Return the unique type for "pid_t" defined in
3985 /// <sys/types.h>. We need this to compute the correct type for vfork().
3986 QualType ASTContext::getProcessIDType() const {
3987 return getFromTargetType(Target->getProcessIDType());
3990 //===----------------------------------------------------------------------===//
3992 //===----------------------------------------------------------------------===//
3994 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
3995 // Push qualifiers into arrays, and then discard any remaining
3997 T = getCanonicalType(T);
3998 T = getVariableArrayDecayedType(T);
3999 const Type *Ty = T.getTypePtr();
4001 if (isa<ArrayType>(Ty)) {
4002 Result = getArrayDecayedType(QualType(Ty,0));
4003 } else if (isa<FunctionType>(Ty)) {
4004 Result = getPointerType(QualType(Ty, 0));
4006 Result = QualType(Ty, 0);
4009 return CanQualType::CreateUnsafe(Result);
4012 QualType ASTContext::getUnqualifiedArrayType(QualType type,
4013 Qualifiers &quals) {
4014 SplitQualType splitType = type.getSplitUnqualifiedType();
4016 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4017 // the unqualified desugared type and then drops it on the floor.
4018 // We then have to strip that sugar back off with
4019 // getUnqualifiedDesugaredType(), which is silly.
4020 const ArrayType *AT =
4021 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
4023 // If we don't have an array, just use the results in splitType.
4025 quals = splitType.Quals;
4026 return QualType(splitType.Ty, 0);
4029 // Otherwise, recurse on the array's element type.
4030 QualType elementType = AT->getElementType();
4031 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4033 // If that didn't change the element type, AT has no qualifiers, so we
4034 // can just use the results in splitType.
4035 if (elementType == unqualElementType) {
4036 assert(quals.empty()); // from the recursive call
4037 quals = splitType.Quals;
4038 return QualType(splitType.Ty, 0);
4041 // Otherwise, add in the qualifiers from the outermost type, then
4042 // build the type back up.
4043 quals.addConsistentQualifiers(splitType.Quals);
4045 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4046 return getConstantArrayType(unqualElementType, CAT->getSize(),
4047 CAT->getSizeModifier(), 0);
4050 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
4051 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
4054 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
4055 return getVariableArrayType(unqualElementType,
4057 VAT->getSizeModifier(),
4058 VAT->getIndexTypeCVRQualifiers(),
4059 VAT->getBracketsRange());
4062 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
4063 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
4064 DSAT->getSizeModifier(), 0,
4068 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4069 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4070 /// they point to and return true. If T1 and T2 aren't pointer types
4071 /// or pointer-to-member types, or if they are not similar at this
4072 /// level, returns false and leaves T1 and T2 unchanged. Top-level
4073 /// qualifiers on T1 and T2 are ignored. This function will typically
4074 /// be called in a loop that successively "unwraps" pointer and
4075 /// pointer-to-member types to compare them at each level.
4076 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4077 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4078 *T2PtrType = T2->getAs<PointerType>();
4079 if (T1PtrType && T2PtrType) {
4080 T1 = T1PtrType->getPointeeType();
4081 T2 = T2PtrType->getPointeeType();
4085 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4086 *T2MPType = T2->getAs<MemberPointerType>();
4087 if (T1MPType && T2MPType &&
4088 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4089 QualType(T2MPType->getClass(), 0))) {
4090 T1 = T1MPType->getPointeeType();
4091 T2 = T2MPType->getPointeeType();
4095 if (getLangOpts().ObjC1) {
4096 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4097 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4098 if (T1OPType && T2OPType) {
4099 T1 = T1OPType->getPointeeType();
4100 T2 = T2OPType->getPointeeType();
4105 // FIXME: Block pointers, too?
4111 ASTContext::getNameForTemplate(TemplateName Name,
4112 SourceLocation NameLoc) const {
4113 switch (Name.getKind()) {
4114 case TemplateName::QualifiedTemplate:
4115 case TemplateName::Template:
4116 // DNInfo work in progress: CHECKME: what about DNLoc?
4117 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4120 case TemplateName::OverloadedTemplate: {
4121 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4122 // DNInfo work in progress: CHECKME: what about DNLoc?
4123 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4126 case TemplateName::DependentTemplate: {
4127 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4128 DeclarationName DName;
4129 if (DTN->isIdentifier()) {
4130 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4131 return DeclarationNameInfo(DName, NameLoc);
4133 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4134 // DNInfo work in progress: FIXME: source locations?
4135 DeclarationNameLoc DNLoc;
4136 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4137 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4138 return DeclarationNameInfo(DName, NameLoc, DNLoc);
4142 case TemplateName::SubstTemplateTemplateParm: {
4143 SubstTemplateTemplateParmStorage *subst
4144 = Name.getAsSubstTemplateTemplateParm();
4145 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4149 case TemplateName::SubstTemplateTemplateParmPack: {
4150 SubstTemplateTemplateParmPackStorage *subst
4151 = Name.getAsSubstTemplateTemplateParmPack();
4152 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4157 llvm_unreachable("bad template name kind!");
4160 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4161 switch (Name.getKind()) {
4162 case TemplateName::QualifiedTemplate:
4163 case TemplateName::Template: {
4164 TemplateDecl *Template = Name.getAsTemplateDecl();
4165 if (TemplateTemplateParmDecl *TTP
4166 = dyn_cast<TemplateTemplateParmDecl>(Template))
4167 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4169 // The canonical template name is the canonical template declaration.
4170 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4173 case TemplateName::OverloadedTemplate:
4174 llvm_unreachable("cannot canonicalize overloaded template");
4176 case TemplateName::DependentTemplate: {
4177 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4178 assert(DTN && "Non-dependent template names must refer to template decls.");
4179 return DTN->CanonicalTemplateName;
4182 case TemplateName::SubstTemplateTemplateParm: {
4183 SubstTemplateTemplateParmStorage *subst
4184 = Name.getAsSubstTemplateTemplateParm();
4185 return getCanonicalTemplateName(subst->getReplacement());
4188 case TemplateName::SubstTemplateTemplateParmPack: {
4189 SubstTemplateTemplateParmPackStorage *subst
4190 = Name.getAsSubstTemplateTemplateParmPack();
4191 TemplateTemplateParmDecl *canonParameter
4192 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4193 TemplateArgument canonArgPack
4194 = getCanonicalTemplateArgument(subst->getArgumentPack());
4195 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4199 llvm_unreachable("bad template name!");
4202 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4203 X = getCanonicalTemplateName(X);
4204 Y = getCanonicalTemplateName(Y);
4205 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4209 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4210 switch (Arg.getKind()) {
4211 case TemplateArgument::Null:
4214 case TemplateArgument::Expression:
4217 case TemplateArgument::Declaration: {
4218 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4219 return TemplateArgument(D, Arg.getParamTypeForDecl());
4222 case TemplateArgument::NullPtr:
4223 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4226 case TemplateArgument::Template:
4227 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4229 case TemplateArgument::TemplateExpansion:
4230 return TemplateArgument(getCanonicalTemplateName(
4231 Arg.getAsTemplateOrTemplatePattern()),
4232 Arg.getNumTemplateExpansions());
4234 case TemplateArgument::Integral:
4235 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4237 case TemplateArgument::Type:
4238 return TemplateArgument(getCanonicalType(Arg.getAsType()));
4240 case TemplateArgument::Pack: {
4241 if (Arg.pack_size() == 0)
4244 TemplateArgument *CanonArgs
4245 = new (*this) TemplateArgument[Arg.pack_size()];
4247 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4248 AEnd = Arg.pack_end();
4249 A != AEnd; (void)++A, ++Idx)
4250 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4252 return TemplateArgument(CanonArgs, Arg.pack_size());
4256 // Silence GCC warning
4257 llvm_unreachable("Unhandled template argument kind");
4260 NestedNameSpecifier *
4261 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4265 switch (NNS->getKind()) {
4266 case NestedNameSpecifier::Identifier:
4267 // Canonicalize the prefix but keep the identifier the same.
4268 return NestedNameSpecifier::Create(*this,
4269 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4270 NNS->getAsIdentifier());
4272 case NestedNameSpecifier::Namespace:
4273 // A namespace is canonical; build a nested-name-specifier with
4274 // this namespace and no prefix.
4275 return NestedNameSpecifier::Create(*this, nullptr,
4276 NNS->getAsNamespace()->getOriginalNamespace());
4278 case NestedNameSpecifier::NamespaceAlias:
4279 // A namespace is canonical; build a nested-name-specifier with
4280 // this namespace and no prefix.
4281 return NestedNameSpecifier::Create(*this, nullptr,
4282 NNS->getAsNamespaceAlias()->getNamespace()
4283 ->getOriginalNamespace());
4285 case NestedNameSpecifier::TypeSpec:
4286 case NestedNameSpecifier::TypeSpecWithTemplate: {
4287 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4289 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4290 // break it apart into its prefix and identifier, then reconsititute those
4291 // as the canonical nested-name-specifier. This is required to canonicalize
4292 // a dependent nested-name-specifier involving typedefs of dependent-name
4294 // typedef typename T::type T1;
4295 // typedef typename T1::type T2;
4296 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4297 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4298 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4300 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4301 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4303 return NestedNameSpecifier::Create(*this, nullptr, false,
4304 const_cast<Type *>(T.getTypePtr()));
4307 case NestedNameSpecifier::Global:
4308 case NestedNameSpecifier::Super:
4309 // The global specifier and __super specifer are canonical and unique.
4313 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4317 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4318 // Handle the non-qualified case efficiently.
4319 if (!T.hasLocalQualifiers()) {
4320 // Handle the common positive case fast.
4321 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4325 // Handle the common negative case fast.
4326 if (!isa<ArrayType>(T.getCanonicalType()))
4329 // Apply any qualifiers from the array type to the element type. This
4330 // implements C99 6.7.3p8: "If the specification of an array type includes
4331 // any type qualifiers, the element type is so qualified, not the array type."
4333 // If we get here, we either have type qualifiers on the type, or we have
4334 // sugar such as a typedef in the way. If we have type qualifiers on the type
4335 // we must propagate them down into the element type.
4337 SplitQualType split = T.getSplitDesugaredType();
4338 Qualifiers qs = split.Quals;
4340 // If we have a simple case, just return now.
4341 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4342 if (!ATy || qs.empty())
4345 // Otherwise, we have an array and we have qualifiers on it. Push the
4346 // qualifiers into the array element type and return a new array type.
4347 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4349 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4350 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4351 CAT->getSizeModifier(),
4352 CAT->getIndexTypeCVRQualifiers()));
4353 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4354 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4355 IAT->getSizeModifier(),
4356 IAT->getIndexTypeCVRQualifiers()));
4358 if (const DependentSizedArrayType *DSAT
4359 = dyn_cast<DependentSizedArrayType>(ATy))
4360 return cast<ArrayType>(
4361 getDependentSizedArrayType(NewEltTy,
4362 DSAT->getSizeExpr(),
4363 DSAT->getSizeModifier(),
4364 DSAT->getIndexTypeCVRQualifiers(),
4365 DSAT->getBracketsRange()));
4367 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4368 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4370 VAT->getSizeModifier(),
4371 VAT->getIndexTypeCVRQualifiers(),
4372 VAT->getBracketsRange()));
4375 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4376 if (T->isArrayType() || T->isFunctionType())
4377 return getDecayedType(T);
4381 QualType ASTContext::getSignatureParameterType(QualType T) const {
4382 T = getVariableArrayDecayedType(T);
4383 T = getAdjustedParameterType(T);
4384 return T.getUnqualifiedType();
4387 QualType ASTContext::getExceptionObjectType(QualType T) const {
4388 // C++ [except.throw]p3:
4389 // A throw-expression initializes a temporary object, called the exception
4390 // object, the type of which is determined by removing any top-level
4391 // cv-qualifiers from the static type of the operand of throw and adjusting
4392 // the type from "array of T" or "function returning T" to "pointer to T"
4393 // or "pointer to function returning T", [...]
4394 T = getVariableArrayDecayedType(T);
4395 if (T->isArrayType() || T->isFunctionType())
4396 T = getDecayedType(T);
4397 return T.getUnqualifiedType();
4400 /// getArrayDecayedType - Return the properly qualified result of decaying the
4401 /// specified array type to a pointer. This operation is non-trivial when
4402 /// handling typedefs etc. The canonical type of "T" must be an array type,
4403 /// this returns a pointer to a properly qualified element of the array.
4405 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4406 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4407 // Get the element type with 'getAsArrayType' so that we don't lose any
4408 // typedefs in the element type of the array. This also handles propagation
4409 // of type qualifiers from the array type into the element type if present
4411 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4412 assert(PrettyArrayType && "Not an array type!");
4414 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4416 // int x[restrict 4] -> int *restrict
4417 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
4420 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4421 return getBaseElementType(array->getElementType());
4424 QualType ASTContext::getBaseElementType(QualType type) const {
4427 SplitQualType split = type.getSplitDesugaredType();
4428 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4431 type = array->getElementType();
4432 qs.addConsistentQualifiers(split.Quals);
4435 return getQualifiedType(type, qs);
4438 /// getConstantArrayElementCount - Returns number of constant array elements.
4440 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4441 uint64_t ElementCount = 1;
4443 ElementCount *= CA->getSize().getZExtValue();
4444 CA = dyn_cast_or_null<ConstantArrayType>(
4445 CA->getElementType()->getAsArrayTypeUnsafe());
4447 return ElementCount;
4450 /// getFloatingRank - Return a relative rank for floating point types.
4451 /// This routine will assert if passed a built-in type that isn't a float.
4452 static FloatingRank getFloatingRank(QualType T) {
4453 if (const ComplexType *CT = T->getAs<ComplexType>())
4454 return getFloatingRank(CT->getElementType());
4456 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4457 switch (T->getAs<BuiltinType>()->getKind()) {
4458 default: llvm_unreachable("getFloatingRank(): not a floating type");
4459 case BuiltinType::Half: return HalfRank;
4460 case BuiltinType::Float: return FloatRank;
4461 case BuiltinType::Double: return DoubleRank;
4462 case BuiltinType::LongDouble: return LongDoubleRank;
4466 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4467 /// point or a complex type (based on typeDomain/typeSize).
4468 /// 'typeDomain' is a real floating point or complex type.
4469 /// 'typeSize' is a real floating point or complex type.
4470 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4471 QualType Domain) const {
4472 FloatingRank EltRank = getFloatingRank(Size);
4473 if (Domain->isComplexType()) {
4475 case HalfRank: llvm_unreachable("Complex half is not supported");
4476 case FloatRank: return FloatComplexTy;
4477 case DoubleRank: return DoubleComplexTy;
4478 case LongDoubleRank: return LongDoubleComplexTy;
4482 assert(Domain->isRealFloatingType() && "Unknown domain!");
4484 case HalfRank: return HalfTy;
4485 case FloatRank: return FloatTy;
4486 case DoubleRank: return DoubleTy;
4487 case LongDoubleRank: return LongDoubleTy;
4489 llvm_unreachable("getFloatingRank(): illegal value for rank");
4492 /// getFloatingTypeOrder - Compare the rank of the two specified floating
4493 /// point types, ignoring the domain of the type (i.e. 'double' ==
4494 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
4495 /// LHS < RHS, return -1.
4496 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
4497 FloatingRank LHSR = getFloatingRank(LHS);
4498 FloatingRank RHSR = getFloatingRank(RHS);
4507 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4508 /// routine will assert if passed a built-in type that isn't an integer or enum,
4509 /// or if it is not canonicalized.
4510 unsigned ASTContext::getIntegerRank(const Type *T) const {
4511 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
4513 switch (cast<BuiltinType>(T)->getKind()) {
4514 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
4515 case BuiltinType::Bool:
4516 return 1 + (getIntWidth(BoolTy) << 3);
4517 case BuiltinType::Char_S:
4518 case BuiltinType::Char_U:
4519 case BuiltinType::SChar:
4520 case BuiltinType::UChar:
4521 return 2 + (getIntWidth(CharTy) << 3);
4522 case BuiltinType::Short:
4523 case BuiltinType::UShort:
4524 return 3 + (getIntWidth(ShortTy) << 3);
4525 case BuiltinType::Int:
4526 case BuiltinType::UInt:
4527 return 4 + (getIntWidth(IntTy) << 3);
4528 case BuiltinType::Long:
4529 case BuiltinType::ULong:
4530 return 5 + (getIntWidth(LongTy) << 3);
4531 case BuiltinType::LongLong:
4532 case BuiltinType::ULongLong:
4533 return 6 + (getIntWidth(LongLongTy) << 3);
4534 case BuiltinType::Int128:
4535 case BuiltinType::UInt128:
4536 return 7 + (getIntWidth(Int128Ty) << 3);
4540 /// \brief Whether this is a promotable bitfield reference according
4541 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4543 /// \returns the type this bit-field will promote to, or NULL if no
4544 /// promotion occurs.
4545 QualType ASTContext::isPromotableBitField(Expr *E) const {
4546 if (E->isTypeDependent() || E->isValueDependent())
4549 // FIXME: We should not do this unless E->refersToBitField() is true. This
4550 // matters in C where getSourceBitField() will find bit-fields for various
4551 // cases where the source expression is not a bit-field designator.
4553 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
4557 QualType FT = Field->getType();
4559 uint64_t BitWidth = Field->getBitWidthValue(*this);
4560 uint64_t IntSize = getTypeSize(IntTy);
4561 // C++ [conv.prom]p5:
4562 // A prvalue for an integral bit-field can be converted to a prvalue of type
4563 // int if int can represent all the values of the bit-field; otherwise, it
4564 // can be converted to unsigned int if unsigned int can represent all the
4565 // values of the bit-field. If the bit-field is larger yet, no integral
4566 // promotion applies to it.
4568 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4569 // If an int can represent all values of the original type (as restricted by
4570 // the width, for a bit-field), the value is converted to an int; otherwise,
4571 // it is converted to an unsigned int.
4573 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4574 // We perform that promotion here to match GCC and C++.
4575 if (BitWidth < IntSize)
4578 if (BitWidth == IntSize)
4579 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4581 // Types bigger than int are not subject to promotions, and therefore act
4582 // like the base type. GCC has some weird bugs in this area that we
4583 // deliberately do not follow (GCC follows a pre-standard resolution to
4584 // C's DR315 which treats bit-width as being part of the type, and this leaks
4585 // into their semantics in some cases).
4589 /// getPromotedIntegerType - Returns the type that Promotable will
4590 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4592 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
4593 assert(!Promotable.isNull());
4594 assert(Promotable->isPromotableIntegerType());
4595 if (const EnumType *ET = Promotable->getAs<EnumType>())
4596 return ET->getDecl()->getPromotionType();
4598 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4599 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4600 // (3.9.1) can be converted to a prvalue of the first of the following
4601 // types that can represent all the values of its underlying type:
4602 // int, unsigned int, long int, unsigned long int, long long int, or
4603 // unsigned long long int [...]
4604 // FIXME: Is there some better way to compute this?
4605 if (BT->getKind() == BuiltinType::WChar_S ||
4606 BT->getKind() == BuiltinType::WChar_U ||
4607 BT->getKind() == BuiltinType::Char16 ||
4608 BT->getKind() == BuiltinType::Char32) {
4609 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4610 uint64_t FromSize = getTypeSize(BT);
4611 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4612 LongLongTy, UnsignedLongLongTy };
4613 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4614 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4615 if (FromSize < ToSize ||
4616 (FromSize == ToSize &&
4617 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4618 return PromoteTypes[Idx];
4620 llvm_unreachable("char type should fit into long long");
4624 // At this point, we should have a signed or unsigned integer type.
4625 if (Promotable->isSignedIntegerType())
4627 uint64_t PromotableSize = getIntWidth(Promotable);
4628 uint64_t IntSize = getIntWidth(IntTy);
4629 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4630 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4633 /// \brief Recurses in pointer/array types until it finds an objc retainable
4634 /// type and returns its ownership.
4635 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4636 while (!T.isNull()) {
4637 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4638 return T.getObjCLifetime();
4639 if (T->isArrayType())
4640 T = getBaseElementType(T);
4641 else if (const PointerType *PT = T->getAs<PointerType>())
4642 T = PT->getPointeeType();
4643 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4644 T = RT->getPointeeType();
4649 return Qualifiers::OCL_None;
4652 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4653 // Incomplete enum types are not treated as integer types.
4654 // FIXME: In C++, enum types are never integer types.
4655 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4656 return ET->getDecl()->getIntegerType().getTypePtr();
4660 /// getIntegerTypeOrder - Returns the highest ranked integer type:
4661 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
4662 /// LHS < RHS, return -1.
4663 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
4664 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4665 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
4667 // Unwrap enums to their underlying type.
4668 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4669 LHSC = getIntegerTypeForEnum(ET);
4670 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4671 RHSC = getIntegerTypeForEnum(ET);
4673 if (LHSC == RHSC) return 0;
4675 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4676 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
4678 unsigned LHSRank = getIntegerRank(LHSC);
4679 unsigned RHSRank = getIntegerRank(RHSC);
4681 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4682 if (LHSRank == RHSRank) return 0;
4683 return LHSRank > RHSRank ? 1 : -1;
4686 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4688 // If the unsigned [LHS] type is larger, return it.
4689 if (LHSRank >= RHSRank)
4692 // If the signed type can represent all values of the unsigned type, it
4693 // wins. Because we are dealing with 2's complement and types that are
4694 // powers of two larger than each other, this is always safe.
4698 // If the unsigned [RHS] type is larger, return it.
4699 if (RHSRank >= LHSRank)
4702 // If the signed type can represent all values of the unsigned type, it
4703 // wins. Because we are dealing with 2's complement and types that are
4704 // powers of two larger than each other, this is always safe.
4708 // getCFConstantStringType - Return the type used for constant CFStrings.
4709 QualType ASTContext::getCFConstantStringType() const {
4710 if (!CFConstantStringTypeDecl) {
4711 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
4712 CFConstantStringTypeDecl->startDefinition();
4714 QualType FieldTypes[4];
4717 FieldTypes[0] = getPointerType(IntTy.withConst());
4719 FieldTypes[1] = IntTy;
4721 FieldTypes[2] = getPointerType(CharTy.withConst());
4723 FieldTypes[3] = LongTy;
4726 for (unsigned i = 0; i < 4; ++i) {
4727 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
4729 SourceLocation(), nullptr,
4730 FieldTypes[i], /*TInfo=*/nullptr,
4731 /*BitWidth=*/nullptr,
4734 Field->setAccess(AS_public);
4735 CFConstantStringTypeDecl->addDecl(Field);
4738 CFConstantStringTypeDecl->completeDefinition();
4741 return getTagDeclType(CFConstantStringTypeDecl);
4744 QualType ASTContext::getObjCSuperType() const {
4745 if (ObjCSuperType.isNull()) {
4746 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
4747 TUDecl->addDecl(ObjCSuperTypeDecl);
4748 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4750 return ObjCSuperType;
4753 void ASTContext::setCFConstantStringType(QualType T) {
4754 const RecordType *Rec = T->getAs<RecordType>();
4755 assert(Rec && "Invalid CFConstantStringType");
4756 CFConstantStringTypeDecl = Rec->getDecl();
4759 QualType ASTContext::getBlockDescriptorType() const {
4760 if (BlockDescriptorType)
4761 return getTagDeclType(BlockDescriptorType);
4764 // FIXME: Needs the FlagAppleBlock bit.
4765 RD = buildImplicitRecord("__block_descriptor");
4766 RD->startDefinition();
4768 QualType FieldTypes[] = {
4773 static const char *const FieldNames[] = {
4778 for (size_t i = 0; i < 2; ++i) {
4779 FieldDecl *Field = FieldDecl::Create(
4780 *this, RD, SourceLocation(), SourceLocation(),
4781 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4782 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
4783 Field->setAccess(AS_public);
4787 RD->completeDefinition();
4789 BlockDescriptorType = RD;
4791 return getTagDeclType(BlockDescriptorType);
4794 QualType ASTContext::getBlockDescriptorExtendedType() const {
4795 if (BlockDescriptorExtendedType)
4796 return getTagDeclType(BlockDescriptorExtendedType);
4799 // FIXME: Needs the FlagAppleBlock bit.
4800 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4801 RD->startDefinition();
4803 QualType FieldTypes[] = {
4806 getPointerType(VoidPtrTy),
4807 getPointerType(VoidPtrTy)
4810 static const char *const FieldNames[] = {
4817 for (size_t i = 0; i < 4; ++i) {
4818 FieldDecl *Field = FieldDecl::Create(
4819 *this, RD, SourceLocation(), SourceLocation(),
4820 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4821 /*BitWidth=*/nullptr,
4822 /*Mutable=*/false, ICIS_NoInit);
4823 Field->setAccess(AS_public);
4827 RD->completeDefinition();
4829 BlockDescriptorExtendedType = RD;
4830 return getTagDeclType(BlockDescriptorExtendedType);
4833 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4834 /// requires copy/dispose. Note that this must match the logic
4835 /// in buildByrefHelpers.
4836 bool ASTContext::BlockRequiresCopying(QualType Ty,
4838 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4839 const Expr *copyExpr = getBlockVarCopyInits(D);
4840 if (!copyExpr && record->hasTrivialDestructor()) return false;
4845 if (!Ty->isObjCRetainableType()) return false;
4847 Qualifiers qs = Ty.getQualifiers();
4849 // If we have lifetime, that dominates.
4850 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4851 assert(getLangOpts().ObjCAutoRefCount);
4854 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4856 // These are just bits as far as the runtime is concerned.
4857 case Qualifiers::OCL_ExplicitNone:
4858 case Qualifiers::OCL_Autoreleasing:
4861 // Tell the runtime that this is ARC __weak, called by the
4863 case Qualifiers::OCL_Weak:
4864 // ARC __strong __block variables need to be retained.
4865 case Qualifiers::OCL_Strong:
4868 llvm_unreachable("fell out of lifetime switch!");
4870 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4871 Ty->isObjCObjectPointerType());
4874 bool ASTContext::getByrefLifetime(QualType Ty,
4875 Qualifiers::ObjCLifetime &LifeTime,
4876 bool &HasByrefExtendedLayout) const {
4878 if (!getLangOpts().ObjC1 ||
4879 getLangOpts().getGC() != LangOptions::NonGC)
4882 HasByrefExtendedLayout = false;
4883 if (Ty->isRecordType()) {
4884 HasByrefExtendedLayout = true;
4885 LifeTime = Qualifiers::OCL_None;
4887 else if (getLangOpts().ObjCAutoRefCount)
4888 LifeTime = Ty.getObjCLifetime();
4890 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4891 LifeTime = Qualifiers::OCL_ExplicitNone;
4893 LifeTime = Qualifiers::OCL_None;
4897 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4898 if (!ObjCInstanceTypeDecl)
4899 ObjCInstanceTypeDecl =
4900 buildImplicitTypedef(getObjCIdType(), "instancetype");
4901 return ObjCInstanceTypeDecl;
4904 // This returns true if a type has been typedefed to BOOL:
4905 // typedef <type> BOOL;
4906 static bool isTypeTypedefedAsBOOL(QualType T) {
4907 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
4908 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4909 return II->isStr("BOOL");
4914 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
4916 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
4917 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4918 return CharUnits::Zero();
4920 CharUnits sz = getTypeSizeInChars(type);
4922 // Make all integer and enum types at least as large as an int
4923 if (sz.isPositive() && type->isIntegralOrEnumerationType())
4924 sz = std::max(sz, getTypeSizeInChars(IntTy));
4925 // Treat arrays as pointers, since that's how they're passed in.
4926 else if (type->isArrayType())
4927 sz = getTypeSizeInChars(VoidPtrTy);
4931 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4932 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4933 VD->getType()->isIntegralOrEnumerationType() &&
4934 VD->isFirstDecl() && !VD->isOutOfLine() && VD->hasInit();
4938 std::string charUnitsToString(const CharUnits &CU) {
4939 return llvm::itostr(CU.getQuantity());
4942 /// getObjCEncodingForBlock - Return the encoded type for this block
4944 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4947 const BlockDecl *Decl = Expr->getBlockDecl();
4949 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4950 // Encode result type.
4951 if (getLangOpts().EncodeExtendedBlockSig)
4952 getObjCEncodingForMethodParameter(
4953 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4956 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
4957 // Compute size of all parameters.
4958 // Start with computing size of a pointer in number of bytes.
4959 // FIXME: There might(should) be a better way of doing this computation!
4961 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4962 CharUnits ParmOffset = PtrSize;
4963 for (auto PI : Decl->params()) {
4964 QualType PType = PI->getType();
4965 CharUnits sz = getObjCEncodingTypeSize(PType);
4968 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
4971 // Size of the argument frame
4972 S += charUnitsToString(ParmOffset);
4973 // Block pointer and offset.
4977 ParmOffset = PtrSize;
4978 for (auto PVDecl : Decl->params()) {
4979 QualType PType = PVDecl->getOriginalType();
4980 if (const ArrayType *AT =
4981 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4982 // Use array's original type only if it has known number of
4984 if (!isa<ConstantArrayType>(AT))
4985 PType = PVDecl->getType();
4986 } else if (PType->isFunctionType())
4987 PType = PVDecl->getType();
4988 if (getLangOpts().EncodeExtendedBlockSig)
4989 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4990 S, true /*Extended*/);
4992 getObjCEncodingForType(PType, S);
4993 S += charUnitsToString(ParmOffset);
4994 ParmOffset += getObjCEncodingTypeSize(PType);
5000 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
5002 // Encode result type.
5003 getObjCEncodingForType(Decl->getReturnType(), S);
5004 CharUnits ParmOffset;
5005 // Compute size of all parameters.
5006 for (auto PI : Decl->params()) {
5007 QualType PType = PI->getType();
5008 CharUnits sz = getObjCEncodingTypeSize(PType);
5012 assert (sz.isPositive() &&
5013 "getObjCEncodingForFunctionDecl - Incomplete param type");
5016 S += charUnitsToString(ParmOffset);
5017 ParmOffset = CharUnits::Zero();
5020 for (auto PVDecl : Decl->params()) {
5021 QualType PType = PVDecl->getOriginalType();
5022 if (const ArrayType *AT =
5023 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5024 // Use array's original type only if it has known number of
5026 if (!isa<ConstantArrayType>(AT))
5027 PType = PVDecl->getType();
5028 } else if (PType->isFunctionType())
5029 PType = PVDecl->getType();
5030 getObjCEncodingForType(PType, S);
5031 S += charUnitsToString(ParmOffset);
5032 ParmOffset += getObjCEncodingTypeSize(PType);
5038 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
5039 /// method parameter or return type. If Extended, include class names and
5040 /// block object types.
5041 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5042 QualType T, std::string& S,
5043 bool Extended) const {
5044 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5045 getObjCEncodingForTypeQualifier(QT, S);
5046 // Encode parameter type.
5047 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5048 true /*OutermostType*/,
5049 false /*EncodingProperty*/,
5050 false /*StructField*/,
5051 Extended /*EncodeBlockParameters*/,
5052 Extended /*EncodeClassNames*/);
5055 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
5057 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5059 bool Extended) const {
5060 // FIXME: This is not very efficient.
5061 // Encode return type.
5062 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5063 Decl->getReturnType(), S, Extended);
5064 // Compute size of all parameters.
5065 // Start with computing size of a pointer in number of bytes.
5066 // FIXME: There might(should) be a better way of doing this computation!
5068 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5069 // The first two arguments (self and _cmd) are pointers; account for
5071 CharUnits ParmOffset = 2 * PtrSize;
5072 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5073 E = Decl->sel_param_end(); PI != E; ++PI) {
5074 QualType PType = (*PI)->getType();
5075 CharUnits sz = getObjCEncodingTypeSize(PType);
5079 assert (sz.isPositive() &&
5080 "getObjCEncodingForMethodDecl - Incomplete param type");
5083 S += charUnitsToString(ParmOffset);
5085 S += charUnitsToString(PtrSize);
5088 ParmOffset = 2 * PtrSize;
5089 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5090 E = Decl->sel_param_end(); PI != E; ++PI) {
5091 const ParmVarDecl *PVDecl = *PI;
5092 QualType PType = PVDecl->getOriginalType();
5093 if (const ArrayType *AT =
5094 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5095 // Use array's original type only if it has known number of
5097 if (!isa<ConstantArrayType>(AT))
5098 PType = PVDecl->getType();
5099 } else if (PType->isFunctionType())
5100 PType = PVDecl->getType();
5101 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5102 PType, S, Extended);
5103 S += charUnitsToString(ParmOffset);
5104 ParmOffset += getObjCEncodingTypeSize(PType);
5110 ObjCPropertyImplDecl *
5111 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5112 const ObjCPropertyDecl *PD,
5113 const Decl *Container) const {
5116 if (const ObjCCategoryImplDecl *CID =
5117 dyn_cast<ObjCCategoryImplDecl>(Container)) {
5118 for (auto *PID : CID->property_impls())
5119 if (PID->getPropertyDecl() == PD)
5122 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5123 for (auto *PID : OID->property_impls())
5124 if (PID->getPropertyDecl() == PD)
5130 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
5131 /// property declaration. If non-NULL, Container must be either an
5132 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5133 /// NULL when getting encodings for protocol properties.
5134 /// Property attributes are stored as a comma-delimited C string. The simple
5135 /// attributes readonly and bycopy are encoded as single characters. The
5136 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
5137 /// encoded as single characters, followed by an identifier. Property types
5138 /// are also encoded as a parametrized attribute. The characters used to encode
5139 /// these attributes are defined by the following enumeration:
5141 /// enum PropertyAttributes {
5142 /// kPropertyReadOnly = 'R', // property is read-only.
5143 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5144 /// kPropertyByref = '&', // property is a reference to the value last assigned
5145 /// kPropertyDynamic = 'D', // property is dynamic
5146 /// kPropertyGetter = 'G', // followed by getter selector name
5147 /// kPropertySetter = 'S', // followed by setter selector name
5148 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
5149 /// kPropertyType = 'T' // followed by old-style type encoding.
5150 /// kPropertyWeak = 'W' // 'weak' property
5151 /// kPropertyStrong = 'P' // property GC'able
5152 /// kPropertyNonAtomic = 'N' // property non-atomic
5155 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5156 const Decl *Container,
5157 std::string& S) const {
5158 // Collect information from the property implementation decl(s).
5159 bool Dynamic = false;
5160 ObjCPropertyImplDecl *SynthesizePID = nullptr;
5162 if (ObjCPropertyImplDecl *PropertyImpDecl =
5163 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5164 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5167 SynthesizePID = PropertyImpDecl;
5170 // FIXME: This is not very efficient.
5173 // Encode result type.
5174 // GCC has some special rules regarding encoding of properties which
5175 // closely resembles encoding of ivars.
5176 getObjCEncodingForPropertyType(PD->getType(), S);
5178 if (PD->isReadOnly()) {
5180 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5182 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5184 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5187 switch (PD->getSetterKind()) {
5188 case ObjCPropertyDecl::Assign: break;
5189 case ObjCPropertyDecl::Copy: S += ",C"; break;
5190 case ObjCPropertyDecl::Retain: S += ",&"; break;
5191 case ObjCPropertyDecl::Weak: S += ",W"; break;
5195 // It really isn't clear at all what this means, since properties
5196 // are "dynamic by default".
5200 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5203 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5205 S += PD->getGetterName().getAsString();
5208 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5210 S += PD->getSetterName().getAsString();
5213 if (SynthesizePID) {
5214 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5216 S += OID->getNameAsString();
5219 // FIXME: OBJCGC: weak & strong
5222 /// getLegacyIntegralTypeEncoding -
5223 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5224 /// 'l' or 'L' , but not always. For typedefs, we need to use
5225 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5227 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5228 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5229 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5230 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5231 PointeeTy = UnsignedIntTy;
5233 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5239 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5240 const FieldDecl *Field,
5241 QualType *NotEncodedT) const {
5242 // We follow the behavior of gcc, expanding structures which are
5243 // directly pointed to, and expanding embedded structures. Note that
5244 // these rules are sufficient to prevent recursive encoding of the
5246 getObjCEncodingForTypeImpl(T, S, true, true, Field,
5247 true /* outermost type */, false, false,
5248 false, false, false, NotEncodedT);
5251 void ASTContext::getObjCEncodingForPropertyType(QualType T,
5252 std::string& S) const {
5253 // Encode result type.
5254 // GCC has some special rules regarding encoding of properties which
5255 // closely resembles encoding of ivars.
5256 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5257 true /* outermost type */,
5258 true /* encoding property */);
5261 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5262 BuiltinType::Kind kind) {
5264 case BuiltinType::Void: return 'v';
5265 case BuiltinType::Bool: return 'B';
5266 case BuiltinType::Char_U:
5267 case BuiltinType::UChar: return 'C';
5268 case BuiltinType::Char16:
5269 case BuiltinType::UShort: return 'S';
5270 case BuiltinType::Char32:
5271 case BuiltinType::UInt: return 'I';
5272 case BuiltinType::ULong:
5273 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5274 case BuiltinType::UInt128: return 'T';
5275 case BuiltinType::ULongLong: return 'Q';
5276 case BuiltinType::Char_S:
5277 case BuiltinType::SChar: return 'c';
5278 case BuiltinType::Short: return 's';
5279 case BuiltinType::WChar_S:
5280 case BuiltinType::WChar_U:
5281 case BuiltinType::Int: return 'i';
5282 case BuiltinType::Long:
5283 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5284 case BuiltinType::LongLong: return 'q';
5285 case BuiltinType::Int128: return 't';
5286 case BuiltinType::Float: return 'f';
5287 case BuiltinType::Double: return 'd';
5288 case BuiltinType::LongDouble: return 'D';
5289 case BuiltinType::NullPtr: return '*'; // like char*
5291 case BuiltinType::Half:
5292 // FIXME: potentially need @encodes for these!
5295 case BuiltinType::ObjCId:
5296 case BuiltinType::ObjCClass:
5297 case BuiltinType::ObjCSel:
5298 llvm_unreachable("@encoding ObjC primitive type");
5300 // OpenCL and placeholder types don't need @encodings.
5301 case BuiltinType::OCLImage1d:
5302 case BuiltinType::OCLImage1dArray:
5303 case BuiltinType::OCLImage1dBuffer:
5304 case BuiltinType::OCLImage2d:
5305 case BuiltinType::OCLImage2dArray:
5306 case BuiltinType::OCLImage3d:
5307 case BuiltinType::OCLEvent:
5308 case BuiltinType::OCLSampler:
5309 case BuiltinType::Dependent:
5310 #define BUILTIN_TYPE(KIND, ID)
5311 #define PLACEHOLDER_TYPE(KIND, ID) \
5312 case BuiltinType::KIND:
5313 #include "clang/AST/BuiltinTypes.def"
5314 llvm_unreachable("invalid builtin type for @encode");
5316 llvm_unreachable("invalid BuiltinType::Kind value");
5319 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5320 EnumDecl *Enum = ET->getDecl();
5322 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5323 if (!Enum->isFixed())
5326 // The encoding of a fixed enum type matches its fixed underlying type.
5327 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5328 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5331 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5332 QualType T, const FieldDecl *FD) {
5333 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5335 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5336 // The GNU runtime requires more information; bitfields are encoded as b,
5337 // then the offset (in bits) of the first element, then the type of the
5338 // bitfield, then the size in bits. For example, in this structure:
5345 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5346 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5347 // information is not especially sensible, but we're stuck with it for
5348 // compatibility with GCC, although providing it breaks anything that
5349 // actually uses runtime introspection and wants to work on both runtimes...
5350 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5351 const RecordDecl *RD = FD->getParent();
5352 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5353 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5354 if (const EnumType *ET = T->getAs<EnumType>())
5355 S += ObjCEncodingForEnumType(Ctx, ET);
5357 const BuiltinType *BT = T->castAs<BuiltinType>();
5358 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5361 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5364 // FIXME: Use SmallString for accumulating string.
5365 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5366 bool ExpandPointedToStructures,
5367 bool ExpandStructures,
5368 const FieldDecl *FD,
5370 bool EncodingProperty,
5372 bool EncodeBlockParameters,
5373 bool EncodeClassNames,
5374 bool EncodePointerToObjCTypedef,
5375 QualType *NotEncodedT) const {
5376 CanQualType CT = getCanonicalType(T);
5377 switch (CT->getTypeClass()) {
5380 if (FD && FD->isBitField())
5381 return EncodeBitField(this, S, T, FD);
5382 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5383 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5385 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5388 case Type::Complex: {
5389 const ComplexType *CT = T->castAs<ComplexType>();
5391 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
5395 case Type::Atomic: {
5396 const AtomicType *AT = T->castAs<AtomicType>();
5398 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
5402 // encoding for pointer or reference types.
5404 case Type::LValueReference:
5405 case Type::RValueReference: {
5407 if (isa<PointerType>(CT)) {
5408 const PointerType *PT = T->castAs<PointerType>();
5409 if (PT->isObjCSelType()) {
5413 PointeeTy = PT->getPointeeType();
5415 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5418 bool isReadOnly = false;
5419 // For historical/compatibility reasons, the read-only qualifier of the
5420 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5421 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5422 // Also, do not emit the 'r' for anything but the outermost type!
5423 if (isa<TypedefType>(T.getTypePtr())) {
5424 if (OutermostType && T.isConstQualified()) {
5428 } else if (OutermostType) {
5429 QualType P = PointeeTy;
5430 while (P->getAs<PointerType>())
5431 P = P->getAs<PointerType>()->getPointeeType();
5432 if (P.isConstQualified()) {
5438 // Another legacy compatibility encoding. Some ObjC qualifier and type
5439 // combinations need to be rearranged.
5440 // Rewrite "in const" from "nr" to "rn"
5441 if (StringRef(S).endswith("nr"))
5442 S.replace(S.end()-2, S.end(), "rn");
5445 if (PointeeTy->isCharType()) {
5446 // char pointer types should be encoded as '*' unless it is a
5447 // type that has been typedef'd to 'BOOL'.
5448 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5452 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5453 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5454 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5458 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5459 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5466 getLegacyIntegralTypeEncoding(PointeeTy);
5468 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5469 nullptr, false, false, false, false, false, false,
5474 case Type::ConstantArray:
5475 case Type::IncompleteArray:
5476 case Type::VariableArray: {
5477 const ArrayType *AT = cast<ArrayType>(CT);
5479 if (isa<IncompleteArrayType>(AT) && !StructField) {
5480 // Incomplete arrays are encoded as a pointer to the array element.
5483 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5484 false, ExpandStructures, FD);
5488 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5489 S += llvm::utostr(CAT->getSize().getZExtValue());
5491 //Variable length arrays are encoded as a regular array with 0 elements.
5492 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5493 "Unknown array type!");
5497 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5498 false, ExpandStructures, FD,
5499 false, false, false, false, false, false,
5506 case Type::FunctionNoProto:
5507 case Type::FunctionProto:
5511 case Type::Record: {
5512 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5513 S += RDecl->isUnion() ? '(' : '{';
5514 // Anonymous structures print as '?'
5515 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5517 if (ClassTemplateSpecializationDecl *Spec
5518 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5519 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5520 llvm::raw_string_ostream OS(S);
5521 TemplateSpecializationType::PrintTemplateArgumentList(OS,
5522 TemplateArgs.data(),
5523 TemplateArgs.size(),
5524 (*this).getPrintingPolicy());
5529 if (ExpandStructures) {
5531 if (!RDecl->isUnion()) {
5532 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
5534 for (const auto *Field : RDecl->fields()) {
5537 S += Field->getNameAsString();
5541 // Special case bit-fields.
5542 if (Field->isBitField()) {
5543 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5546 QualType qt = Field->getType();
5547 getLegacyIntegralTypeEncoding(qt);
5548 getObjCEncodingForTypeImpl(qt, S, false, true,
5549 FD, /*OutermostType*/false,
5550 /*EncodingProperty*/false,
5551 /*StructField*/true,
5552 false, false, false, NotEncodedT);
5557 S += RDecl->isUnion() ? ')' : '}';
5561 case Type::BlockPointer: {
5562 const BlockPointerType *BT = T->castAs<BlockPointerType>();
5563 S += "@?"; // Unlike a pointer-to-function, which is "^?".
5564 if (EncodeBlockParameters) {
5565 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5568 // Block return type
5569 getObjCEncodingForTypeImpl(
5570 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5571 FD, false /* OutermostType */, EncodingProperty,
5572 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5577 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5578 for (const auto &I : FPT->param_types())
5579 getObjCEncodingForTypeImpl(
5580 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5581 false /* OutermostType */, EncodingProperty,
5582 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5583 false, NotEncodedT);
5590 case Type::ObjCObject: {
5591 // hack to match legacy encoding of *id and *Class
5592 QualType Ty = getObjCObjectPointerType(CT);
5593 if (Ty->isObjCIdType()) {
5594 S += "{objc_object=}";
5597 else if (Ty->isObjCClassType()) {
5598 S += "{objc_class=}";
5603 case Type::ObjCInterface: {
5604 // Ignore protocol qualifiers when mangling at this level.
5605 T = T->castAs<ObjCObjectType>()->getBaseType();
5607 // The assumption seems to be that this assert will succeed
5608 // because nested levels will have filtered out 'id' and 'Class'.
5609 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
5610 // @encode(class_name)
5611 ObjCInterfaceDecl *OI = OIT->getDecl();
5613 const IdentifierInfo *II = OI->getIdentifier();
5616 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5617 DeepCollectObjCIvars(OI, true, Ivars);
5618 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5619 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5620 if (Field->isBitField())
5621 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5623 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5624 false, false, false, false, false,
5625 EncodePointerToObjCTypedef,
5632 case Type::ObjCObjectPointer: {
5633 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5634 if (OPT->isObjCIdType()) {
5639 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5640 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5641 // Since this is a binary compatibility issue, need to consult with runtime
5642 // folks. Fortunately, this is a *very* obsure construct.
5647 if (OPT->isObjCQualifiedIdType()) {
5648 getObjCEncodingForTypeImpl(getObjCIdType(), S,
5649 ExpandPointedToStructures,
5650 ExpandStructures, FD);
5651 if (FD || EncodingProperty || EncodeClassNames) {
5652 // Note that we do extended encoding of protocol qualifer list
5653 // Only when doing ivar or property encoding.
5655 for (const auto *I : OPT->quals()) {
5657 S += I->getNameAsString();
5665 QualType PointeeTy = OPT->getPointeeType();
5666 if (!EncodingProperty &&
5667 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5668 !EncodePointerToObjCTypedef) {
5669 // Another historical/compatibility reason.
5670 // We encode the underlying type which comes out as
5673 if (FD && OPT->getInterfaceDecl()) {
5674 // Prevent recursive encoding of fields in some rare cases.
5675 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5676 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5677 DeepCollectObjCIvars(OI, true, Ivars);
5678 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5679 if (cast<FieldDecl>(Ivars[i]) == FD) {
5681 S += OI->getIdentifier()->getName();
5687 getObjCEncodingForTypeImpl(PointeeTy, S,
5688 false, ExpandPointedToStructures,
5690 false, false, false, false, false,
5691 /*EncodePointerToObjCTypedef*/true);
5696 if (OPT->getInterfaceDecl() &&
5697 (FD || EncodingProperty || EncodeClassNames)) {
5699 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
5700 for (const auto *I : OPT->quals()) {
5702 S += I->getNameAsString();
5710 // gcc just blithely ignores member pointers.
5711 // FIXME: we shoul do better than that. 'M' is available.
5712 case Type::MemberPointer:
5713 // This matches gcc's encoding, even though technically it is insufficient.
5714 //FIXME. We should do a better job than gcc.
5716 case Type::ExtVector:
5717 // Until we have a coherent encoding of these three types, issue warning.
5723 // We could see an undeduced auto type here during error recovery.
5729 #define ABSTRACT_TYPE(KIND, BASE)
5730 #define TYPE(KIND, BASE)
5731 #define DEPENDENT_TYPE(KIND, BASE) \
5733 #define NON_CANONICAL_TYPE(KIND, BASE) \
5735 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5737 #include "clang/AST/TypeNodes.def"
5738 llvm_unreachable("@encode for dependent type!");
5740 llvm_unreachable("bad type kind!");
5743 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5745 const FieldDecl *FD,
5747 QualType *NotEncodedT) const {
5748 assert(RDecl && "Expected non-null RecordDecl");
5749 assert(!RDecl->isUnion() && "Should not be called for unions");
5750 if (!RDecl->getDefinition())
5753 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5754 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5755 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5758 for (const auto &BI : CXXRec->bases()) {
5759 if (!BI.isVirtual()) {
5760 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5761 if (base->isEmpty())
5763 uint64_t offs = toBits(layout.getBaseClassOffset(base));
5764 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5765 std::make_pair(offs, base));
5771 for (auto *Field : RDecl->fields()) {
5772 uint64_t offs = layout.getFieldOffset(i);
5773 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5774 std::make_pair(offs, Field));
5778 if (CXXRec && includeVBases) {
5779 for (const auto &BI : CXXRec->vbases()) {
5780 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5781 if (base->isEmpty())
5783 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
5784 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5785 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5786 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5787 std::make_pair(offs, base));
5793 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5795 size = layout.getSize();
5799 uint64_t CurOffs = 0;
5801 std::multimap<uint64_t, NamedDecl *>::iterator
5802 CurLayObj = FieldOrBaseOffsets.begin();
5804 if (CXXRec && CXXRec->isDynamicClass() &&
5805 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
5808 std::string recname = CXXRec->getNameAsString();
5809 if (recname.empty()) recname = "?";
5815 CurOffs += getTypeSize(VoidPtrTy);
5819 if (!RDecl->hasFlexibleArrayMember()) {
5820 // Mark the end of the structure.
5821 uint64_t offs = toBits(size);
5822 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5823 std::make_pair(offs, nullptr));
5826 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5828 assert(CurOffs <= CurLayObj->first);
5829 if (CurOffs < CurLayObj->first) {
5830 uint64_t padding = CurLayObj->first - CurOffs;
5831 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5832 // packing/alignment of members is different that normal, in which case
5833 // the encoding will be out-of-sync with the real layout.
5834 // If the runtime switches to just consider the size of types without
5835 // taking into account alignment, we could make padding explicit in the
5836 // encoding (e.g. using arrays of chars). The encoding strings would be
5837 // longer then though.
5842 NamedDecl *dcl = CurLayObj->second;
5844 break; // reached end of structure.
5846 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5847 // We expand the bases without their virtual bases since those are going
5848 // in the initial structure. Note that this differs from gcc which
5849 // expands virtual bases each time one is encountered in the hierarchy,
5850 // making the encoding type bigger than it really is.
5851 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5853 assert(!base->isEmpty());
5855 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
5858 FieldDecl *field = cast<FieldDecl>(dcl);
5861 S += field->getNameAsString();
5865 if (field->isBitField()) {
5866 EncodeBitField(this, S, field->getType(), field);
5868 CurOffs += field->getBitWidthValue(*this);
5871 QualType qt = field->getType();
5872 getLegacyIntegralTypeEncoding(qt);
5873 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5874 /*OutermostType*/false,
5875 /*EncodingProperty*/false,
5876 /*StructField*/true,
5877 false, false, false, NotEncodedT);
5879 CurOffs += getTypeSize(field->getType());
5886 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
5887 std::string& S) const {
5888 if (QT & Decl::OBJC_TQ_In)
5890 if (QT & Decl::OBJC_TQ_Inout)
5892 if (QT & Decl::OBJC_TQ_Out)
5894 if (QT & Decl::OBJC_TQ_Bycopy)
5896 if (QT & Decl::OBJC_TQ_Byref)
5898 if (QT & Decl::OBJC_TQ_Oneway)
5902 TypedefDecl *ASTContext::getObjCIdDecl() const {
5904 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0);
5905 T = getObjCObjectPointerType(T);
5906 ObjCIdDecl = buildImplicitTypedef(T, "id");
5911 TypedefDecl *ASTContext::getObjCSelDecl() const {
5913 QualType T = getPointerType(ObjCBuiltinSelTy);
5914 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
5919 TypedefDecl *ASTContext::getObjCClassDecl() const {
5920 if (!ObjCClassDecl) {
5921 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0);
5922 T = getObjCObjectPointerType(T);
5923 ObjCClassDecl = buildImplicitTypedef(T, "Class");
5925 return ObjCClassDecl;
5928 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5929 if (!ObjCProtocolClassDecl) {
5930 ObjCProtocolClassDecl
5931 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5933 &Idents.get("Protocol"),
5934 /*PrevDecl=*/nullptr,
5935 SourceLocation(), true);
5938 return ObjCProtocolClassDecl;
5941 //===----------------------------------------------------------------------===//
5942 // __builtin_va_list Construction Functions
5943 //===----------------------------------------------------------------------===//
5945 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5946 // typedef char* __builtin_va_list;
5947 QualType T = Context->getPointerType(Context->CharTy);
5948 return Context->buildImplicitTypedef(T, "__builtin_va_list");
5951 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5952 // typedef void* __builtin_va_list;
5953 QualType T = Context->getPointerType(Context->VoidTy);
5954 return Context->buildImplicitTypedef(T, "__builtin_va_list");
5957 static TypedefDecl *
5958 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5960 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
5961 if (Context->getLangOpts().CPlusPlus) {
5962 // namespace std { struct __va_list {
5964 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5965 Context->getTranslationUnitDecl(),
5966 /*Inline*/ false, SourceLocation(),
5967 SourceLocation(), &Context->Idents.get("std"),
5968 /*PrevDecl*/ nullptr);
5970 VaListTagDecl->setDeclContext(NS);
5973 VaListTagDecl->startDefinition();
5975 const size_t NumFields = 5;
5976 QualType FieldTypes[NumFields];
5977 const char *FieldNames[NumFields];
5980 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5981 FieldNames[0] = "__stack";
5984 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5985 FieldNames[1] = "__gr_top";
5988 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5989 FieldNames[2] = "__vr_top";
5992 FieldTypes[3] = Context->IntTy;
5993 FieldNames[3] = "__gr_offs";
5996 FieldTypes[4] = Context->IntTy;
5997 FieldNames[4] = "__vr_offs";
6000 for (unsigned i = 0; i < NumFields; ++i) {
6001 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6005 &Context->Idents.get(FieldNames[i]),
6006 FieldTypes[i], /*TInfo=*/nullptr,
6007 /*BitWidth=*/nullptr,
6010 Field->setAccess(AS_public);
6011 VaListTagDecl->addDecl(Field);
6013 VaListTagDecl->completeDefinition();
6014 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6015 Context->VaListTagTy = VaListTagType;
6017 // } __builtin_va_list;
6018 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
6021 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6022 // typedef struct __va_list_tag {
6023 RecordDecl *VaListTagDecl;
6025 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6026 VaListTagDecl->startDefinition();
6028 const size_t NumFields = 5;
6029 QualType FieldTypes[NumFields];
6030 const char *FieldNames[NumFields];
6032 // unsigned char gpr;
6033 FieldTypes[0] = Context->UnsignedCharTy;
6034 FieldNames[0] = "gpr";
6036 // unsigned char fpr;
6037 FieldTypes[1] = Context->UnsignedCharTy;
6038 FieldNames[1] = "fpr";
6040 // unsigned short reserved;
6041 FieldTypes[2] = Context->UnsignedShortTy;
6042 FieldNames[2] = "reserved";
6044 // void* overflow_arg_area;
6045 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6046 FieldNames[3] = "overflow_arg_area";
6048 // void* reg_save_area;
6049 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6050 FieldNames[4] = "reg_save_area";
6053 for (unsigned i = 0; i < NumFields; ++i) {
6054 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6057 &Context->Idents.get(FieldNames[i]),
6058 FieldTypes[i], /*TInfo=*/nullptr,
6059 /*BitWidth=*/nullptr,
6062 Field->setAccess(AS_public);
6063 VaListTagDecl->addDecl(Field);
6065 VaListTagDecl->completeDefinition();
6066 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6067 Context->VaListTagTy = VaListTagType;
6070 TypedefDecl *VaListTagTypedefDecl =
6071 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6073 QualType VaListTagTypedefType =
6074 Context->getTypedefType(VaListTagTypedefDecl);
6076 // typedef __va_list_tag __builtin_va_list[1];
6077 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6078 QualType VaListTagArrayType
6079 = Context->getConstantArrayType(VaListTagTypedefType,
6080 Size, ArrayType::Normal, 0);
6081 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6084 static TypedefDecl *
6085 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6086 // typedef struct __va_list_tag {
6087 RecordDecl *VaListTagDecl;
6088 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6089 VaListTagDecl->startDefinition();
6091 const size_t NumFields = 4;
6092 QualType FieldTypes[NumFields];
6093 const char *FieldNames[NumFields];
6095 // unsigned gp_offset;
6096 FieldTypes[0] = Context->UnsignedIntTy;
6097 FieldNames[0] = "gp_offset";
6099 // unsigned fp_offset;
6100 FieldTypes[1] = Context->UnsignedIntTy;
6101 FieldNames[1] = "fp_offset";
6103 // void* overflow_arg_area;
6104 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6105 FieldNames[2] = "overflow_arg_area";
6107 // void* reg_save_area;
6108 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6109 FieldNames[3] = "reg_save_area";
6112 for (unsigned i = 0; i < NumFields; ++i) {
6113 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6117 &Context->Idents.get(FieldNames[i]),
6118 FieldTypes[i], /*TInfo=*/nullptr,
6119 /*BitWidth=*/nullptr,
6122 Field->setAccess(AS_public);
6123 VaListTagDecl->addDecl(Field);
6125 VaListTagDecl->completeDefinition();
6126 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6127 Context->VaListTagTy = VaListTagType;
6130 TypedefDecl *VaListTagTypedefDecl =
6131 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6133 QualType VaListTagTypedefType =
6134 Context->getTypedefType(VaListTagTypedefDecl);
6136 // typedef __va_list_tag __builtin_va_list[1];
6137 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6138 QualType VaListTagArrayType
6139 = Context->getConstantArrayType(VaListTagTypedefType,
6140 Size, ArrayType::Normal,0);
6141 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6144 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6145 // typedef int __builtin_va_list[4];
6146 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6147 QualType IntArrayType
6148 = Context->getConstantArrayType(Context->IntTy,
6149 Size, ArrayType::Normal, 0);
6150 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6153 static TypedefDecl *
6154 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6156 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6157 if (Context->getLangOpts().CPlusPlus) {
6158 // namespace std { struct __va_list {
6160 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6161 Context->getTranslationUnitDecl(),
6162 /*Inline*/false, SourceLocation(),
6163 SourceLocation(), &Context->Idents.get("std"),
6164 /*PrevDecl*/ nullptr);
6166 VaListDecl->setDeclContext(NS);
6169 VaListDecl->startDefinition();
6172 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6176 &Context->Idents.get("__ap"),
6177 Context->getPointerType(Context->VoidTy),
6179 /*BitWidth=*/nullptr,
6182 Field->setAccess(AS_public);
6183 VaListDecl->addDecl(Field);
6186 VaListDecl->completeDefinition();
6188 // typedef struct __va_list __builtin_va_list;
6189 QualType T = Context->getRecordType(VaListDecl);
6190 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6193 static TypedefDecl *
6194 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6195 // typedef struct __va_list_tag {
6196 RecordDecl *VaListTagDecl;
6197 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6198 VaListTagDecl->startDefinition();
6200 const size_t NumFields = 4;
6201 QualType FieldTypes[NumFields];
6202 const char *FieldNames[NumFields];
6205 FieldTypes[0] = Context->LongTy;
6206 FieldNames[0] = "__gpr";
6209 FieldTypes[1] = Context->LongTy;
6210 FieldNames[1] = "__fpr";
6212 // void *__overflow_arg_area;
6213 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6214 FieldNames[2] = "__overflow_arg_area";
6216 // void *__reg_save_area;
6217 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6218 FieldNames[3] = "__reg_save_area";
6221 for (unsigned i = 0; i < NumFields; ++i) {
6222 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6226 &Context->Idents.get(FieldNames[i]),
6227 FieldTypes[i], /*TInfo=*/nullptr,
6228 /*BitWidth=*/nullptr,
6231 Field->setAccess(AS_public);
6232 VaListTagDecl->addDecl(Field);
6234 VaListTagDecl->completeDefinition();
6235 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6236 Context->VaListTagTy = VaListTagType;
6239 TypedefDecl *VaListTagTypedefDecl =
6240 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6241 QualType VaListTagTypedefType =
6242 Context->getTypedefType(VaListTagTypedefDecl);
6244 // typedef __va_list_tag __builtin_va_list[1];
6245 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6246 QualType VaListTagArrayType
6247 = Context->getConstantArrayType(VaListTagTypedefType,
6248 Size, ArrayType::Normal,0);
6250 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6253 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6254 TargetInfo::BuiltinVaListKind Kind) {
6256 case TargetInfo::CharPtrBuiltinVaList:
6257 return CreateCharPtrBuiltinVaListDecl(Context);
6258 case TargetInfo::VoidPtrBuiltinVaList:
6259 return CreateVoidPtrBuiltinVaListDecl(Context);
6260 case TargetInfo::AArch64ABIBuiltinVaList:
6261 return CreateAArch64ABIBuiltinVaListDecl(Context);
6262 case TargetInfo::PowerABIBuiltinVaList:
6263 return CreatePowerABIBuiltinVaListDecl(Context);
6264 case TargetInfo::X86_64ABIBuiltinVaList:
6265 return CreateX86_64ABIBuiltinVaListDecl(Context);
6266 case TargetInfo::PNaClABIBuiltinVaList:
6267 return CreatePNaClABIBuiltinVaListDecl(Context);
6268 case TargetInfo::AAPCSABIBuiltinVaList:
6269 return CreateAAPCSABIBuiltinVaListDecl(Context);
6270 case TargetInfo::SystemZBuiltinVaList:
6271 return CreateSystemZBuiltinVaListDecl(Context);
6274 llvm_unreachable("Unhandled __builtin_va_list type kind");
6277 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6278 if (!BuiltinVaListDecl) {
6279 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6280 assert(BuiltinVaListDecl->isImplicit());
6283 return BuiltinVaListDecl;
6286 QualType ASTContext::getVaListTagType() const {
6287 // Force the creation of VaListTagTy by building the __builtin_va_list
6289 if (VaListTagTy.isNull())
6290 (void) getBuiltinVaListDecl();
6295 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6296 assert(ObjCConstantStringType.isNull() &&
6297 "'NSConstantString' type already set!");
6299 ObjCConstantStringType = getObjCInterfaceType(Decl);
6302 /// \brief Retrieve the template name that corresponds to a non-empty
6305 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6306 UnresolvedSetIterator End) const {
6307 unsigned size = End - Begin;
6308 assert(size > 1 && "set is not overloaded!");
6310 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6311 size * sizeof(FunctionTemplateDecl*));
6312 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6314 NamedDecl **Storage = OT->getStorage();
6315 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6317 assert(isa<FunctionTemplateDecl>(D) ||
6318 (isa<UsingShadowDecl>(D) &&
6319 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6323 return TemplateName(OT);
6326 /// \brief Retrieve the template name that represents a qualified
6327 /// template name such as \c std::vector.
6329 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6330 bool TemplateKeyword,
6331 TemplateDecl *Template) const {
6332 assert(NNS && "Missing nested-name-specifier in qualified template name");
6334 // FIXME: Canonicalization?
6335 llvm::FoldingSetNodeID ID;
6336 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6338 void *InsertPos = nullptr;
6339 QualifiedTemplateName *QTN =
6340 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6342 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6343 QualifiedTemplateName(NNS, TemplateKeyword, Template);
6344 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6347 return TemplateName(QTN);
6350 /// \brief Retrieve the template name that represents a dependent
6351 /// template name such as \c MetaFun::template apply.
6353 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6354 const IdentifierInfo *Name) const {
6355 assert((!NNS || NNS->isDependent()) &&
6356 "Nested name specifier must be dependent");
6358 llvm::FoldingSetNodeID ID;
6359 DependentTemplateName::Profile(ID, NNS, Name);
6361 void *InsertPos = nullptr;
6362 DependentTemplateName *QTN =
6363 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6366 return TemplateName(QTN);
6368 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6369 if (CanonNNS == NNS) {
6370 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6371 DependentTemplateName(NNS, Name);
6373 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6374 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6375 DependentTemplateName(NNS, Name, Canon);
6376 DependentTemplateName *CheckQTN =
6377 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6378 assert(!CheckQTN && "Dependent type name canonicalization broken");
6382 DependentTemplateNames.InsertNode(QTN, InsertPos);
6383 return TemplateName(QTN);
6386 /// \brief Retrieve the template name that represents a dependent
6387 /// template name such as \c MetaFun::template operator+.
6389 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6390 OverloadedOperatorKind Operator) const {
6391 assert((!NNS || NNS->isDependent()) &&
6392 "Nested name specifier must be dependent");
6394 llvm::FoldingSetNodeID ID;
6395 DependentTemplateName::Profile(ID, NNS, Operator);
6397 void *InsertPos = nullptr;
6398 DependentTemplateName *QTN
6399 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6402 return TemplateName(QTN);
6404 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6405 if (CanonNNS == NNS) {
6406 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6407 DependentTemplateName(NNS, Operator);
6409 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6410 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6411 DependentTemplateName(NNS, Operator, Canon);
6413 DependentTemplateName *CheckQTN
6414 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6415 assert(!CheckQTN && "Dependent template name canonicalization broken");
6419 DependentTemplateNames.InsertNode(QTN, InsertPos);
6420 return TemplateName(QTN);
6424 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6425 TemplateName replacement) const {
6426 llvm::FoldingSetNodeID ID;
6427 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6429 void *insertPos = nullptr;
6430 SubstTemplateTemplateParmStorage *subst
6431 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6434 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6435 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6438 return TemplateName(subst);
6442 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6443 const TemplateArgument &ArgPack) const {
6444 ASTContext &Self = const_cast<ASTContext &>(*this);
6445 llvm::FoldingSetNodeID ID;
6446 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6448 void *InsertPos = nullptr;
6449 SubstTemplateTemplateParmPackStorage *Subst
6450 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6453 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6454 ArgPack.pack_size(),
6455 ArgPack.pack_begin());
6456 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6459 return TemplateName(Subst);
6462 /// getFromTargetType - Given one of the integer types provided by
6463 /// TargetInfo, produce the corresponding type. The unsigned @p Type
6464 /// is actually a value of type @c TargetInfo::IntType.
6465 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6467 case TargetInfo::NoInt: return CanQualType();
6468 case TargetInfo::SignedChar: return SignedCharTy;
6469 case TargetInfo::UnsignedChar: return UnsignedCharTy;
6470 case TargetInfo::SignedShort: return ShortTy;
6471 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6472 case TargetInfo::SignedInt: return IntTy;
6473 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6474 case TargetInfo::SignedLong: return LongTy;
6475 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6476 case TargetInfo::SignedLongLong: return LongLongTy;
6477 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6480 llvm_unreachable("Unhandled TargetInfo::IntType value");
6483 //===----------------------------------------------------------------------===//
6485 //===----------------------------------------------------------------------===//
6487 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6488 /// garbage collection attribute.
6490 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6491 if (getLangOpts().getGC() == LangOptions::NonGC)
6492 return Qualifiers::GCNone;
6494 assert(getLangOpts().ObjC1);
6495 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6497 // Default behaviour under objective-C's gc is for ObjC pointers
6498 // (or pointers to them) be treated as though they were declared
6500 if (GCAttrs == Qualifiers::GCNone) {
6501 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6502 return Qualifiers::Strong;
6503 else if (Ty->isPointerType())
6504 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6506 // It's not valid to set GC attributes on anything that isn't a
6509 QualType CT = Ty->getCanonicalTypeInternal();
6510 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6511 CT = AT->getElementType();
6512 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6518 //===----------------------------------------------------------------------===//
6519 // Type Compatibility Testing
6520 //===----------------------------------------------------------------------===//
6522 /// areCompatVectorTypes - Return true if the two specified vector types are
6524 static bool areCompatVectorTypes(const VectorType *LHS,
6525 const VectorType *RHS) {
6526 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6527 return LHS->getElementType() == RHS->getElementType() &&
6528 LHS->getNumElements() == RHS->getNumElements();
6531 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6532 QualType SecondVec) {
6533 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6534 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6536 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6539 // Treat Neon vector types and most AltiVec vector types as if they are the
6540 // equivalent GCC vector types.
6541 const VectorType *First = FirstVec->getAs<VectorType>();
6542 const VectorType *Second = SecondVec->getAs<VectorType>();
6543 if (First->getNumElements() == Second->getNumElements() &&
6544 hasSameType(First->getElementType(), Second->getElementType()) &&
6545 First->getVectorKind() != VectorType::AltiVecPixel &&
6546 First->getVectorKind() != VectorType::AltiVecBool &&
6547 Second->getVectorKind() != VectorType::AltiVecPixel &&
6548 Second->getVectorKind() != VectorType::AltiVecBool)
6554 //===----------------------------------------------------------------------===//
6555 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6556 //===----------------------------------------------------------------------===//
6558 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6559 /// inheritance hierarchy of 'rProto'.
6561 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6562 ObjCProtocolDecl *rProto) const {
6563 if (declaresSameEntity(lProto, rProto))
6565 for (auto *PI : rProto->protocols())
6566 if (ProtocolCompatibleWithProtocol(lProto, PI))
6571 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6572 /// Class<pr1, ...>.
6573 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6575 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6576 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6577 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6579 for (auto *lhsProto : lhsQID->quals()) {
6581 for (auto *rhsProto : rhsOPT->quals()) {
6582 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6593 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6594 /// ObjCQualifiedIDType.
6595 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6597 // Allow id<P..> and an 'id' or void* type in all cases.
6598 if (lhs->isVoidPointerType() ||
6599 lhs->isObjCIdType() || lhs->isObjCClassType())
6601 else if (rhs->isVoidPointerType() ||
6602 rhs->isObjCIdType() || rhs->isObjCClassType())
6605 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6606 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6608 if (!rhsOPT) return false;
6610 if (rhsOPT->qual_empty()) {
6611 // If the RHS is a unqualified interface pointer "NSString*",
6612 // make sure we check the class hierarchy.
6613 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6614 for (auto *I : lhsQID->quals()) {
6615 // when comparing an id<P> on lhs with a static type on rhs,
6616 // see if static class implements all of id's protocols, directly or
6617 // through its super class and categories.
6618 if (!rhsID->ClassImplementsProtocol(I, true))
6622 // If there are no qualifiers and no interface, we have an 'id'.
6625 // Both the right and left sides have qualifiers.
6626 for (auto *lhsProto : lhsQID->quals()) {
6629 // when comparing an id<P> on lhs with a static type on rhs,
6630 // see if static class implements all of id's protocols, directly or
6631 // through its super class and categories.
6632 for (auto *rhsProto : rhsOPT->quals()) {
6633 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6634 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6639 // If the RHS is a qualified interface pointer "NSString<P>*",
6640 // make sure we check the class hierarchy.
6641 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6642 for (auto *I : lhsQID->quals()) {
6643 // when comparing an id<P> on lhs with a static type on rhs,
6644 // see if static class implements all of id's protocols, directly or
6645 // through its super class and categories.
6646 if (rhsID->ClassImplementsProtocol(I, true)) {
6659 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6660 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6662 if (const ObjCObjectPointerType *lhsOPT =
6663 lhs->getAsObjCInterfacePointerType()) {
6664 // If both the right and left sides have qualifiers.
6665 for (auto *lhsProto : lhsOPT->quals()) {
6668 // when comparing an id<P> on rhs with a static type on lhs,
6669 // see if static class implements all of id's protocols, directly or
6670 // through its super class and categories.
6671 // First, lhs protocols in the qualifier list must be found, direct
6672 // or indirect in rhs's qualifier list or it is a mismatch.
6673 for (auto *rhsProto : rhsQID->quals()) {
6674 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6675 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6684 // Static class's protocols, or its super class or category protocols
6685 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6686 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6687 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6688 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6689 // This is rather dubious but matches gcc's behavior. If lhs has
6690 // no type qualifier and its class has no static protocol(s)
6691 // assume that it is mismatch.
6692 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6694 for (auto *lhsProto : LHSInheritedProtocols) {
6696 for (auto *rhsProto : rhsQID->quals()) {
6697 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6698 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6712 /// canAssignObjCInterfaces - Return true if the two interface types are
6713 /// compatible for assignment from RHS to LHS. This handles validation of any
6714 /// protocol qualifiers on the LHS or RHS.
6716 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6717 const ObjCObjectPointerType *RHSOPT) {
6718 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6719 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6721 // If either type represents the built-in 'id' or 'Class' types, return true.
6722 if (LHS->isObjCUnqualifiedIdOrClass() ||
6723 RHS->isObjCUnqualifiedIdOrClass())
6726 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
6727 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6731 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6732 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6733 QualType(RHSOPT,0));
6735 // If we have 2 user-defined types, fall into that path.
6736 if (LHS->getInterface() && RHS->getInterface())
6737 return canAssignObjCInterfaces(LHS, RHS);
6742 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6743 /// for providing type-safety for objective-c pointers used to pass/return
6744 /// arguments in block literals. When passed as arguments, passing 'A*' where
6745 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6746 /// not OK. For the return type, the opposite is not OK.
6747 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6748 const ObjCObjectPointerType *LHSOPT,
6749 const ObjCObjectPointerType *RHSOPT,
6750 bool BlockReturnType) {
6751 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
6754 if (LHSOPT->isObjCBuiltinType()) {
6755 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6758 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
6759 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6763 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6764 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6765 if (LHS && RHS) { // We have 2 user-defined types.
6767 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
6768 return BlockReturnType;
6769 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
6770 return !BlockReturnType;
6778 /// getIntersectionOfProtocols - This routine finds the intersection of set
6779 /// of protocols inherited from two distinct objective-c pointer objects.
6780 /// It is used to build composite qualifier list of the composite type of
6781 /// the conditional expression involving two objective-c pointer objects.
6783 void getIntersectionOfProtocols(ASTContext &Context,
6784 const ObjCObjectPointerType *LHSOPT,
6785 const ObjCObjectPointerType *RHSOPT,
6786 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
6788 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6789 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6790 assert(LHS->getInterface() && "LHS must have an interface base");
6791 assert(RHS->getInterface() && "RHS must have an interface base");
6793 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6794 unsigned LHSNumProtocols = LHS->getNumProtocols();
6795 if (LHSNumProtocols > 0)
6796 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6798 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6799 Context.CollectInheritedProtocols(LHS->getInterface(),
6800 LHSInheritedProtocols);
6801 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6802 LHSInheritedProtocols.end());
6805 unsigned RHSNumProtocols = RHS->getNumProtocols();
6806 if (RHSNumProtocols > 0) {
6807 ObjCProtocolDecl **RHSProtocols =
6808 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
6809 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6810 if (InheritedProtocolSet.count(RHSProtocols[i]))
6811 IntersectionOfProtocols.push_back(RHSProtocols[i]);
6813 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
6814 Context.CollectInheritedProtocols(RHS->getInterface(),
6815 RHSInheritedProtocols);
6816 for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols)
6817 if (InheritedProtocolSet.count(ProtDecl))
6818 IntersectionOfProtocols.push_back(ProtDecl);
6822 /// areCommonBaseCompatible - Returns common base class of the two classes if
6823 /// one found. Note that this is O'2 algorithm. But it will be called as the
6824 /// last type comparison in a ?-exp of ObjC pointer types before a
6825 /// warning is issued. So, its invokation is extremely rare.
6826 QualType ASTContext::areCommonBaseCompatible(
6827 const ObjCObjectPointerType *Lptr,
6828 const ObjCObjectPointerType *Rptr) {
6829 const ObjCObjectType *LHS = Lptr->getObjectType();
6830 const ObjCObjectType *RHS = Rptr->getObjectType();
6831 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6832 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
6833 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
6837 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
6838 if (canAssignObjCInterfaces(LHS, RHS)) {
6839 SmallVector<ObjCProtocolDecl *, 8> Protocols;
6840 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6842 QualType Result = QualType(LHS, 0);
6843 if (!Protocols.empty())
6844 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6845 Result = getObjCObjectPointerType(Result);
6848 } while ((LDecl = LDecl->getSuperClass()));
6853 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6854 const ObjCObjectType *RHS) {
6855 assert(LHS->getInterface() && "LHS is not an interface type");
6856 assert(RHS->getInterface() && "RHS is not an interface type");
6858 // Verify that the base decls are compatible: the RHS must be a subclass of
6860 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
6863 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6864 // protocol qualified at all, then we are good.
6865 if (LHS->getNumProtocols() == 0)
6868 // Okay, we know the LHS has protocol qualifiers. But RHS may or may not.
6869 // More detailed analysis is required.
6870 // OK, if LHS is same or a superclass of RHS *and*
6871 // this LHS, or as RHS's super class is assignment compatible with LHS.
6873 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6875 // OK if conversion of LHS to SuperClass results in narrowing of types
6876 // ; i.e., SuperClass may implement at least one of the protocols
6877 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6878 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6879 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6880 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6881 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
6883 for (auto *RHSPI : RHS->quals())
6884 SuperClassInheritedProtocols.insert(RHSPI->getCanonicalDecl());
6885 // If there is no protocols associated with RHS, it is not a match.
6886 if (SuperClassInheritedProtocols.empty())
6889 for (const auto *LHSProto : LHS->quals()) {
6890 bool SuperImplementsProtocol = false;
6891 for (auto *SuperClassProto : SuperClassInheritedProtocols)
6892 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6893 SuperImplementsProtocol = true;
6896 if (!SuperImplementsProtocol)
6904 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6905 // get the "pointed to" types
6906 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6907 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
6909 if (!LHSOPT || !RHSOPT)
6912 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6913 canAssignObjCInterfaces(RHSOPT, LHSOPT);
6916 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6917 return canAssignObjCInterfaces(
6918 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6919 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6922 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
6923 /// both shall have the identically qualified version of a compatible type.
6924 /// C99 6.2.7p1: Two types have compatible types if their types are the
6925 /// same. See 6.7.[2,3,5] for additional rules.
6926 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6927 bool CompareUnqualified) {
6928 if (getLangOpts().CPlusPlus)
6929 return hasSameType(LHS, RHS);
6931 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
6934 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
6935 return typesAreCompatible(LHS, RHS);
6938 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6939 return !mergeTypes(LHS, RHS, true).isNull();
6942 /// mergeTransparentUnionType - if T is a transparent union type and a member
6943 /// of T is compatible with SubType, return the merged type, else return
6945 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6946 bool OfBlockPointer,
6948 if (const RecordType *UT = T->getAsUnionType()) {
6949 RecordDecl *UD = UT->getDecl();
6950 if (UD->hasAttr<TransparentUnionAttr>()) {
6951 for (const auto *I : UD->fields()) {
6952 QualType ET = I->getType().getUnqualifiedType();
6953 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6963 /// mergeFunctionParameterTypes - merge two types which appear as function
6965 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6966 bool OfBlockPointer,
6968 // GNU extension: two types are compatible if they appear as a function
6969 // argument, one of the types is a transparent union type and the other
6970 // type is compatible with a union member
6971 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6973 if (!lmerge.isNull())
6976 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6978 if (!rmerge.isNull())
6981 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6984 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
6985 bool OfBlockPointer,
6987 const FunctionType *lbase = lhs->getAs<FunctionType>();
6988 const FunctionType *rbase = rhs->getAs<FunctionType>();
6989 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6990 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
6991 bool allLTypes = true;
6992 bool allRTypes = true;
6994 // Check return type
6996 if (OfBlockPointer) {
6997 QualType RHS = rbase->getReturnType();
6998 QualType LHS = lbase->getReturnType();
6999 bool UnqualifiedResult = Unqualified;
7000 if (!UnqualifiedResult)
7001 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
7002 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
7005 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
7007 if (retType.isNull()) return QualType();
7010 retType = retType.getUnqualifiedType();
7012 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7013 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
7015 LRetType = LRetType.getUnqualifiedType();
7016 RRetType = RRetType.getUnqualifiedType();
7019 if (getCanonicalType(retType) != LRetType)
7021 if (getCanonicalType(retType) != RRetType)
7024 // FIXME: double check this
7025 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7026 // rbase->getRegParmAttr() != 0 &&
7027 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
7028 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7029 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
7031 // Compatible functions must have compatible calling conventions
7032 if (lbaseInfo.getCC() != rbaseInfo.getCC())
7035 // Regparm is part of the calling convention.
7036 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7038 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7041 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7044 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7045 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
7047 if (lbaseInfo.getNoReturn() != NoReturn)
7049 if (rbaseInfo.getNoReturn() != NoReturn)
7052 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
7054 if (lproto && rproto) { // two C99 style function prototypes
7055 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7056 "C++ shouldn't be here");
7057 // Compatible functions must have the same number of parameters
7058 if (lproto->getNumParams() != rproto->getNumParams())
7061 // Variadic and non-variadic functions aren't compatible
7062 if (lproto->isVariadic() != rproto->isVariadic())
7065 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7068 if (LangOpts.ObjCAutoRefCount &&
7069 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7072 // Check parameter type compatibility
7073 SmallVector<QualType, 10> types;
7074 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7075 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7076 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7077 QualType paramType = mergeFunctionParameterTypes(
7078 lParamType, rParamType, OfBlockPointer, Unqualified);
7079 if (paramType.isNull())
7083 paramType = paramType.getUnqualifiedType();
7085 types.push_back(paramType);
7087 lParamType = lParamType.getUnqualifiedType();
7088 rParamType = rParamType.getUnqualifiedType();
7091 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
7093 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
7097 if (allLTypes) return lhs;
7098 if (allRTypes) return rhs;
7100 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7101 EPI.ExtInfo = einfo;
7102 return getFunctionType(retType, types, EPI);
7105 if (lproto) allRTypes = false;
7106 if (rproto) allLTypes = false;
7108 const FunctionProtoType *proto = lproto ? lproto : rproto;
7110 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7111 if (proto->isVariadic()) return QualType();
7112 // Check that the types are compatible with the types that
7113 // would result from default argument promotions (C99 6.7.5.3p15).
7114 // The only types actually affected are promotable integer
7115 // types and floats, which would be passed as a different
7116 // type depending on whether the prototype is visible.
7117 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7118 QualType paramTy = proto->getParamType(i);
7120 // Look at the converted type of enum types, since that is the type used
7121 // to pass enum values.
7122 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7123 paramTy = Enum->getDecl()->getIntegerType();
7124 if (paramTy.isNull())
7128 if (paramTy->isPromotableIntegerType() ||
7129 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
7133 if (allLTypes) return lhs;
7134 if (allRTypes) return rhs;
7136 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7137 EPI.ExtInfo = einfo;
7138 return getFunctionType(retType, proto->getParamTypes(), EPI);
7141 if (allLTypes) return lhs;
7142 if (allRTypes) return rhs;
7143 return getFunctionNoProtoType(retType, einfo);
7146 /// Given that we have an enum type and a non-enum type, try to merge them.
7147 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7148 QualType other, bool isBlockReturnType) {
7149 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7150 // a signed integer type, or an unsigned integer type.
7151 // Compatibility is based on the underlying type, not the promotion
7153 QualType underlyingType = ET->getDecl()->getIntegerType();
7154 if (underlyingType.isNull()) return QualType();
7155 if (Context.hasSameType(underlyingType, other))
7158 // In block return types, we're more permissive and accept any
7159 // integral type of the same size.
7160 if (isBlockReturnType && other->isIntegerType() &&
7161 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7167 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
7168 bool OfBlockPointer,
7169 bool Unqualified, bool BlockReturnType) {
7170 // C++ [expr]: If an expression initially has the type "reference to T", the
7171 // type is adjusted to "T" prior to any further analysis, the expression
7172 // designates the object or function denoted by the reference, and the
7173 // expression is an lvalue unless the reference is an rvalue reference and
7174 // the expression is a function call (possibly inside parentheses).
7175 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7176 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
7179 LHS = LHS.getUnqualifiedType();
7180 RHS = RHS.getUnqualifiedType();
7183 QualType LHSCan = getCanonicalType(LHS),
7184 RHSCan = getCanonicalType(RHS);
7186 // If two types are identical, they are compatible.
7187 if (LHSCan == RHSCan)
7190 // If the qualifiers are different, the types aren't compatible... mostly.
7191 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7192 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7193 if (LQuals != RQuals) {
7194 // If any of these qualifiers are different, we have a type
7196 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7197 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7198 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
7201 // Exactly one GC qualifier difference is allowed: __strong is
7202 // okay if the other type has no GC qualifier but is an Objective
7203 // C object pointer (i.e. implicitly strong by default). We fix
7204 // this by pretending that the unqualified type was actually
7205 // qualified __strong.
7206 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7207 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7208 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7210 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7213 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7214 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7216 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7217 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7222 // Okay, qualifiers are equal.
7224 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7225 Type::TypeClass RHSClass = RHSCan->getTypeClass();
7227 // We want to consider the two function types to be the same for these
7228 // comparisons, just force one to the other.
7229 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7230 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
7232 // Same as above for arrays
7233 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7234 LHSClass = Type::ConstantArray;
7235 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7236 RHSClass = Type::ConstantArray;
7238 // ObjCInterfaces are just specialized ObjCObjects.
7239 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7240 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7242 // Canonicalize ExtVector -> Vector.
7243 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7244 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
7246 // If the canonical type classes don't match.
7247 if (LHSClass != RHSClass) {
7248 // Note that we only have special rules for turning block enum
7249 // returns into block int returns, not vice-versa.
7250 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
7251 return mergeEnumWithInteger(*this, ETy, RHS, false);
7253 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
7254 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
7256 // allow block pointer type to match an 'id' type.
7257 if (OfBlockPointer && !BlockReturnType) {
7258 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7260 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7267 // The canonical type classes match.
7269 #define TYPE(Class, Base)
7270 #define ABSTRACT_TYPE(Class, Base)
7271 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
7272 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7273 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
7274 #include "clang/AST/TypeNodes.def"
7275 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
7278 case Type::LValueReference:
7279 case Type::RValueReference:
7280 case Type::MemberPointer:
7281 llvm_unreachable("C++ should never be in mergeTypes");
7283 case Type::ObjCInterface:
7284 case Type::IncompleteArray:
7285 case Type::VariableArray:
7286 case Type::FunctionProto:
7287 case Type::ExtVector:
7288 llvm_unreachable("Types are eliminated above");
7292 // Merge two pointer types, while trying to preserve typedef info
7293 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7294 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
7296 LHSPointee = LHSPointee.getUnqualifiedType();
7297 RHSPointee = RHSPointee.getUnqualifiedType();
7299 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7301 if (ResultType.isNull()) return QualType();
7302 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7304 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7306 return getPointerType(ResultType);
7308 case Type::BlockPointer:
7310 // Merge two block pointer types, while trying to preserve typedef info
7311 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7312 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7314 LHSPointee = LHSPointee.getUnqualifiedType();
7315 RHSPointee = RHSPointee.getUnqualifiedType();
7317 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7319 if (ResultType.isNull()) return QualType();
7320 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7322 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7324 return getBlockPointerType(ResultType);
7328 // Merge two pointer types, while trying to preserve typedef info
7329 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7330 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7332 LHSValue = LHSValue.getUnqualifiedType();
7333 RHSValue = RHSValue.getUnqualifiedType();
7335 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7337 if (ResultType.isNull()) return QualType();
7338 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7340 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7342 return getAtomicType(ResultType);
7344 case Type::ConstantArray:
7346 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7347 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7348 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7351 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7352 QualType RHSElem = getAsArrayType(RHS)->getElementType();
7354 LHSElem = LHSElem.getUnqualifiedType();
7355 RHSElem = RHSElem.getUnqualifiedType();
7358 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7359 if (ResultType.isNull()) return QualType();
7360 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7362 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7364 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7365 ArrayType::ArraySizeModifier(), 0);
7366 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7367 ArrayType::ArraySizeModifier(), 0);
7368 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7369 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7370 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7372 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7375 // FIXME: This isn't correct! But tricky to implement because
7376 // the array's size has to be the size of LHS, but the type
7377 // has to be different.
7381 // FIXME: This isn't correct! But tricky to implement because
7382 // the array's size has to be the size of RHS, but the type
7383 // has to be different.
7386 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7387 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7388 return getIncompleteArrayType(ResultType,
7389 ArrayType::ArraySizeModifier(), 0);
7391 case Type::FunctionNoProto:
7392 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7397 // Only exactly equal builtin types are compatible, which is tested above.
7400 // Distinct complex types are incompatible.
7403 // FIXME: The merged type should be an ExtVector!
7404 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7405 RHSCan->getAs<VectorType>()))
7408 case Type::ObjCObject: {
7409 // Check if the types are assignment compatible.
7410 // FIXME: This should be type compatibility, e.g. whether
7411 // "LHS x; RHS x;" at global scope is legal.
7412 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7413 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7414 if (canAssignObjCInterfaces(LHSIface, RHSIface))
7419 case Type::ObjCObjectPointer: {
7420 if (OfBlockPointer) {
7421 if (canAssignObjCInterfacesInBlockPointer(
7422 LHS->getAs<ObjCObjectPointerType>(),
7423 RHS->getAs<ObjCObjectPointerType>(),
7428 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7429 RHS->getAs<ObjCObjectPointerType>()))
7436 llvm_unreachable("Invalid Type::Class!");
7439 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7440 const FunctionProtoType *FromFunctionType,
7441 const FunctionProtoType *ToFunctionType) {
7442 if (FromFunctionType->hasAnyConsumedParams() !=
7443 ToFunctionType->hasAnyConsumedParams())
7445 FunctionProtoType::ExtProtoInfo FromEPI =
7446 FromFunctionType->getExtProtoInfo();
7447 FunctionProtoType::ExtProtoInfo ToEPI =
7448 ToFunctionType->getExtProtoInfo();
7449 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
7450 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7451 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
7457 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7458 /// 'RHS' attributes and returns the merged version; including for function
7460 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7461 QualType LHSCan = getCanonicalType(LHS),
7462 RHSCan = getCanonicalType(RHS);
7463 // If two types are identical, they are compatible.
7464 if (LHSCan == RHSCan)
7466 if (RHSCan->isFunctionType()) {
7467 if (!LHSCan->isFunctionType())
7469 QualType OldReturnType =
7470 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
7471 QualType NewReturnType =
7472 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
7473 QualType ResReturnType =
7474 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7475 if (ResReturnType.isNull())
7477 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7478 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7479 // In either case, use OldReturnType to build the new function type.
7480 const FunctionType *F = LHS->getAs<FunctionType>();
7481 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7482 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7483 EPI.ExtInfo = getFunctionExtInfo(LHS);
7484 QualType ResultType =
7485 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
7492 // If the qualifiers are different, the types can still be merged.
7493 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7494 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7495 if (LQuals != RQuals) {
7496 // If any of these qualifiers are different, we have a type mismatch.
7497 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7498 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7501 // Exactly one GC qualifier difference is allowed: __strong is
7502 // okay if the other type has no GC qualifier but is an Objective
7503 // C object pointer (i.e. implicitly strong by default). We fix
7504 // this by pretending that the unqualified type was actually
7505 // qualified __strong.
7506 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7507 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7508 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7510 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7513 if (GC_L == Qualifiers::Strong)
7515 if (GC_R == Qualifiers::Strong)
7520 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7521 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7522 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7523 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7524 if (ResQT == LHSBaseQT)
7526 if (ResQT == RHSBaseQT)
7532 //===----------------------------------------------------------------------===//
7533 // Integer Predicates
7534 //===----------------------------------------------------------------------===//
7536 unsigned ASTContext::getIntWidth(QualType T) const {
7537 if (const EnumType *ET = T->getAs<EnumType>())
7538 T = ET->getDecl()->getIntegerType();
7539 if (T->isBooleanType())
7541 // For builtin types, just use the standard type sizing method
7542 return (unsigned)getTypeSize(T);
7545 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
7546 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
7548 // Turn <4 x signed int> -> <4 x unsigned int>
7549 if (const VectorType *VTy = T->getAs<VectorType>())
7550 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
7551 VTy->getNumElements(), VTy->getVectorKind());
7553 // For enums, we return the unsigned version of the base type.
7554 if (const EnumType *ETy = T->getAs<EnumType>())
7555 T = ETy->getDecl()->getIntegerType();
7557 const BuiltinType *BTy = T->getAs<BuiltinType>();
7558 assert(BTy && "Unexpected signed integer type");
7559 switch (BTy->getKind()) {
7560 case BuiltinType::Char_S:
7561 case BuiltinType::SChar:
7562 return UnsignedCharTy;
7563 case BuiltinType::Short:
7564 return UnsignedShortTy;
7565 case BuiltinType::Int:
7566 return UnsignedIntTy;
7567 case BuiltinType::Long:
7568 return UnsignedLongTy;
7569 case BuiltinType::LongLong:
7570 return UnsignedLongLongTy;
7571 case BuiltinType::Int128:
7572 return UnsignedInt128Ty;
7574 llvm_unreachable("Unexpected signed integer type");
7578 ASTMutationListener::~ASTMutationListener() { }
7580 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7581 QualType ReturnType) {}
7583 //===----------------------------------------------------------------------===//
7584 // Builtin Type Computation
7585 //===----------------------------------------------------------------------===//
7587 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
7588 /// pointer over the consumed characters. This returns the resultant type. If
7589 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7590 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7591 /// a vector of "i*".
7593 /// RequiresICE is filled in on return to indicate whether the value is required
7594 /// to be an Integer Constant Expression.
7595 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
7596 ASTContext::GetBuiltinTypeError &Error,
7598 bool AllowTypeModifiers) {
7601 bool Signed = false, Unsigned = false;
7602 RequiresICE = false;
7604 // Read the prefixed modifiers first.
7608 default: Done = true; --Str; break;
7613 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7614 assert(!Signed && "Can't use 'S' modifier multiple times!");
7618 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7619 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
7623 assert(HowLong <= 2 && "Can't have LLLL modifier");
7627 // This modifier represents int64 type.
7628 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7629 switch (Context.getTargetInfo().getInt64Type()) {
7631 llvm_unreachable("Unexpected integer type");
7632 case TargetInfo::SignedLong:
7635 case TargetInfo::SignedLongLong:
7644 // Read the base type.
7646 default: llvm_unreachable("Unknown builtin type letter!");
7648 assert(HowLong == 0 && !Signed && !Unsigned &&
7649 "Bad modifiers used with 'v'!");
7650 Type = Context.VoidTy;
7653 assert(HowLong == 0 && !Signed && !Unsigned &&
7654 "Bad modifiers used with 'h'!");
7655 Type = Context.HalfTy;
7658 assert(HowLong == 0 && !Signed && !Unsigned &&
7659 "Bad modifiers used with 'f'!");
7660 Type = Context.FloatTy;
7663 assert(HowLong < 2 && !Signed && !Unsigned &&
7664 "Bad modifiers used with 'd'!");
7666 Type = Context.LongDoubleTy;
7668 Type = Context.DoubleTy;
7671 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7673 Type = Context.UnsignedShortTy;
7675 Type = Context.ShortTy;
7679 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7680 else if (HowLong == 2)
7681 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7682 else if (HowLong == 1)
7683 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7685 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7688 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7690 Type = Context.SignedCharTy;
7692 Type = Context.UnsignedCharTy;
7694 Type = Context.CharTy;
7696 case 'b': // boolean
7697 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7698 Type = Context.BoolTy;
7700 case 'z': // size_t.
7701 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7702 Type = Context.getSizeType();
7705 Type = Context.getCFConstantStringType();
7708 Type = Context.getObjCIdType();
7711 Type = Context.getObjCSelType();
7714 Type = Context.getObjCSuperType();
7717 Type = Context.getBuiltinVaListType();
7718 assert(!Type.isNull() && "builtin va list type not initialized!");
7721 // This is a "reference" to a va_list; however, what exactly
7722 // this means depends on how va_list is defined. There are two
7723 // different kinds of va_list: ones passed by value, and ones
7724 // passed by reference. An example of a by-value va_list is
7725 // x86, where va_list is a char*. An example of by-ref va_list
7726 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7727 // we want this argument to be a char*&; for x86-64, we want
7728 // it to be a __va_list_tag*.
7729 Type = Context.getBuiltinVaListType();
7730 assert(!Type.isNull() && "builtin va list type not initialized!");
7731 if (Type->isArrayType())
7732 Type = Context.getArrayDecayedType(Type);
7734 Type = Context.getLValueReferenceType(Type);
7738 unsigned NumElements = strtoul(Str, &End, 10);
7739 assert(End != Str && "Missing vector size");
7742 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7743 RequiresICE, false);
7744 assert(!RequiresICE && "Can't require vector ICE");
7746 // TODO: No way to make AltiVec vectors in builtins yet.
7747 Type = Context.getVectorType(ElementType, NumElements,
7748 VectorType::GenericVector);
7754 unsigned NumElements = strtoul(Str, &End, 10);
7755 assert(End != Str && "Missing vector size");
7759 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7761 Type = Context.getExtVectorType(ElementType, NumElements);
7765 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7767 assert(!RequiresICE && "Can't require complex ICE");
7768 Type = Context.getComplexType(ElementType);
7772 Type = Context.getPointerDiffType();
7776 Type = Context.getFILEType();
7777 if (Type.isNull()) {
7778 Error = ASTContext::GE_Missing_stdio;
7784 Type = Context.getsigjmp_bufType();
7786 Type = Context.getjmp_bufType();
7788 if (Type.isNull()) {
7789 Error = ASTContext::GE_Missing_setjmp;
7794 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7795 Type = Context.getucontext_tType();
7797 if (Type.isNull()) {
7798 Error = ASTContext::GE_Missing_ucontext;
7803 Type = Context.getProcessIDType();
7807 // If there are modifiers and if we're allowed to parse them, go for it.
7808 Done = !AllowTypeModifiers;
7810 switch (char c = *Str++) {
7811 default: Done = true; --Str; break;
7814 // Both pointers and references can have their pointee types
7815 // qualified with an address space.
7817 unsigned AddrSpace = strtoul(Str, &End, 10);
7818 if (End != Str && AddrSpace != 0) {
7819 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7823 Type = Context.getPointerType(Type);
7825 Type = Context.getLValueReferenceType(Type);
7828 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7830 Type = Type.withConst();
7833 Type = Context.getVolatileType(Type);
7836 Type = Type.withRestrict();
7841 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
7842 "Integer constant 'I' type must be an integer");
7847 /// GetBuiltinType - Return the type for the specified builtin.
7848 QualType ASTContext::GetBuiltinType(unsigned Id,
7849 GetBuiltinTypeError &Error,
7850 unsigned *IntegerConstantArgs) const {
7851 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
7853 SmallVector<QualType, 8> ArgTypes;
7855 bool RequiresICE = false;
7857 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7859 if (Error != GE_None)
7862 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7864 while (TypeStr[0] && TypeStr[0] != '.') {
7865 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
7866 if (Error != GE_None)
7869 // If this argument is required to be an IntegerConstantExpression and the
7870 // caller cares, fill in the bitmask we return.
7871 if (RequiresICE && IntegerConstantArgs)
7872 *IntegerConstantArgs |= 1 << ArgTypes.size();
7874 // Do array -> pointer decay. The builtin should use the decayed type.
7875 if (Ty->isArrayType())
7876 Ty = getArrayDecayedType(Ty);
7878 ArgTypes.push_back(Ty);
7881 if (Id == Builtin::BI__GetExceptionInfo)
7884 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7885 "'.' should only occur at end of builtin type list!");
7887 FunctionType::ExtInfo EI(CC_C);
7888 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7890 bool Variadic = (TypeStr[0] == '.');
7892 // We really shouldn't be making a no-proto type here, especially in C++.
7893 if (ArgTypes.empty() && Variadic)
7894 return getFunctionNoProtoType(ResType, EI);
7896 FunctionProtoType::ExtProtoInfo EPI;
7898 EPI.Variadic = Variadic;
7900 return getFunctionType(ResType, ArgTypes, EPI);
7903 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
7904 const FunctionDecl *FD) {
7905 if (!FD->isExternallyVisible())
7906 return GVA_Internal;
7908 GVALinkage External = GVA_StrongExternal;
7909 switch (FD->getTemplateSpecializationKind()) {
7910 case TSK_Undeclared:
7911 case TSK_ExplicitSpecialization:
7912 External = GVA_StrongExternal;
7915 case TSK_ExplicitInstantiationDefinition:
7916 return GVA_StrongODR;
7918 // C++11 [temp.explicit]p10:
7919 // [ Note: The intent is that an inline function that is the subject of
7920 // an explicit instantiation declaration will still be implicitly
7921 // instantiated when used so that the body can be considered for
7922 // inlining, but that no out-of-line copy of the inline function would be
7923 // generated in the translation unit. -- end note ]
7924 case TSK_ExplicitInstantiationDeclaration:
7925 return GVA_AvailableExternally;
7927 case TSK_ImplicitInstantiation:
7928 External = GVA_DiscardableODR;
7932 if (!FD->isInlined())
7935 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
7936 !FD->hasAttr<DLLExportAttr>()) ||
7937 FD->hasAttr<GNUInlineAttr>()) {
7938 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
7940 // GNU or C99 inline semantics. Determine whether this symbol should be
7941 // externally visible.
7942 if (FD->isInlineDefinitionExternallyVisible())
7945 // C99 inline semantics, where the symbol is not externally visible.
7946 return GVA_AvailableExternally;
7949 // Functions specified with extern and inline in -fms-compatibility mode
7950 // forcibly get emitted. While the body of the function cannot be later
7951 // replaced, the function definition cannot be discarded.
7952 if (FD->isMSExternInline())
7953 return GVA_StrongODR;
7955 return GVA_DiscardableODR;
7958 static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
7959 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
7960 // dllexport/dllimport on inline functions.
7961 if (D->hasAttr<DLLImportAttr>()) {
7962 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
7963 return GVA_AvailableExternally;
7964 } else if (D->hasAttr<DLLExportAttr>()) {
7965 if (L == GVA_DiscardableODR)
7966 return GVA_StrongODR;
7971 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
7972 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
7976 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
7977 const VarDecl *VD) {
7978 if (!VD->isExternallyVisible())
7979 return GVA_Internal;
7981 if (VD->isStaticLocal()) {
7982 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
7983 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
7984 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
7985 LexicalContext = LexicalContext->getLexicalParent();
7987 // Let the static local variable inherit its linkage from the nearest
7988 // enclosing function.
7990 StaticLocalLinkage =
7991 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
7993 // GVA_StrongODR function linkage is stronger than what we need,
7994 // downgrade to GVA_DiscardableODR.
7995 // This allows us to discard the variable if we never end up needing it.
7996 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
7997 : StaticLocalLinkage;
8000 // MSVC treats in-class initialized static data members as definitions.
8001 // By giving them non-strong linkage, out-of-line definitions won't
8002 // cause link errors.
8003 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8004 return GVA_DiscardableODR;
8006 switch (VD->getTemplateSpecializationKind()) {
8007 case TSK_Undeclared:
8008 case TSK_ExplicitSpecialization:
8009 return GVA_StrongExternal;
8011 case TSK_ExplicitInstantiationDefinition:
8012 return GVA_StrongODR;
8014 case TSK_ExplicitInstantiationDeclaration:
8015 return GVA_AvailableExternally;
8017 case TSK_ImplicitInstantiation:
8018 return GVA_DiscardableODR;
8021 llvm_unreachable("Invalid Linkage!");
8024 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8025 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
8029 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
8030 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8031 if (!VD->isFileVarDecl())
8033 // Global named register variables (GNU extension) are never emitted.
8034 if (VD->getStorageClass() == SC_Register)
8036 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8037 // We never need to emit an uninstantiated function template.
8038 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8040 } else if (isa<OMPThreadPrivateDecl>(D))
8045 // If this is a member of a class template, we do not need to emit it.
8046 if (D->getDeclContext()->isDependentContext())
8049 // Weak references don't produce any output by themselves.
8050 if (D->hasAttr<WeakRefAttr>())
8053 // Aliases and used decls are required.
8054 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8057 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8058 // Forward declarations aren't required.
8059 if (!FD->doesThisDeclarationHaveABody())
8060 return FD->doesDeclarationForceExternallyVisibleDefinition();
8062 // Constructors and destructors are required.
8063 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8066 // The key function for a class is required. This rule only comes
8067 // into play when inline functions can be key functions, though.
8068 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8069 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8070 const CXXRecordDecl *RD = MD->getParent();
8071 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8072 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8073 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8079 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8081 // static, static inline, always_inline, and extern inline functions can
8082 // always be deferred. Normal inline functions can be deferred in C99/C++.
8083 // Implicit template instantiations can also be deferred in C++.
8084 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8085 Linkage == GVA_DiscardableODR)
8090 const VarDecl *VD = cast<VarDecl>(D);
8091 assert(VD->isFileVarDecl() && "Expected file scoped var");
8093 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8094 !isMSStaticDataMemberInlineDefinition(VD))
8097 // Variables that can be needed in other TUs are required.
8098 GVALinkage L = GetGVALinkageForVariable(VD);
8099 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8100 L != GVA_DiscardableODR)
8103 // Variables that have destruction with side-effects are required.
8104 if (VD->getType().isDestructedType())
8107 // Variables that have initialization with side-effects are required.
8108 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
8114 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8115 bool IsCXXMethod) const {
8116 // Pass through to the C++ ABI object
8118 return ABI->getDefaultMethodCallConv(IsVariadic);
8120 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8122 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
8125 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
8126 // Pass through to the C++ ABI object
8127 return ABI->isNearlyEmpty(RD);
8130 VTableContextBase *ASTContext::getVTableContext() {
8131 if (!VTContext.get()) {
8132 if (Target->getCXXABI().isMicrosoft())
8133 VTContext.reset(new MicrosoftVTableContext(*this));
8135 VTContext.reset(new ItaniumVTableContext(*this));
8137 return VTContext.get();
8140 MangleContext *ASTContext::createMangleContext() {
8141 switch (Target->getCXXABI().getKind()) {
8142 case TargetCXXABI::GenericAArch64:
8143 case TargetCXXABI::GenericItanium:
8144 case TargetCXXABI::GenericARM:
8145 case TargetCXXABI::GenericMIPS:
8146 case TargetCXXABI::iOS:
8147 case TargetCXXABI::iOS64:
8148 return ItaniumMangleContext::create(*this, getDiagnostics());
8149 case TargetCXXABI::Microsoft:
8150 return MicrosoftMangleContext::create(*this, getDiagnostics());
8152 llvm_unreachable("Unsupported ABI");
8155 CXXABI::~CXXABI() {}
8157 size_t ASTContext::getSideTableAllocatedMemory() const {
8158 return ASTRecordLayouts.getMemorySize() +
8159 llvm::capacity_in_bytes(ObjCLayouts) +
8160 llvm::capacity_in_bytes(KeyFunctions) +
8161 llvm::capacity_in_bytes(ObjCImpls) +
8162 llvm::capacity_in_bytes(BlockVarCopyInits) +
8163 llvm::capacity_in_bytes(DeclAttrs) +
8164 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8165 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8166 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8167 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8168 llvm::capacity_in_bytes(OverriddenMethods) +
8169 llvm::capacity_in_bytes(Types) +
8170 llvm::capacity_in_bytes(VariableArrayTypes) +
8171 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
8174 /// getIntTypeForBitwidth -
8175 /// sets integer QualTy according to specified details:
8176 /// bitwidth, signed/unsigned.
8177 /// Returns empty type if there is no appropriate target types.
8178 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8179 unsigned Signed) const {
8180 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8181 CanQualType QualTy = getFromTargetType(Ty);
8182 if (!QualTy && DestWidth == 128)
8183 return Signed ? Int128Ty : UnsignedInt128Ty;
8187 /// getRealTypeForBitwidth -
8188 /// sets floating point QualTy according to specified bitwidth.
8189 /// Returns empty type if there is no appropriate target types.
8190 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8191 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8193 case TargetInfo::Float:
8195 case TargetInfo::Double:
8197 case TargetInfo::LongDouble:
8198 return LongDoubleTy;
8199 case TargetInfo::NoFloat:
8203 llvm_unreachable("Unhandled TargetInfo::RealType value");
8206 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8208 MangleNumbers[ND] = Number;
8211 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8212 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8213 MangleNumbers.find(ND);
8214 return I != MangleNumbers.end() ? I->second : 1;
8217 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8219 StaticLocalNumbers[VD] = Number;
8222 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8223 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8224 StaticLocalNumbers.find(VD);
8225 return I != StaticLocalNumbers.end() ? I->second : 1;
8228 MangleNumberingContext &
8229 ASTContext::getManglingNumberContext(const DeclContext *DC) {
8230 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8231 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8233 MCtx = createMangleNumberingContext();
8237 MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8238 return ABI->createMangleNumberingContext();
8241 const CXXConstructorDecl *
8242 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8243 return ABI->getCopyConstructorForExceptionObject(
8244 cast<CXXRecordDecl>(RD->getFirstDecl()));
8247 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8248 CXXConstructorDecl *CD) {
8249 return ABI->addCopyConstructorForExceptionObject(
8250 cast<CXXRecordDecl>(RD->getFirstDecl()),
8251 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8254 void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8255 unsigned ParmIdx, Expr *DAE) {
8256 ABI->addDefaultArgExprForConstructor(
8257 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8260 Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8262 return ABI->getDefaultArgExprForConstructor(
8263 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8266 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8267 ParamIndices[D] = index;
8270 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8271 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8272 assert(I != ParamIndices.end() &&
8273 "ParmIndices lacks entry set by ParmVarDecl");
8278 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8280 assert(E && E->getStorageDuration() == SD_Static &&
8281 "don't need to cache the computed value for this temporary");
8283 return &MaterializedTemporaryValues[E];
8285 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8286 MaterializedTemporaryValues.find(E);
8287 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
8290 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8291 const llvm::Triple &T = getTargetInfo().getTriple();
8292 if (!T.isOSDarwin())
8295 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8296 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8299 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8300 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8301 uint64_t Size = sizeChars.getQuantity();
8302 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8303 unsigned Align = alignChars.getQuantity();
8304 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8305 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8310 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8311 /// parents as defined by the \c RecursiveASTVisitor.
8313 /// Note that the relationship described here is purely in terms of AST
8314 /// traversal - there are other relationships (for example declaration context)
8315 /// in the AST that are better modeled by special matchers.
8317 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8318 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8321 /// \brief Builds and returns the translation unit's parent map.
8323 /// The caller takes ownership of the returned \c ParentMap.
8324 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8325 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8326 Visitor.TraverseDecl(&TU);
8327 return Visitor.Parents;
8331 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8333 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8336 bool shouldVisitTemplateInstantiations() const {
8339 bool shouldVisitImplicitCode() const {
8342 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8343 // are not triggered during data recursion.
8344 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8348 template <typename T>
8349 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8352 if (ParentStack.size() > 0) {
8353 // FIXME: Currently we add the same parent multiple times, but only
8354 // when no memoization data is available for the type.
8355 // For example when we visit all subexpressions of template
8356 // instantiations; this is suboptimal, but benign: the only way to
8357 // visit those is with hasAncestor / hasParent, and those do not create
8359 // The plan is to enable DynTypedNode to be storable in a map or hash
8360 // map. The main problem there is to implement hash functions /
8361 // comparison operators for all types that DynTypedNode supports that
8362 // do not have pointer identity.
8363 auto &NodeOrVector = (*Parents)[Node];
8364 if (NodeOrVector.isNull()) {
8365 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
8367 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8369 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8370 auto *Vector = new ASTContext::ParentVector(1, *Node);
8371 NodeOrVector = Vector;
8374 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
8377 NodeOrVector.template get<ASTContext::ParentVector *>();
8378 // Skip duplicates for types that have memoization data.
8379 // We must check that the type has memoization data before calling
8380 // std::find() because DynTypedNode::operator== can't compare all
8382 bool Found = ParentStack.back().getMemoizationData() &&
8383 std::find(Vector->begin(), Vector->end(),
8384 ParentStack.back()) != Vector->end();
8386 Vector->push_back(ParentStack.back());
8389 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8390 bool Result = (this ->* traverse) (Node);
8391 ParentStack.pop_back();
8395 bool TraverseDecl(Decl *DeclNode) {
8396 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8399 bool TraverseStmt(Stmt *StmtNode) {
8400 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8403 ASTContext::ParentMap *Parents;
8404 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8406 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8411 ArrayRef<ast_type_traits::DynTypedNode>
8412 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8413 assert(Node.getMemoizationData() &&
8414 "Invariant broken: only nodes that support memoization may be "
8415 "used in the parent map.");
8417 // We always need to run over the whole translation unit, as
8418 // hasAncestor can escape any subtree.
8420 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8422 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8423 if (I == AllParents->end()) {
8426 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8427 return llvm::makeArrayRef(N, 1);
8429 return *I->second.get<ParentVector *>();
8433 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8434 const ObjCMethodDecl *MethodImpl) {
8435 // No point trying to match an unavailable/deprecated mothod.
8436 if (MethodDecl->hasAttr<UnavailableAttr>()
8437 || MethodDecl->hasAttr<DeprecatedAttr>())
8439 if (MethodDecl->getObjCDeclQualifier() !=
8440 MethodImpl->getObjCDeclQualifier())
8442 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
8445 if (MethodDecl->param_size() != MethodImpl->param_size())
8448 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8449 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8450 EF = MethodDecl->param_end();
8451 IM != EM && IF != EF; ++IM, ++IF) {
8452 const ParmVarDecl *DeclVar = (*IF);
8453 const ParmVarDecl *ImplVar = (*IM);
8454 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8456 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8459 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8463 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8464 // doesn't include ASTContext.h
8466 clang::LazyGenerationalUpdatePtr<
8467 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8468 clang::LazyGenerationalUpdatePtr<
8469 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8470 const clang::ASTContext &Ctx, Decl *Value);