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(),
742 SourceMgr(SM), LangOpts(LOpts),
743 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFile, 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 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
870 RecordDecl::TagKind TK) const {
873 if (getLangOpts().CPlusPlus)
874 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
875 Loc, &Idents.get(Name));
877 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
879 NewDecl->setImplicit();
883 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
884 StringRef Name) const {
885 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
886 TypedefDecl *NewDecl = TypedefDecl::Create(
887 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
888 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
889 NewDecl->setImplicit();
893 TypedefDecl *ASTContext::getInt128Decl() const {
895 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
899 TypedefDecl *ASTContext::getUInt128Decl() const {
901 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
905 TypeDecl *ASTContext::getFloat128StubType() const {
906 assert(LangOpts.CPlusPlus && "should only be called for c++");
907 if (!Float128StubDecl)
908 Float128StubDecl = buildImplicitRecord("__float128");
910 return Float128StubDecl;
913 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
914 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
915 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
919 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
920 assert((!this->Target || this->Target == &Target) &&
921 "Incorrect target reinitialization");
922 assert(VoidTy.isNull() && "Context reinitialized?");
924 this->Target = &Target;
926 ABI.reset(createCXXABI(Target));
927 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
928 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
931 InitBuiltinType(VoidTy, BuiltinType::Void);
934 InitBuiltinType(BoolTy, BuiltinType::Bool);
936 if (LangOpts.CharIsSigned)
937 InitBuiltinType(CharTy, BuiltinType::Char_S);
939 InitBuiltinType(CharTy, BuiltinType::Char_U);
941 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
942 InitBuiltinType(ShortTy, BuiltinType::Short);
943 InitBuiltinType(IntTy, BuiltinType::Int);
944 InitBuiltinType(LongTy, BuiltinType::Long);
945 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
948 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
949 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
950 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
951 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
952 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
955 InitBuiltinType(FloatTy, BuiltinType::Float);
956 InitBuiltinType(DoubleTy, BuiltinType::Double);
957 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
959 // GNU extension, 128-bit integers.
960 InitBuiltinType(Int128Ty, BuiltinType::Int128);
961 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
964 if (TargetInfo::isTypeSigned(Target.getWCharType()))
965 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
966 else // -fshort-wchar makes wchar_t be unsigned.
967 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
968 if (LangOpts.CPlusPlus && LangOpts.WChar)
969 WideCharTy = WCharTy;
971 // C99 (or C++ using -fno-wchar).
972 WideCharTy = getFromTargetType(Target.getWCharType());
975 WIntTy = getFromTargetType(Target.getWIntType());
977 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
978 InitBuiltinType(Char16Ty, BuiltinType::Char16);
980 Char16Ty = getFromTargetType(Target.getChar16Type());
982 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
983 InitBuiltinType(Char32Ty, BuiltinType::Char32);
985 Char32Ty = getFromTargetType(Target.getChar32Type());
987 // Placeholder type for type-dependent expressions whose type is
988 // completely unknown. No code should ever check a type against
989 // DependentTy and users should never see it; however, it is here to
990 // help diagnose failures to properly check for type-dependent
992 InitBuiltinType(DependentTy, BuiltinType::Dependent);
994 // Placeholder type for functions.
995 InitBuiltinType(OverloadTy, BuiltinType::Overload);
997 // Placeholder type for bound members.
998 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1000 // Placeholder type for pseudo-objects.
1001 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1003 // "any" type; useful for debugger-like clients.
1004 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1006 // Placeholder type for unbridged ARC casts.
1007 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1009 // Placeholder type for builtin functions.
1010 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1013 FloatComplexTy = getComplexType(FloatTy);
1014 DoubleComplexTy = getComplexType(DoubleTy);
1015 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1017 // Builtin types for 'id', 'Class', and 'SEL'.
1018 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1019 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1020 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1022 if (LangOpts.OpenCL) {
1023 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1024 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1025 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1026 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1027 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1028 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
1030 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1031 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1034 // Builtin type for __objc_yes and __objc_no
1035 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1036 SignedCharTy : BoolTy);
1038 ObjCConstantStringType = QualType();
1040 ObjCSuperType = QualType();
1043 VoidPtrTy = getPointerType(VoidTy);
1045 // nullptr type (C++0x 2.14.7)
1046 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1048 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1049 InitBuiltinType(HalfTy, BuiltinType::Half);
1051 // Builtin type used to help define __builtin_va_list.
1052 VaListTagTy = QualType();
1055 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1056 return SourceMgr.getDiagnostics();
1059 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1060 AttrVec *&Result = DeclAttrs[D];
1062 void *Mem = Allocate(sizeof(AttrVec));
1063 Result = new (Mem) AttrVec;
1069 /// \brief Erase the attributes corresponding to the given declaration.
1070 void ASTContext::eraseDeclAttrs(const Decl *D) {
1071 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1072 if (Pos != DeclAttrs.end()) {
1073 Pos->second->~AttrVec();
1074 DeclAttrs.erase(Pos);
1079 MemberSpecializationInfo *
1080 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1081 assert(Var->isStaticDataMember() && "Not a static data member");
1082 return getTemplateOrSpecializationInfo(Var)
1083 .dyn_cast<MemberSpecializationInfo *>();
1086 ASTContext::TemplateOrSpecializationInfo
1087 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1088 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1089 TemplateOrInstantiation.find(Var);
1090 if (Pos == TemplateOrInstantiation.end())
1091 return TemplateOrSpecializationInfo();
1097 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1098 TemplateSpecializationKind TSK,
1099 SourceLocation PointOfInstantiation) {
1100 assert(Inst->isStaticDataMember() && "Not a static data member");
1101 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1102 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1103 Tmpl, TSK, PointOfInstantiation));
1107 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1108 TemplateOrSpecializationInfo TSI) {
1109 assert(!TemplateOrInstantiation[Inst] &&
1110 "Already noted what the variable was instantiated from");
1111 TemplateOrInstantiation[Inst] = TSI;
1114 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1115 const FunctionDecl *FD){
1116 assert(FD && "Specialization is 0");
1117 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1118 = ClassScopeSpecializationPattern.find(FD);
1119 if (Pos == ClassScopeSpecializationPattern.end())
1125 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1126 FunctionDecl *Pattern) {
1127 assert(FD && "Specialization is 0");
1128 assert(Pattern && "Class scope specialization pattern is 0");
1129 ClassScopeSpecializationPattern[FD] = Pattern;
1133 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
1134 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
1135 = InstantiatedFromUsingDecl.find(UUD);
1136 if (Pos == InstantiatedFromUsingDecl.end())
1143 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1144 assert((isa<UsingDecl>(Pattern) ||
1145 isa<UnresolvedUsingValueDecl>(Pattern) ||
1146 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1147 "pattern decl is not a using decl");
1148 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1149 InstantiatedFromUsingDecl[Inst] = Pattern;
1153 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1154 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1155 = InstantiatedFromUsingShadowDecl.find(Inst);
1156 if (Pos == InstantiatedFromUsingShadowDecl.end())
1163 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1164 UsingShadowDecl *Pattern) {
1165 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1166 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1169 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1170 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1171 = InstantiatedFromUnnamedFieldDecl.find(Field);
1172 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1178 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1180 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1181 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1182 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1183 "Already noted what unnamed field was instantiated from");
1185 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1188 ASTContext::overridden_cxx_method_iterator
1189 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1190 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1191 = OverriddenMethods.find(Method->getCanonicalDecl());
1192 if (Pos == OverriddenMethods.end())
1195 return Pos->second.begin();
1198 ASTContext::overridden_cxx_method_iterator
1199 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1200 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1201 = OverriddenMethods.find(Method->getCanonicalDecl());
1202 if (Pos == OverriddenMethods.end())
1205 return Pos->second.end();
1209 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1210 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1211 = OverriddenMethods.find(Method->getCanonicalDecl());
1212 if (Pos == OverriddenMethods.end())
1215 return Pos->second.size();
1218 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1219 const CXXMethodDecl *Overridden) {
1220 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1221 OverriddenMethods[Method].push_back(Overridden);
1224 void ASTContext::getOverriddenMethods(
1226 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1229 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1230 Overridden.append(overridden_methods_begin(CXXMethod),
1231 overridden_methods_end(CXXMethod));
1235 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1239 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1240 Method->getOverriddenMethods(OverDecls);
1241 Overridden.append(OverDecls.begin(), OverDecls.end());
1244 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1245 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1246 assert(!Import->isFromASTFile() && "Non-local import declaration");
1247 if (!FirstLocalImport) {
1248 FirstLocalImport = Import;
1249 LastLocalImport = Import;
1253 LastLocalImport->NextLocalImport = Import;
1254 LastLocalImport = Import;
1257 //===----------------------------------------------------------------------===//
1258 // Type Sizing and Analysis
1259 //===----------------------------------------------------------------------===//
1261 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1262 /// scalar floating point type.
1263 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1264 const BuiltinType *BT = T->getAs<BuiltinType>();
1265 assert(BT && "Not a floating point type!");
1266 switch (BT->getKind()) {
1267 default: llvm_unreachable("Not a floating point type!");
1268 case BuiltinType::Half: return Target->getHalfFormat();
1269 case BuiltinType::Float: return Target->getFloatFormat();
1270 case BuiltinType::Double: return Target->getDoubleFormat();
1271 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1275 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1276 unsigned Align = Target->getCharWidth();
1278 bool UseAlignAttrOnly = false;
1279 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1280 Align = AlignFromAttr;
1282 // __attribute__((aligned)) can increase or decrease alignment
1283 // *except* on a struct or struct member, where it only increases
1284 // alignment unless 'packed' is also specified.
1286 // It is an error for alignas to decrease alignment, so we can
1287 // ignore that possibility; Sema should diagnose it.
1288 if (isa<FieldDecl>(D)) {
1289 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1290 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1292 UseAlignAttrOnly = true;
1295 else if (isa<FieldDecl>(D))
1297 D->hasAttr<PackedAttr>() ||
1298 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1300 // If we're using the align attribute only, just ignore everything
1301 // else about the declaration and its type.
1302 if (UseAlignAttrOnly) {
1305 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1306 QualType T = VD->getType();
1307 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
1309 T = RT->getPointeeType();
1311 T = getPointerType(RT->getPointeeType());
1313 QualType BaseT = getBaseElementType(T);
1314 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
1315 // Adjust alignments of declarations with array type by the
1316 // large-array alignment on the target.
1317 if (const ArrayType *arrayType = getAsArrayType(T)) {
1318 unsigned MinWidth = Target->getLargeArrayMinWidth();
1319 if (!ForAlignof && MinWidth) {
1320 if (isa<VariableArrayType>(arrayType))
1321 Align = std::max(Align, Target->getLargeArrayAlign());
1322 else if (isa<ConstantArrayType>(arrayType) &&
1323 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1324 Align = std::max(Align, Target->getLargeArrayAlign());
1327 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1328 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1329 if (VD->hasGlobalStorage())
1330 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1334 // Fields can be subject to extra alignment constraints, like if
1335 // the field is packed, the struct is packed, or the struct has a
1336 // a max-field-alignment constraint (#pragma pack). So calculate
1337 // the actual alignment of the field within the struct, and then
1338 // (as we're expected to) constrain that by the alignment of the type.
1339 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1340 const RecordDecl *Parent = Field->getParent();
1341 // We can only produce a sensible answer if the record is valid.
1342 if (!Parent->isInvalidDecl()) {
1343 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1345 // Start with the record's overall alignment.
1346 unsigned FieldAlign = toBits(Layout.getAlignment());
1348 // Use the GCD of that and the offset within the record.
1349 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1351 // Alignment is always a power of 2, so the GCD will be a power of 2,
1352 // which means we get to do this crazy thing instead of Euclid's.
1353 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1354 if (LowBitOfOffset < FieldAlign)
1355 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1358 Align = std::min(Align, FieldAlign);
1363 return toCharUnitsFromBits(Align);
1366 // getTypeInfoDataSizeInChars - Return the size of a type, in
1367 // chars. If the type is a record, its data size is returned. This is
1368 // the size of the memcpy that's performed when assigning this type
1369 // using a trivial copy/move assignment operator.
1370 std::pair<CharUnits, CharUnits>
1371 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1372 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1374 // In C++, objects can sometimes be allocated into the tail padding
1375 // of a base-class subobject. We decide whether that's possible
1376 // during class layout, so here we can just trust the layout results.
1377 if (getLangOpts().CPlusPlus) {
1378 if (const RecordType *RT = T->getAs<RecordType>()) {
1379 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1380 sizeAndAlign.first = layout.getDataSize();
1384 return sizeAndAlign;
1387 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1388 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1389 std::pair<CharUnits, CharUnits>
1390 static getConstantArrayInfoInChars(const ASTContext &Context,
1391 const ConstantArrayType *CAT) {
1392 std::pair<CharUnits, CharUnits> EltInfo =
1393 Context.getTypeInfoInChars(CAT->getElementType());
1394 uint64_t Size = CAT->getSize().getZExtValue();
1395 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1396 (uint64_t)(-1)/Size) &&
1397 "Overflow in array type char size evaluation");
1398 uint64_t Width = EltInfo.first.getQuantity() * Size;
1399 unsigned Align = EltInfo.second.getQuantity();
1400 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1401 Context.getTargetInfo().getPointerWidth(0) == 64)
1402 Width = llvm::RoundUpToAlignment(Width, Align);
1403 return std::make_pair(CharUnits::fromQuantity(Width),
1404 CharUnits::fromQuantity(Align));
1407 std::pair<CharUnits, CharUnits>
1408 ASTContext::getTypeInfoInChars(const Type *T) const {
1409 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1410 return getConstantArrayInfoInChars(*this, CAT);
1411 TypeInfo Info = getTypeInfo(T);
1412 return std::make_pair(toCharUnitsFromBits(Info.Width),
1413 toCharUnitsFromBits(Info.Align));
1416 std::pair<CharUnits, CharUnits>
1417 ASTContext::getTypeInfoInChars(QualType T) const {
1418 return getTypeInfoInChars(T.getTypePtr());
1421 bool ASTContext::isAlignmentRequired(const Type *T) const {
1422 return getTypeInfo(T).AlignIsRequired;
1425 bool ASTContext::isAlignmentRequired(QualType T) const {
1426 return isAlignmentRequired(T.getTypePtr());
1429 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1430 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1431 if (I != MemoizedTypeInfo.end())
1434 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1435 TypeInfo TI = getTypeInfoImpl(T);
1436 MemoizedTypeInfo[T] = TI;
1440 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1441 /// method does not work on incomplete types.
1443 /// FIXME: Pointers into different addr spaces could have different sizes and
1444 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1445 /// should take a QualType, &c.
1446 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1449 bool AlignIsRequired = false;
1450 switch (T->getTypeClass()) {
1451 #define TYPE(Class, Base)
1452 #define ABSTRACT_TYPE(Class, Base)
1453 #define NON_CANONICAL_TYPE(Class, Base)
1454 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1455 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1457 assert(!T->isDependentType() && "should not see dependent types here"); \
1458 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1459 #include "clang/AST/TypeNodes.def"
1460 llvm_unreachable("Should not see dependent types");
1462 case Type::FunctionNoProto:
1463 case Type::FunctionProto:
1464 // GCC extension: alignof(function) = 32 bits
1469 case Type::IncompleteArray:
1470 case Type::VariableArray:
1472 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1475 case Type::ConstantArray: {
1476 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1478 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1479 uint64_t Size = CAT->getSize().getZExtValue();
1480 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1481 "Overflow in array type bit size evaluation");
1482 Width = EltInfo.Width * Size;
1483 Align = EltInfo.Align;
1484 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1485 getTargetInfo().getPointerWidth(0) == 64)
1486 Width = llvm::RoundUpToAlignment(Width, Align);
1489 case Type::ExtVector:
1490 case Type::Vector: {
1491 const VectorType *VT = cast<VectorType>(T);
1492 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1493 Width = EltInfo.Width * VT->getNumElements();
1495 // If the alignment is not a power of 2, round up to the next power of 2.
1496 // This happens for non-power-of-2 length vectors.
1497 if (Align & (Align-1)) {
1498 Align = llvm::NextPowerOf2(Align);
1499 Width = llvm::RoundUpToAlignment(Width, Align);
1501 // Adjust the alignment based on the target max.
1502 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1503 if (TargetVectorAlign && TargetVectorAlign < Align)
1504 Align = TargetVectorAlign;
1509 switch (cast<BuiltinType>(T)->getKind()) {
1510 default: llvm_unreachable("Unknown builtin type!");
1511 case BuiltinType::Void:
1512 // GCC extension: alignof(void) = 8 bits.
1517 case BuiltinType::Bool:
1518 Width = Target->getBoolWidth();
1519 Align = Target->getBoolAlign();
1521 case BuiltinType::Char_S:
1522 case BuiltinType::Char_U:
1523 case BuiltinType::UChar:
1524 case BuiltinType::SChar:
1525 Width = Target->getCharWidth();
1526 Align = Target->getCharAlign();
1528 case BuiltinType::WChar_S:
1529 case BuiltinType::WChar_U:
1530 Width = Target->getWCharWidth();
1531 Align = Target->getWCharAlign();
1533 case BuiltinType::Char16:
1534 Width = Target->getChar16Width();
1535 Align = Target->getChar16Align();
1537 case BuiltinType::Char32:
1538 Width = Target->getChar32Width();
1539 Align = Target->getChar32Align();
1541 case BuiltinType::UShort:
1542 case BuiltinType::Short:
1543 Width = Target->getShortWidth();
1544 Align = Target->getShortAlign();
1546 case BuiltinType::UInt:
1547 case BuiltinType::Int:
1548 Width = Target->getIntWidth();
1549 Align = Target->getIntAlign();
1551 case BuiltinType::ULong:
1552 case BuiltinType::Long:
1553 Width = Target->getLongWidth();
1554 Align = Target->getLongAlign();
1556 case BuiltinType::ULongLong:
1557 case BuiltinType::LongLong:
1558 Width = Target->getLongLongWidth();
1559 Align = Target->getLongLongAlign();
1561 case BuiltinType::Int128:
1562 case BuiltinType::UInt128:
1564 Align = 128; // int128_t is 128-bit aligned on all targets.
1566 case BuiltinType::Half:
1567 Width = Target->getHalfWidth();
1568 Align = Target->getHalfAlign();
1570 case BuiltinType::Float:
1571 Width = Target->getFloatWidth();
1572 Align = Target->getFloatAlign();
1574 case BuiltinType::Double:
1575 Width = Target->getDoubleWidth();
1576 Align = Target->getDoubleAlign();
1578 case BuiltinType::LongDouble:
1579 Width = Target->getLongDoubleWidth();
1580 Align = Target->getLongDoubleAlign();
1582 case BuiltinType::NullPtr:
1583 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1584 Align = Target->getPointerAlign(0); // == sizeof(void*)
1586 case BuiltinType::ObjCId:
1587 case BuiltinType::ObjCClass:
1588 case BuiltinType::ObjCSel:
1589 Width = Target->getPointerWidth(0);
1590 Align = Target->getPointerAlign(0);
1592 case BuiltinType::OCLSampler:
1593 // Samplers are modeled as integers.
1594 Width = Target->getIntWidth();
1595 Align = Target->getIntAlign();
1597 case BuiltinType::OCLEvent:
1598 case BuiltinType::OCLImage1d:
1599 case BuiltinType::OCLImage1dArray:
1600 case BuiltinType::OCLImage1dBuffer:
1601 case BuiltinType::OCLImage2d:
1602 case BuiltinType::OCLImage2dArray:
1603 case BuiltinType::OCLImage3d:
1604 // Currently these types are pointers to opaque types.
1605 Width = Target->getPointerWidth(0);
1606 Align = Target->getPointerAlign(0);
1610 case Type::ObjCObjectPointer:
1611 Width = Target->getPointerWidth(0);
1612 Align = Target->getPointerAlign(0);
1614 case Type::BlockPointer: {
1615 unsigned AS = getTargetAddressSpace(
1616 cast<BlockPointerType>(T)->getPointeeType());
1617 Width = Target->getPointerWidth(AS);
1618 Align = Target->getPointerAlign(AS);
1621 case Type::LValueReference:
1622 case Type::RValueReference: {
1623 // alignof and sizeof should never enter this code path here, so we go
1624 // the pointer route.
1625 unsigned AS = getTargetAddressSpace(
1626 cast<ReferenceType>(T)->getPointeeType());
1627 Width = Target->getPointerWidth(AS);
1628 Align = Target->getPointerAlign(AS);
1631 case Type::Pointer: {
1632 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1633 Width = Target->getPointerWidth(AS);
1634 Align = Target->getPointerAlign(AS);
1637 case Type::MemberPointer: {
1638 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1639 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1642 case Type::Complex: {
1643 // Complex types have the same alignment as their elements, but twice the
1645 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1646 Width = EltInfo.Width * 2;
1647 Align = EltInfo.Align;
1650 case Type::ObjCObject:
1651 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1652 case Type::Adjusted:
1654 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1655 case Type::ObjCInterface: {
1656 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1657 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1658 Width = toBits(Layout.getSize());
1659 Align = toBits(Layout.getAlignment());
1664 const TagType *TT = cast<TagType>(T);
1666 if (TT->getDecl()->isInvalidDecl()) {
1672 if (const EnumType *ET = dyn_cast<EnumType>(TT))
1673 return getTypeInfo(ET->getDecl()->getIntegerType());
1675 const RecordType *RT = cast<RecordType>(TT);
1676 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
1677 Width = toBits(Layout.getSize());
1678 Align = toBits(Layout.getAlignment());
1682 case Type::SubstTemplateTypeParm:
1683 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1684 getReplacementType().getTypePtr());
1687 const AutoType *A = cast<AutoType>(T);
1688 assert(!A->getDeducedType().isNull() &&
1689 "cannot request the size of an undeduced or dependent auto type");
1690 return getTypeInfo(A->getDeducedType().getTypePtr());
1694 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1696 case Type::Typedef: {
1697 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1698 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1699 // If the typedef has an aligned attribute on it, it overrides any computed
1700 // alignment we have. This violates the GCC documentation (which says that
1701 // attribute(aligned) can only round up) but matches its implementation.
1702 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
1704 AlignIsRequired = true;
1707 AlignIsRequired = Info.AlignIsRequired;
1713 case Type::Elaborated:
1714 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1716 case Type::Attributed:
1718 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1720 case Type::Atomic: {
1721 // Start with the base type information.
1722 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1726 // If the size of the type doesn't exceed the platform's max
1727 // atomic promotion width, make the size and alignment more
1728 // favorable to atomic operations:
1729 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1730 // Round the size up to a power of 2.
1731 if (!llvm::isPowerOf2_64(Width))
1732 Width = llvm::NextPowerOf2(Width);
1734 // Set the alignment equal to the size.
1735 Align = static_cast<unsigned>(Width);
1741 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1742 return TypeInfo(Width, Align, AlignIsRequired);
1745 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1746 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1747 return CharUnits::fromQuantity(BitSize / getCharWidth());
1750 /// toBits - Convert a size in characters to a size in characters.
1751 int64_t ASTContext::toBits(CharUnits CharSize) const {
1752 return CharSize.getQuantity() * getCharWidth();
1755 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1756 /// This method does not work on incomplete types.
1757 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1758 return getTypeInfoInChars(T).first;
1760 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1761 return getTypeInfoInChars(T).first;
1764 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1765 /// characters. This method does not work on incomplete types.
1766 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1767 return toCharUnitsFromBits(getTypeAlign(T));
1769 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1770 return toCharUnitsFromBits(getTypeAlign(T));
1773 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1774 /// type for the current target in bits. This can be different than the ABI
1775 /// alignment in cases where it is beneficial for performance to overalign
1777 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1778 TypeInfo TI = getTypeInfo(T);
1779 unsigned ABIAlign = TI.Align;
1781 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1782 return ABIAlign; // Never overalign on XCore.
1784 // Double and long long should be naturally aligned if possible.
1785 T = T->getBaseElementTypeUnsafe();
1786 if (const ComplexType *CT = T->getAs<ComplexType>())
1787 T = CT->getElementType().getTypePtr();
1788 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1789 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1790 T->isSpecificBuiltinType(BuiltinType::ULongLong))
1791 // Don't increase the alignment if an alignment attribute was specified on a
1792 // typedef declaration.
1793 if (!TI.AlignIsRequired)
1794 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1799 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
1800 /// to a global variable of the specified type.
1801 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1802 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1805 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
1806 /// should be given to a global variable of the specified type.
1807 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1808 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1811 /// DeepCollectObjCIvars -
1812 /// This routine first collects all declared, but not synthesized, ivars in
1813 /// super class and then collects all ivars, including those synthesized for
1814 /// current class. This routine is used for implementation of current class
1815 /// when all ivars, declared and synthesized are known.
1817 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1819 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1820 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1821 DeepCollectObjCIvars(SuperClass, false, Ivars);
1823 for (const auto *I : OI->ivars())
1826 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1827 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1828 Iv= Iv->getNextIvar())
1829 Ivars.push_back(Iv);
1833 /// CollectInheritedProtocols - Collect all protocols in current class and
1834 /// those inherited by it.
1835 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1836 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1837 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1838 // We can use protocol_iterator here instead of
1839 // all_referenced_protocol_iterator since we are walking all categories.
1840 for (auto *Proto : OI->all_referenced_protocols()) {
1841 Protocols.insert(Proto->getCanonicalDecl());
1842 for (auto *P : Proto->protocols()) {
1843 Protocols.insert(P->getCanonicalDecl());
1844 CollectInheritedProtocols(P, Protocols);
1848 // Categories of this Interface.
1849 for (const auto *Cat : OI->visible_categories())
1850 CollectInheritedProtocols(Cat, Protocols);
1852 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1854 CollectInheritedProtocols(SD, Protocols);
1855 SD = SD->getSuperClass();
1857 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1858 for (auto *Proto : OC->protocols()) {
1859 Protocols.insert(Proto->getCanonicalDecl());
1860 for (const auto *P : Proto->protocols())
1861 CollectInheritedProtocols(P, Protocols);
1863 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1864 for (auto *Proto : OP->protocols()) {
1865 Protocols.insert(Proto->getCanonicalDecl());
1866 for (const auto *P : Proto->protocols())
1867 CollectInheritedProtocols(P, Protocols);
1872 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1874 // Count ivars declared in class extension.
1875 for (const auto *Ext : OI->known_extensions())
1876 count += Ext->ivar_size();
1878 // Count ivar defined in this class's implementation. This
1879 // includes synthesized ivars.
1880 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1881 count += ImplDecl->ivar_size();
1886 bool ASTContext::isSentinelNullExpr(const Expr *E) {
1890 // nullptr_t is always treated as null.
1891 if (E->getType()->isNullPtrType()) return true;
1893 if (E->getType()->isAnyPointerType() &&
1894 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1895 Expr::NPC_ValueDependentIsNull))
1898 // Unfortunately, __null has type 'int'.
1899 if (isa<GNUNullExpr>(E)) return true;
1904 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1905 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1906 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1907 I = ObjCImpls.find(D);
1908 if (I != ObjCImpls.end())
1909 return cast<ObjCImplementationDecl>(I->second);
1912 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1913 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1914 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1915 I = ObjCImpls.find(D);
1916 if (I != ObjCImpls.end())
1917 return cast<ObjCCategoryImplDecl>(I->second);
1921 /// \brief Set the implementation of ObjCInterfaceDecl.
1922 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1923 ObjCImplementationDecl *ImplD) {
1924 assert(IFaceD && ImplD && "Passed null params");
1925 ObjCImpls[IFaceD] = ImplD;
1927 /// \brief Set the implementation of ObjCCategoryDecl.
1928 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1929 ObjCCategoryImplDecl *ImplD) {
1930 assert(CatD && ImplD && "Passed null params");
1931 ObjCImpls[CatD] = ImplD;
1934 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1935 const NamedDecl *ND) const {
1936 if (const ObjCInterfaceDecl *ID =
1937 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1939 if (const ObjCCategoryDecl *CD =
1940 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1941 return CD->getClassInterface();
1942 if (const ObjCImplDecl *IMD =
1943 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1944 return IMD->getClassInterface();
1949 /// \brief Get the copy initialization expression of VarDecl,or NULL if
1951 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1952 assert(VD && "Passed null params");
1953 assert(VD->hasAttr<BlocksAttr>() &&
1954 "getBlockVarCopyInits - not __block var");
1955 llvm::DenseMap<const VarDecl*, Expr*>::iterator
1956 I = BlockVarCopyInits.find(VD);
1957 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
1960 /// \brief Set the copy inialization expression of a block var decl.
1961 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1962 assert(VD && Init && "Passed null params");
1963 assert(VD->hasAttr<BlocksAttr>() &&
1964 "setBlockVarCopyInits - not __block var");
1965 BlockVarCopyInits[VD] = Init;
1968 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1969 unsigned DataSize) const {
1971 DataSize = TypeLoc::getFullDataSizeForType(T);
1973 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1974 "incorrect data size provided to CreateTypeSourceInfo!");
1976 TypeSourceInfo *TInfo =
1977 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1978 new (TInfo) TypeSourceInfo(T);
1982 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1983 SourceLocation L) const {
1984 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1985 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1989 const ASTRecordLayout &
1990 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1991 return getObjCLayout(D, nullptr);
1994 const ASTRecordLayout &
1995 ASTContext::getASTObjCImplementationLayout(
1996 const ObjCImplementationDecl *D) const {
1997 return getObjCLayout(D->getClassInterface(), D);
2000 //===----------------------------------------------------------------------===//
2001 // Type creation/memoization methods
2002 //===----------------------------------------------------------------------===//
2005 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2006 unsigned fastQuals = quals.getFastQualifiers();
2007 quals.removeFastQualifiers();
2009 // Check if we've already instantiated this type.
2010 llvm::FoldingSetNodeID ID;
2011 ExtQuals::Profile(ID, baseType, quals);
2012 void *insertPos = nullptr;
2013 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2014 assert(eq->getQualifiers() == quals);
2015 return QualType(eq, fastQuals);
2018 // If the base type is not canonical, make the appropriate canonical type.
2020 if (!baseType->isCanonicalUnqualified()) {
2021 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2022 canonSplit.Quals.addConsistentQualifiers(quals);
2023 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2025 // Re-find the insert position.
2026 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2029 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2030 ExtQualNodes.InsertNode(eq, insertPos);
2031 return QualType(eq, fastQuals);
2035 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2036 QualType CanT = getCanonicalType(T);
2037 if (CanT.getAddressSpace() == AddressSpace)
2040 // If we are composing extended qualifiers together, merge together
2041 // into one ExtQuals node.
2042 QualifierCollector Quals;
2043 const Type *TypeNode = Quals.strip(T);
2045 // If this type already has an address space specified, it cannot get
2047 assert(!Quals.hasAddressSpace() &&
2048 "Type cannot be in multiple addr spaces!");
2049 Quals.addAddressSpace(AddressSpace);
2051 return getExtQualType(TypeNode, Quals);
2054 QualType ASTContext::getObjCGCQualType(QualType T,
2055 Qualifiers::GC GCAttr) const {
2056 QualType CanT = getCanonicalType(T);
2057 if (CanT.getObjCGCAttr() == GCAttr)
2060 if (const PointerType *ptr = T->getAs<PointerType>()) {
2061 QualType Pointee = ptr->getPointeeType();
2062 if (Pointee->isAnyPointerType()) {
2063 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2064 return getPointerType(ResultType);
2068 // If we are composing extended qualifiers together, merge together
2069 // into one ExtQuals node.
2070 QualifierCollector Quals;
2071 const Type *TypeNode = Quals.strip(T);
2073 // If this type already has an ObjCGC specified, it cannot get
2075 assert(!Quals.hasObjCGCAttr() &&
2076 "Type cannot have multiple ObjCGCs!");
2077 Quals.addObjCGCAttr(GCAttr);
2079 return getExtQualType(TypeNode, Quals);
2082 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2083 FunctionType::ExtInfo Info) {
2084 if (T->getExtInfo() == Info)
2088 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2089 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2091 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2092 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2094 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2097 return cast<FunctionType>(Result.getTypePtr());
2100 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2101 QualType ResultType) {
2102 FD = FD->getMostRecentDecl();
2104 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2105 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2106 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2107 if (FunctionDecl *Next = FD->getPreviousDecl())
2112 if (ASTMutationListener *L = getASTMutationListener())
2113 L->DeducedReturnType(FD, ResultType);
2116 /// Get a function type and produce the equivalent function type with the
2117 /// specified exception specification. Type sugar that can be present on a
2118 /// declaration of a function with an exception specification is permitted
2119 /// and preserved. Other type sugar (for instance, typedefs) is not.
2120 static QualType getFunctionTypeWithExceptionSpec(
2121 ASTContext &Context, QualType Orig,
2122 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2123 // Might have some parens.
2124 if (auto *PT = dyn_cast<ParenType>(Orig))
2125 return Context.getParenType(
2126 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2128 // Might have a calling-convention attribute.
2129 if (auto *AT = dyn_cast<AttributedType>(Orig))
2130 return Context.getAttributedType(
2132 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2133 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2136 // Anything else must be a function type. Rebuild it with the new exception
2138 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2139 return Context.getFunctionType(
2140 Proto->getReturnType(), Proto->getParamTypes(),
2141 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2144 void ASTContext::adjustExceptionSpec(
2145 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2149 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2150 FD->setType(Updated);
2155 // Update the type in the type source information too.
2156 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2157 // If the type and the type-as-written differ, we may need to update
2158 // the type-as-written too.
2159 if (TSInfo->getType() != FD->getType())
2160 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2162 // FIXME: When we get proper type location information for exceptions,
2163 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2164 // up the TypeSourceInfo;
2165 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2166 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2167 "TypeLoc size mismatch from updating exception specification");
2168 TSInfo->overrideType(Updated);
2172 /// getComplexType - Return the uniqued reference to the type for a complex
2173 /// number with the specified element type.
2174 QualType ASTContext::getComplexType(QualType T) const {
2175 // Unique pointers, to guarantee there is only one pointer of a particular
2177 llvm::FoldingSetNodeID ID;
2178 ComplexType::Profile(ID, T);
2180 void *InsertPos = nullptr;
2181 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2182 return QualType(CT, 0);
2184 // If the pointee type isn't canonical, this won't be a canonical type either,
2185 // so fill in the canonical type field.
2187 if (!T.isCanonical()) {
2188 Canonical = getComplexType(getCanonicalType(T));
2190 // Get the new insert position for the node we care about.
2191 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2192 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2194 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2195 Types.push_back(New);
2196 ComplexTypes.InsertNode(New, InsertPos);
2197 return QualType(New, 0);
2200 /// getPointerType - Return the uniqued reference to the type for a pointer to
2201 /// the specified type.
2202 QualType ASTContext::getPointerType(QualType T) const {
2203 // Unique pointers, to guarantee there is only one pointer of a particular
2205 llvm::FoldingSetNodeID ID;
2206 PointerType::Profile(ID, T);
2208 void *InsertPos = nullptr;
2209 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2210 return QualType(PT, 0);
2212 // If the pointee type isn't canonical, this won't be a canonical type either,
2213 // so fill in the canonical type field.
2215 if (!T.isCanonical()) {
2216 Canonical = getPointerType(getCanonicalType(T));
2218 // Get the new insert position for the node we care about.
2219 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2220 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2222 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2223 Types.push_back(New);
2224 PointerTypes.InsertNode(New, InsertPos);
2225 return QualType(New, 0);
2228 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2229 llvm::FoldingSetNodeID ID;
2230 AdjustedType::Profile(ID, Orig, New);
2231 void *InsertPos = nullptr;
2232 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2234 return QualType(AT, 0);
2236 QualType Canonical = getCanonicalType(New);
2238 // Get the new insert position for the node we care about.
2239 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2240 assert(!AT && "Shouldn't be in the map!");
2242 AT = new (*this, TypeAlignment)
2243 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2244 Types.push_back(AT);
2245 AdjustedTypes.InsertNode(AT, InsertPos);
2246 return QualType(AT, 0);
2249 QualType ASTContext::getDecayedType(QualType T) const {
2250 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2255 // A declaration of a parameter as "array of type" shall be
2256 // adjusted to "qualified pointer to type", where the type
2257 // qualifiers (if any) are those specified within the [ and ] of
2258 // the array type derivation.
2259 if (T->isArrayType())
2260 Decayed = getArrayDecayedType(T);
2263 // A declaration of a parameter as "function returning type"
2264 // shall be adjusted to "pointer to function returning type", as
2266 if (T->isFunctionType())
2267 Decayed = getPointerType(T);
2269 llvm::FoldingSetNodeID ID;
2270 AdjustedType::Profile(ID, T, Decayed);
2271 void *InsertPos = nullptr;
2272 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2274 return QualType(AT, 0);
2276 QualType Canonical = getCanonicalType(Decayed);
2278 // Get the new insert position for the node we care about.
2279 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2280 assert(!AT && "Shouldn't be in the map!");
2282 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2283 Types.push_back(AT);
2284 AdjustedTypes.InsertNode(AT, InsertPos);
2285 return QualType(AT, 0);
2288 /// getBlockPointerType - Return the uniqued reference to the type for
2289 /// a pointer to the specified block.
2290 QualType ASTContext::getBlockPointerType(QualType T) const {
2291 assert(T->isFunctionType() && "block of function types only");
2292 // Unique pointers, to guarantee there is only one block of a particular
2294 llvm::FoldingSetNodeID ID;
2295 BlockPointerType::Profile(ID, T);
2297 void *InsertPos = nullptr;
2298 if (BlockPointerType *PT =
2299 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2300 return QualType(PT, 0);
2302 // If the block pointee type isn't canonical, this won't be a canonical
2303 // type either so fill in the canonical type field.
2305 if (!T.isCanonical()) {
2306 Canonical = getBlockPointerType(getCanonicalType(T));
2308 // Get the new insert position for the node we care about.
2309 BlockPointerType *NewIP =
2310 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2311 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2313 BlockPointerType *New
2314 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2315 Types.push_back(New);
2316 BlockPointerTypes.InsertNode(New, InsertPos);
2317 return QualType(New, 0);
2320 /// getLValueReferenceType - Return the uniqued reference to the type for an
2321 /// lvalue reference to the specified type.
2323 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2324 assert(getCanonicalType(T) != OverloadTy &&
2325 "Unresolved overloaded function type");
2327 // Unique pointers, to guarantee there is only one pointer of a particular
2329 llvm::FoldingSetNodeID ID;
2330 ReferenceType::Profile(ID, T, SpelledAsLValue);
2332 void *InsertPos = nullptr;
2333 if (LValueReferenceType *RT =
2334 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2335 return QualType(RT, 0);
2337 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2339 // If the referencee type isn't canonical, this won't be a canonical type
2340 // either, so fill in the canonical type field.
2342 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2343 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2344 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2346 // Get the new insert position for the node we care about.
2347 LValueReferenceType *NewIP =
2348 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2349 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2352 LValueReferenceType *New
2353 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2355 Types.push_back(New);
2356 LValueReferenceTypes.InsertNode(New, InsertPos);
2358 return QualType(New, 0);
2361 /// getRValueReferenceType - Return the uniqued reference to the type for an
2362 /// rvalue reference to the specified type.
2363 QualType ASTContext::getRValueReferenceType(QualType T) const {
2364 // Unique pointers, to guarantee there is only one pointer of a particular
2366 llvm::FoldingSetNodeID ID;
2367 ReferenceType::Profile(ID, T, false);
2369 void *InsertPos = nullptr;
2370 if (RValueReferenceType *RT =
2371 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2372 return QualType(RT, 0);
2374 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2376 // If the referencee type isn't canonical, this won't be a canonical type
2377 // either, so fill in the canonical type field.
2379 if (InnerRef || !T.isCanonical()) {
2380 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2381 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2383 // Get the new insert position for the node we care about.
2384 RValueReferenceType *NewIP =
2385 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2386 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2389 RValueReferenceType *New
2390 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2391 Types.push_back(New);
2392 RValueReferenceTypes.InsertNode(New, InsertPos);
2393 return QualType(New, 0);
2396 /// getMemberPointerType - Return the uniqued reference to the type for a
2397 /// member pointer to the specified type, in the specified class.
2398 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2399 // Unique pointers, to guarantee there is only one pointer of a particular
2401 llvm::FoldingSetNodeID ID;
2402 MemberPointerType::Profile(ID, T, Cls);
2404 void *InsertPos = nullptr;
2405 if (MemberPointerType *PT =
2406 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2407 return QualType(PT, 0);
2409 // If the pointee or class type isn't canonical, this won't be a canonical
2410 // type either, so fill in the canonical type field.
2412 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2413 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2415 // Get the new insert position for the node we care about.
2416 MemberPointerType *NewIP =
2417 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2418 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2420 MemberPointerType *New
2421 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2422 Types.push_back(New);
2423 MemberPointerTypes.InsertNode(New, InsertPos);
2424 return QualType(New, 0);
2427 /// getConstantArrayType - Return the unique reference to the type for an
2428 /// array of the specified element type.
2429 QualType ASTContext::getConstantArrayType(QualType EltTy,
2430 const llvm::APInt &ArySizeIn,
2431 ArrayType::ArraySizeModifier ASM,
2432 unsigned IndexTypeQuals) const {
2433 assert((EltTy->isDependentType() ||
2434 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2435 "Constant array of VLAs is illegal!");
2437 // Convert the array size into a canonical width matching the pointer size for
2439 llvm::APInt ArySize(ArySizeIn);
2441 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2443 llvm::FoldingSetNodeID ID;
2444 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2446 void *InsertPos = nullptr;
2447 if (ConstantArrayType *ATP =
2448 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2449 return QualType(ATP, 0);
2451 // If the element type isn't canonical or has qualifiers, this won't
2452 // be a canonical type either, so fill in the canonical type field.
2454 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2455 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2456 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2457 ASM, IndexTypeQuals);
2458 Canon = getQualifiedType(Canon, canonSplit.Quals);
2460 // Get the new insert position for the node we care about.
2461 ConstantArrayType *NewIP =
2462 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2463 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2466 ConstantArrayType *New = new(*this,TypeAlignment)
2467 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2468 ConstantArrayTypes.InsertNode(New, InsertPos);
2469 Types.push_back(New);
2470 return QualType(New, 0);
2473 /// getVariableArrayDecayedType - Turns the given type, which may be
2474 /// variably-modified, into the corresponding type with all the known
2475 /// sizes replaced with [*].
2476 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2477 // Vastly most common case.
2478 if (!type->isVariablyModifiedType()) return type;
2482 SplitQualType split = type.getSplitDesugaredType();
2483 const Type *ty = split.Ty;
2484 switch (ty->getTypeClass()) {
2485 #define TYPE(Class, Base)
2486 #define ABSTRACT_TYPE(Class, Base)
2487 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2488 #include "clang/AST/TypeNodes.def"
2489 llvm_unreachable("didn't desugar past all non-canonical types?");
2491 // These types should never be variably-modified.
2495 case Type::ExtVector:
2496 case Type::DependentSizedExtVector:
2497 case Type::ObjCObject:
2498 case Type::ObjCInterface:
2499 case Type::ObjCObjectPointer:
2502 case Type::UnresolvedUsing:
2503 case Type::TypeOfExpr:
2505 case Type::Decltype:
2506 case Type::UnaryTransform:
2507 case Type::DependentName:
2508 case Type::InjectedClassName:
2509 case Type::TemplateSpecialization:
2510 case Type::DependentTemplateSpecialization:
2511 case Type::TemplateTypeParm:
2512 case Type::SubstTemplateTypeParmPack:
2514 case Type::PackExpansion:
2515 llvm_unreachable("type should never be variably-modified");
2517 // These types can be variably-modified but should never need to
2519 case Type::FunctionNoProto:
2520 case Type::FunctionProto:
2521 case Type::BlockPointer:
2522 case Type::MemberPointer:
2525 // These types can be variably-modified. All these modifications
2526 // preserve structure except as noted by comments.
2527 // TODO: if we ever care about optimizing VLAs, there are no-op
2528 // optimizations available here.
2530 result = getPointerType(getVariableArrayDecayedType(
2531 cast<PointerType>(ty)->getPointeeType()));
2534 case Type::LValueReference: {
2535 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2536 result = getLValueReferenceType(
2537 getVariableArrayDecayedType(lv->getPointeeType()),
2538 lv->isSpelledAsLValue());
2542 case Type::RValueReference: {
2543 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2544 result = getRValueReferenceType(
2545 getVariableArrayDecayedType(lv->getPointeeType()));
2549 case Type::Atomic: {
2550 const AtomicType *at = cast<AtomicType>(ty);
2551 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2555 case Type::ConstantArray: {
2556 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2557 result = getConstantArrayType(
2558 getVariableArrayDecayedType(cat->getElementType()),
2560 cat->getSizeModifier(),
2561 cat->getIndexTypeCVRQualifiers());
2565 case Type::DependentSizedArray: {
2566 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2567 result = getDependentSizedArrayType(
2568 getVariableArrayDecayedType(dat->getElementType()),
2570 dat->getSizeModifier(),
2571 dat->getIndexTypeCVRQualifiers(),
2572 dat->getBracketsRange());
2576 // Turn incomplete types into [*] types.
2577 case Type::IncompleteArray: {
2578 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2579 result = getVariableArrayType(
2580 getVariableArrayDecayedType(iat->getElementType()),
2583 iat->getIndexTypeCVRQualifiers(),
2588 // Turn VLA types into [*] types.
2589 case Type::VariableArray: {
2590 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2591 result = getVariableArrayType(
2592 getVariableArrayDecayedType(vat->getElementType()),
2595 vat->getIndexTypeCVRQualifiers(),
2596 vat->getBracketsRange());
2601 // Apply the top-level qualifiers from the original.
2602 return getQualifiedType(result, split.Quals);
2605 /// getVariableArrayType - Returns a non-unique reference to the type for a
2606 /// variable array of the specified element type.
2607 QualType ASTContext::getVariableArrayType(QualType EltTy,
2609 ArrayType::ArraySizeModifier ASM,
2610 unsigned IndexTypeQuals,
2611 SourceRange Brackets) const {
2612 // Since we don't unique expressions, it isn't possible to unique VLA's
2613 // that have an expression provided for their size.
2616 // Be sure to pull qualifiers off the element type.
2617 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2618 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2619 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2620 IndexTypeQuals, Brackets);
2621 Canon = getQualifiedType(Canon, canonSplit.Quals);
2624 VariableArrayType *New = new(*this, TypeAlignment)
2625 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2627 VariableArrayTypes.push_back(New);
2628 Types.push_back(New);
2629 return QualType(New, 0);
2632 /// getDependentSizedArrayType - Returns a non-unique reference to
2633 /// the type for a dependently-sized array of the specified element
2635 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2637 ArrayType::ArraySizeModifier ASM,
2638 unsigned elementTypeQuals,
2639 SourceRange brackets) const {
2640 assert((!numElements || numElements->isTypeDependent() ||
2641 numElements->isValueDependent()) &&
2642 "Size must be type- or value-dependent!");
2644 // Dependently-sized array types that do not have a specified number
2645 // of elements will have their sizes deduced from a dependent
2646 // initializer. We do no canonicalization here at all, which is okay
2647 // because they can't be used in most locations.
2649 DependentSizedArrayType *newType
2650 = new (*this, TypeAlignment)
2651 DependentSizedArrayType(*this, elementType, QualType(),
2652 numElements, ASM, elementTypeQuals,
2654 Types.push_back(newType);
2655 return QualType(newType, 0);
2658 // Otherwise, we actually build a new type every time, but we
2659 // also build a canonical type.
2661 SplitQualType canonElementType = getCanonicalType(elementType).split();
2663 void *insertPos = nullptr;
2664 llvm::FoldingSetNodeID ID;
2665 DependentSizedArrayType::Profile(ID, *this,
2666 QualType(canonElementType.Ty, 0),
2667 ASM, elementTypeQuals, numElements);
2669 // Look for an existing type with these properties.
2670 DependentSizedArrayType *canonTy =
2671 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2673 // If we don't have one, build one.
2675 canonTy = new (*this, TypeAlignment)
2676 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2677 QualType(), numElements, ASM, elementTypeQuals,
2679 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2680 Types.push_back(canonTy);
2683 // Apply qualifiers from the element type to the array.
2684 QualType canon = getQualifiedType(QualType(canonTy,0),
2685 canonElementType.Quals);
2687 // If we didn't need extra canonicalization for the element type,
2688 // then just use that as our result.
2689 if (QualType(canonElementType.Ty, 0) == elementType)
2692 // Otherwise, we need to build a type which follows the spelling
2693 // of the element type.
2694 DependentSizedArrayType *sugaredType
2695 = new (*this, TypeAlignment)
2696 DependentSizedArrayType(*this, elementType, canon, numElements,
2697 ASM, elementTypeQuals, brackets);
2698 Types.push_back(sugaredType);
2699 return QualType(sugaredType, 0);
2702 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2703 ArrayType::ArraySizeModifier ASM,
2704 unsigned elementTypeQuals) const {
2705 llvm::FoldingSetNodeID ID;
2706 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2708 void *insertPos = nullptr;
2709 if (IncompleteArrayType *iat =
2710 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2711 return QualType(iat, 0);
2713 // If the element type isn't canonical, this won't be a canonical type
2714 // either, so fill in the canonical type field. We also have to pull
2715 // qualifiers off the element type.
2718 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2719 SplitQualType canonSplit = getCanonicalType(elementType).split();
2720 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2721 ASM, elementTypeQuals);
2722 canon = getQualifiedType(canon, canonSplit.Quals);
2724 // Get the new insert position for the node we care about.
2725 IncompleteArrayType *existing =
2726 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2727 assert(!existing && "Shouldn't be in the map!"); (void) existing;
2730 IncompleteArrayType *newType = new (*this, TypeAlignment)
2731 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2733 IncompleteArrayTypes.InsertNode(newType, insertPos);
2734 Types.push_back(newType);
2735 return QualType(newType, 0);
2738 /// getVectorType - Return the unique reference to a vector type of
2739 /// the specified element type and size. VectorType must be a built-in type.
2740 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2741 VectorType::VectorKind VecKind) const {
2742 assert(vecType->isBuiltinType());
2744 // Check if we've already instantiated a vector of this type.
2745 llvm::FoldingSetNodeID ID;
2746 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2748 void *InsertPos = nullptr;
2749 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2750 return QualType(VTP, 0);
2752 // If the element type isn't canonical, this won't be a canonical type either,
2753 // so fill in the canonical type field.
2755 if (!vecType.isCanonical()) {
2756 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2758 // Get the new insert position for the node we care about.
2759 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2760 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2762 VectorType *New = new (*this, TypeAlignment)
2763 VectorType(vecType, NumElts, Canonical, VecKind);
2764 VectorTypes.InsertNode(New, InsertPos);
2765 Types.push_back(New);
2766 return QualType(New, 0);
2769 /// getExtVectorType - Return the unique reference to an extended vector type of
2770 /// the specified element type and size. VectorType must be a built-in type.
2772 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2773 assert(vecType->isBuiltinType() || vecType->isDependentType());
2775 // Check if we've already instantiated a vector of this type.
2776 llvm::FoldingSetNodeID ID;
2777 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2778 VectorType::GenericVector);
2779 void *InsertPos = nullptr;
2780 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2781 return QualType(VTP, 0);
2783 // If the element type isn't canonical, this won't be a canonical type either,
2784 // so fill in the canonical type field.
2786 if (!vecType.isCanonical()) {
2787 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2789 // Get the new insert position for the node we care about.
2790 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2791 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2793 ExtVectorType *New = new (*this, TypeAlignment)
2794 ExtVectorType(vecType, NumElts, Canonical);
2795 VectorTypes.InsertNode(New, InsertPos);
2796 Types.push_back(New);
2797 return QualType(New, 0);
2801 ASTContext::getDependentSizedExtVectorType(QualType vecType,
2803 SourceLocation AttrLoc) const {
2804 llvm::FoldingSetNodeID ID;
2805 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2808 void *InsertPos = nullptr;
2809 DependentSizedExtVectorType *Canon
2810 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2811 DependentSizedExtVectorType *New;
2813 // We already have a canonical version of this array type; use it as
2814 // the canonical type for a newly-built type.
2815 New = new (*this, TypeAlignment)
2816 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2819 QualType CanonVecTy = getCanonicalType(vecType);
2820 if (CanonVecTy == vecType) {
2821 New = new (*this, TypeAlignment)
2822 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2825 DependentSizedExtVectorType *CanonCheck
2826 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2827 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2829 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2831 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2833 New = new (*this, TypeAlignment)
2834 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2838 Types.push_back(New);
2839 return QualType(New, 0);
2842 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2845 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2846 const FunctionType::ExtInfo &Info) const {
2847 const CallingConv CallConv = Info.getCC();
2849 // Unique functions, to guarantee there is only one function of a particular
2851 llvm::FoldingSetNodeID ID;
2852 FunctionNoProtoType::Profile(ID, ResultTy, Info);
2854 void *InsertPos = nullptr;
2855 if (FunctionNoProtoType *FT =
2856 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2857 return QualType(FT, 0);
2860 if (!ResultTy.isCanonical()) {
2861 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
2863 // Get the new insert position for the node we care about.
2864 FunctionNoProtoType *NewIP =
2865 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2866 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2869 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
2870 FunctionNoProtoType *New = new (*this, TypeAlignment)
2871 FunctionNoProtoType(ResultTy, Canonical, newInfo);
2872 Types.push_back(New);
2873 FunctionNoProtoTypes.InsertNode(New, InsertPos);
2874 return QualType(New, 0);
2877 /// \brief Determine whether \p T is canonical as the result type of a function.
2878 static bool isCanonicalResultType(QualType T) {
2879 return T.isCanonical() &&
2880 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2881 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2885 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
2886 const FunctionProtoType::ExtProtoInfo &EPI) const {
2887 size_t NumArgs = ArgArray.size();
2889 // Unique functions, to guarantee there is only one function of a particular
2891 llvm::FoldingSetNodeID ID;
2892 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2895 void *InsertPos = nullptr;
2896 if (FunctionProtoType *FTP =
2897 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2898 return QualType(FTP, 0);
2900 // Determine whether the type being created is already canonical or not.
2902 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
2903 !EPI.HasTrailingReturn;
2904 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2905 if (!ArgArray[i].isCanonicalAsParam())
2906 isCanonical = false;
2908 // If this type isn't canonical, get the canonical version of it.
2909 // The exception spec is not part of the canonical type.
2912 SmallVector<QualType, 16> CanonicalArgs;
2913 CanonicalArgs.reserve(NumArgs);
2914 for (unsigned i = 0; i != NumArgs; ++i)
2915 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2917 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2918 CanonicalEPI.HasTrailingReturn = false;
2919 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
2921 // Result types do not have ARC lifetime qualifiers.
2922 QualType CanResultTy = getCanonicalType(ResultTy);
2923 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2924 Qualifiers Qs = CanResultTy.getQualifiers();
2925 Qs.removeObjCLifetime();
2926 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2929 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
2931 // Get the new insert position for the node we care about.
2932 FunctionProtoType *NewIP =
2933 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2934 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2937 // FunctionProtoType objects are allocated with extra bytes after
2938 // them for three variable size arrays at the end:
2939 // - parameter types
2940 // - exception types
2941 // - consumed-arguments flags
2942 // Instead of the exception types, there could be a noexcept
2943 // expression, or information used to resolve the exception
2945 size_t Size = sizeof(FunctionProtoType) +
2946 NumArgs * sizeof(QualType);
2947 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
2948 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
2949 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
2950 Size += sizeof(Expr*);
2951 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
2952 Size += 2 * sizeof(FunctionDecl*);
2953 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
2954 Size += sizeof(FunctionDecl*);
2956 if (EPI.ConsumedParameters)
2957 Size += NumArgs * sizeof(bool);
2959 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2960 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2961 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
2962 Types.push_back(FTP);
2963 FunctionProtoTypes.InsertNode(FTP, InsertPos);
2964 return QualType(FTP, 0);
2968 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2969 if (!isa<CXXRecordDecl>(D)) return false;
2970 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2971 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2973 if (RD->getDescribedClassTemplate() &&
2974 !isa<ClassTemplateSpecializationDecl>(RD))
2980 /// getInjectedClassNameType - Return the unique reference to the
2981 /// injected class name type for the specified templated declaration.
2982 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2983 QualType TST) const {
2984 assert(NeedsInjectedClassNameType(Decl));
2985 if (Decl->TypeForDecl) {
2986 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2987 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
2988 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2989 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2990 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2993 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2994 Decl->TypeForDecl = newType;
2995 Types.push_back(newType);
2997 return QualType(Decl->TypeForDecl, 0);
3000 /// getTypeDeclType - Return the unique reference to the type for the
3001 /// specified type declaration.
3002 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3003 assert(Decl && "Passed null for Decl param");
3004 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3006 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3007 return getTypedefType(Typedef);
3009 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3010 "Template type parameter types are always available.");
3012 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
3013 assert(Record->isFirstDecl() && "struct/union has previous declaration");
3014 assert(!NeedsInjectedClassNameType(Record));
3015 return getRecordType(Record);
3016 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
3017 assert(Enum->isFirstDecl() && "enum has previous declaration");
3018 return getEnumType(Enum);
3019 } else if (const UnresolvedUsingTypenameDecl *Using =
3020 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3021 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3022 Decl->TypeForDecl = newType;
3023 Types.push_back(newType);
3025 llvm_unreachable("TypeDecl without a type?");
3027 return QualType(Decl->TypeForDecl, 0);
3030 /// getTypedefType - Return the unique reference to the type for the
3031 /// specified typedef name decl.
3033 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3034 QualType Canonical) const {
3035 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3037 if (Canonical.isNull())
3038 Canonical = getCanonicalType(Decl->getUnderlyingType());
3039 TypedefType *newType = new(*this, TypeAlignment)
3040 TypedefType(Type::Typedef, Decl, Canonical);
3041 Decl->TypeForDecl = newType;
3042 Types.push_back(newType);
3043 return QualType(newType, 0);
3046 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
3047 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3049 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3050 if (PrevDecl->TypeForDecl)
3051 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3053 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3054 Decl->TypeForDecl = newType;
3055 Types.push_back(newType);
3056 return QualType(newType, 0);
3059 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3060 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3062 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3063 if (PrevDecl->TypeForDecl)
3064 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3066 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3067 Decl->TypeForDecl = newType;
3068 Types.push_back(newType);
3069 return QualType(newType, 0);
3072 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3073 QualType modifiedType,
3074 QualType equivalentType) {
3075 llvm::FoldingSetNodeID id;
3076 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3078 void *insertPos = nullptr;
3079 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3080 if (type) return QualType(type, 0);
3082 QualType canon = getCanonicalType(equivalentType);
3083 type = new (*this, TypeAlignment)
3084 AttributedType(canon, attrKind, modifiedType, equivalentType);
3086 Types.push_back(type);
3087 AttributedTypes.InsertNode(type, insertPos);
3089 return QualType(type, 0);
3093 /// \brief Retrieve a substitution-result type.
3095 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3096 QualType Replacement) const {
3097 assert(Replacement.isCanonical()
3098 && "replacement types must always be canonical");
3100 llvm::FoldingSetNodeID ID;
3101 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3102 void *InsertPos = nullptr;
3103 SubstTemplateTypeParmType *SubstParm
3104 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3107 SubstParm = new (*this, TypeAlignment)
3108 SubstTemplateTypeParmType(Parm, Replacement);
3109 Types.push_back(SubstParm);
3110 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3113 return QualType(SubstParm, 0);
3116 /// \brief Retrieve a
3117 QualType ASTContext::getSubstTemplateTypeParmPackType(
3118 const TemplateTypeParmType *Parm,
3119 const TemplateArgument &ArgPack) {
3121 for (const auto &P : ArgPack.pack_elements()) {
3122 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3123 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
3127 llvm::FoldingSetNodeID ID;
3128 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3129 void *InsertPos = nullptr;
3130 if (SubstTemplateTypeParmPackType *SubstParm
3131 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3132 return QualType(SubstParm, 0);
3135 if (!Parm->isCanonicalUnqualified()) {
3136 Canon = getCanonicalType(QualType(Parm, 0));
3137 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3139 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3142 SubstTemplateTypeParmPackType *SubstParm
3143 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3145 Types.push_back(SubstParm);
3146 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3147 return QualType(SubstParm, 0);
3150 /// \brief Retrieve the template type parameter type for a template
3151 /// parameter or parameter pack with the given depth, index, and (optionally)
3153 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3155 TemplateTypeParmDecl *TTPDecl) const {
3156 llvm::FoldingSetNodeID ID;
3157 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3158 void *InsertPos = nullptr;
3159 TemplateTypeParmType *TypeParm
3160 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3163 return QualType(TypeParm, 0);
3166 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3167 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3169 TemplateTypeParmType *TypeCheck
3170 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3171 assert(!TypeCheck && "Template type parameter canonical type broken");
3174 TypeParm = new (*this, TypeAlignment)
3175 TemplateTypeParmType(Depth, Index, ParameterPack);
3177 Types.push_back(TypeParm);
3178 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3180 return QualType(TypeParm, 0);
3184 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3185 SourceLocation NameLoc,
3186 const TemplateArgumentListInfo &Args,
3187 QualType Underlying) const {
3188 assert(!Name.getAsDependentTemplateName() &&
3189 "No dependent template names here!");
3190 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3192 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3193 TemplateSpecializationTypeLoc TL =
3194 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3195 TL.setTemplateKeywordLoc(SourceLocation());
3196 TL.setTemplateNameLoc(NameLoc);
3197 TL.setLAngleLoc(Args.getLAngleLoc());
3198 TL.setRAngleLoc(Args.getRAngleLoc());
3199 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3200 TL.setArgLocInfo(i, Args[i].getLocInfo());
3205 ASTContext::getTemplateSpecializationType(TemplateName Template,
3206 const TemplateArgumentListInfo &Args,
3207 QualType Underlying) const {
3208 assert(!Template.getAsDependentTemplateName() &&
3209 "No dependent template names here!");
3211 unsigned NumArgs = Args.size();
3213 SmallVector<TemplateArgument, 4> ArgVec;
3214 ArgVec.reserve(NumArgs);
3215 for (unsigned i = 0; i != NumArgs; ++i)
3216 ArgVec.push_back(Args[i].getArgument());
3218 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
3223 static bool hasAnyPackExpansions(const TemplateArgument *Args,
3225 for (unsigned I = 0; I != NumArgs; ++I)
3226 if (Args[I].isPackExpansion())
3234 ASTContext::getTemplateSpecializationType(TemplateName Template,
3235 const TemplateArgument *Args,
3237 QualType Underlying) const {
3238 assert(!Template.getAsDependentTemplateName() &&
3239 "No dependent template names here!");
3240 // Look through qualified template names.
3241 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3242 Template = TemplateName(QTN->getTemplateDecl());
3245 Template.getAsTemplateDecl() &&
3246 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3248 if (!Underlying.isNull())
3249 CanonType = getCanonicalType(Underlying);
3251 // We can get here with an alias template when the specialization contains
3252 // a pack expansion that does not match up with a parameter pack.
3253 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3254 "Caller must compute aliased type");
3255 IsTypeAlias = false;
3256 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3260 // Allocate the (non-canonical) template specialization type, but don't
3261 // try to unique it: these types typically have location information that
3262 // we don't unique and don't want to lose.
3263 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3264 sizeof(TemplateArgument) * NumArgs +
3265 (IsTypeAlias? sizeof(QualType) : 0),
3267 TemplateSpecializationType *Spec
3268 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3269 IsTypeAlias ? Underlying : QualType());
3271 Types.push_back(Spec);
3272 return QualType(Spec, 0);
3276 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3277 const TemplateArgument *Args,
3278 unsigned NumArgs) const {
3279 assert(!Template.getAsDependentTemplateName() &&
3280 "No dependent template names here!");
3282 // Look through qualified template names.
3283 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3284 Template = TemplateName(QTN->getTemplateDecl());
3286 // Build the canonical template specialization type.
3287 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3288 SmallVector<TemplateArgument, 4> CanonArgs;
3289 CanonArgs.reserve(NumArgs);
3290 for (unsigned I = 0; I != NumArgs; ++I)
3291 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3293 // Determine whether this canonical template specialization type already
3295 llvm::FoldingSetNodeID ID;
3296 TemplateSpecializationType::Profile(ID, CanonTemplate,
3297 CanonArgs.data(), NumArgs, *this);
3299 void *InsertPos = nullptr;
3300 TemplateSpecializationType *Spec
3301 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3304 // Allocate a new canonical template specialization type.
3305 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3306 sizeof(TemplateArgument) * NumArgs),
3308 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3309 CanonArgs.data(), NumArgs,
3310 QualType(), QualType());
3311 Types.push_back(Spec);
3312 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3315 assert(Spec->isDependentType() &&
3316 "Non-dependent template-id type must have a canonical type");
3317 return QualType(Spec, 0);
3321 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3322 NestedNameSpecifier *NNS,
3323 QualType NamedType) const {
3324 llvm::FoldingSetNodeID ID;
3325 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3327 void *InsertPos = nullptr;
3328 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3330 return QualType(T, 0);
3332 QualType Canon = NamedType;
3333 if (!Canon.isCanonical()) {
3334 Canon = getCanonicalType(NamedType);
3335 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3336 assert(!CheckT && "Elaborated canonical type broken");
3340 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
3342 ElaboratedTypes.InsertNode(T, InsertPos);
3343 return QualType(T, 0);
3347 ASTContext::getParenType(QualType InnerType) const {
3348 llvm::FoldingSetNodeID ID;
3349 ParenType::Profile(ID, InnerType);
3351 void *InsertPos = nullptr;
3352 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3354 return QualType(T, 0);
3356 QualType Canon = InnerType;
3357 if (!Canon.isCanonical()) {
3358 Canon = getCanonicalType(InnerType);
3359 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3360 assert(!CheckT && "Paren canonical type broken");
3364 T = new (*this) ParenType(InnerType, Canon);
3366 ParenTypes.InsertNode(T, InsertPos);
3367 return QualType(T, 0);
3370 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3371 NestedNameSpecifier *NNS,
3372 const IdentifierInfo *Name,
3373 QualType Canon) const {
3374 if (Canon.isNull()) {
3375 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3376 ElaboratedTypeKeyword CanonKeyword = Keyword;
3377 if (Keyword == ETK_None)
3378 CanonKeyword = ETK_Typename;
3380 if (CanonNNS != NNS || CanonKeyword != Keyword)
3381 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3384 llvm::FoldingSetNodeID ID;
3385 DependentNameType::Profile(ID, Keyword, NNS, Name);
3387 void *InsertPos = nullptr;
3388 DependentNameType *T
3389 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3391 return QualType(T, 0);
3393 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
3395 DependentNameTypes.InsertNode(T, InsertPos);
3396 return QualType(T, 0);
3400 ASTContext::getDependentTemplateSpecializationType(
3401 ElaboratedTypeKeyword Keyword,
3402 NestedNameSpecifier *NNS,
3403 const IdentifierInfo *Name,
3404 const TemplateArgumentListInfo &Args) const {
3405 // TODO: avoid this copy
3406 SmallVector<TemplateArgument, 16> ArgCopy;
3407 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3408 ArgCopy.push_back(Args[I].getArgument());
3409 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3415 ASTContext::getDependentTemplateSpecializationType(
3416 ElaboratedTypeKeyword Keyword,
3417 NestedNameSpecifier *NNS,
3418 const IdentifierInfo *Name,
3420 const TemplateArgument *Args) const {
3421 assert((!NNS || NNS->isDependent()) &&
3422 "nested-name-specifier must be dependent");
3424 llvm::FoldingSetNodeID ID;
3425 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3426 Name, NumArgs, Args);
3428 void *InsertPos = nullptr;
3429 DependentTemplateSpecializationType *T
3430 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3432 return QualType(T, 0);
3434 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3436 ElaboratedTypeKeyword CanonKeyword = Keyword;
3437 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3439 bool AnyNonCanonArgs = false;
3440 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3441 for (unsigned I = 0; I != NumArgs; ++I) {
3442 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3443 if (!CanonArgs[I].structurallyEquals(Args[I]))
3444 AnyNonCanonArgs = true;
3448 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3449 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3453 // Find the insert position again.
3454 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3457 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3458 sizeof(TemplateArgument) * NumArgs),
3460 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3461 Name, NumArgs, Args, Canon);
3463 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3464 return QualType(T, 0);
3467 QualType ASTContext::getPackExpansionType(QualType Pattern,
3468 Optional<unsigned> NumExpansions) {
3469 llvm::FoldingSetNodeID ID;
3470 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3472 assert(Pattern->containsUnexpandedParameterPack() &&
3473 "Pack expansions must expand one or more parameter packs");
3474 void *InsertPos = nullptr;
3475 PackExpansionType *T
3476 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3478 return QualType(T, 0);
3481 if (!Pattern.isCanonical()) {
3482 Canon = getCanonicalType(Pattern);
3483 // The canonical type might not contain an unexpanded parameter pack, if it
3484 // contains an alias template specialization which ignores one of its
3486 if (Canon->containsUnexpandedParameterPack()) {
3487 Canon = getPackExpansionType(Canon, NumExpansions);
3489 // Find the insert position again, in case we inserted an element into
3490 // PackExpansionTypes and invalidated our insert position.
3491 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3495 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
3497 PackExpansionTypes.InsertNode(T, InsertPos);
3498 return QualType(T, 0);
3501 /// CmpProtocolNames - Comparison predicate for sorting protocols
3503 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3504 const ObjCProtocolDecl *RHS) {
3505 return LHS->getDeclName() < RHS->getDeclName();
3508 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
3509 unsigned NumProtocols) {
3510 if (NumProtocols == 0) return true;
3512 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3515 for (unsigned i = 1; i != NumProtocols; ++i)
3516 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3517 Protocols[i]->getCanonicalDecl() != Protocols[i])
3522 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
3523 unsigned &NumProtocols) {
3524 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
3526 // Sort protocols, keyed by name.
3527 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3530 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3531 Protocols[I] = Protocols[I]->getCanonicalDecl();
3533 // Remove duplicates.
3534 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3535 NumProtocols = ProtocolsEnd-Protocols;
3538 QualType ASTContext::getObjCObjectType(QualType BaseType,
3539 ObjCProtocolDecl * const *Protocols,
3540 unsigned NumProtocols) const {
3541 // If the base type is an interface and there aren't any protocols
3542 // to add, then the interface type will do just fine.
3543 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3546 // Look in the folding set for an existing type.
3547 llvm::FoldingSetNodeID ID;
3548 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
3549 void *InsertPos = nullptr;
3550 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3551 return QualType(QT, 0);
3553 // Build the canonical type, which has the canonical base type and
3554 // a sorted-and-uniqued list of protocols.
3556 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3557 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3558 if (!ProtocolsSorted) {
3559 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
3560 Protocols + NumProtocols);
3561 unsigned UniqueCount = NumProtocols;
3563 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
3564 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3565 &Sorted[0], UniqueCount);
3567 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3568 Protocols, NumProtocols);
3571 // Regenerate InsertPos.
3572 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3575 unsigned Size = sizeof(ObjCObjectTypeImpl);
3576 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3577 void *Mem = Allocate(Size, TypeAlignment);
3578 ObjCObjectTypeImpl *T =
3579 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3582 ObjCObjectTypes.InsertNode(T, InsertPos);
3583 return QualType(T, 0);
3586 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3587 /// protocol list adopt all protocols in QT's qualified-id protocol
3589 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3590 ObjCInterfaceDecl *IC) {
3591 if (!QT->isObjCQualifiedIdType())
3594 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3595 // If both the right and left sides have qualifiers.
3596 for (auto *Proto : OPT->quals()) {
3597 if (!IC->ClassImplementsProtocol(Proto, false))
3605 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3606 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
3608 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3609 ObjCInterfaceDecl *IDecl) {
3610 if (!QT->isObjCQualifiedIdType())
3612 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3615 if (!IDecl->hasDefinition())
3617 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3618 CollectInheritedProtocols(IDecl, InheritedProtocols);
3619 if (InheritedProtocols.empty())
3621 // Check that if every protocol in list of id<plist> conforms to a protcol
3622 // of IDecl's, then bridge casting is ok.
3623 bool Conforms = false;
3624 for (auto *Proto : OPT->quals()) {
3626 for (auto *PI : InheritedProtocols) {
3627 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3638 for (auto *PI : InheritedProtocols) {
3639 // If both the right and left sides have qualifiers.
3640 bool Adopts = false;
3641 for (auto *Proto : OPT->quals()) {
3642 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
3643 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
3652 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3653 /// the given object type.
3654 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
3655 llvm::FoldingSetNodeID ID;
3656 ObjCObjectPointerType::Profile(ID, ObjectT);
3658 void *InsertPos = nullptr;
3659 if (ObjCObjectPointerType *QT =
3660 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3661 return QualType(QT, 0);
3663 // Find the canonical object type.
3665 if (!ObjectT.isCanonical()) {
3666 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3668 // Regenerate InsertPos.
3669 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3673 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3674 ObjCObjectPointerType *QType =
3675 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
3677 Types.push_back(QType);
3678 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
3679 return QualType(QType, 0);
3682 /// getObjCInterfaceType - Return the unique reference to the type for the
3683 /// specified ObjC interface decl. The list of protocols is optional.
3684 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3685 ObjCInterfaceDecl *PrevDecl) const {
3686 if (Decl->TypeForDecl)
3687 return QualType(Decl->TypeForDecl, 0);
3690 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3691 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3692 return QualType(PrevDecl->TypeForDecl, 0);
3695 // Prefer the definition, if there is one.
3696 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3699 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3700 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3701 Decl->TypeForDecl = T;
3703 return QualType(T, 0);
3706 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3707 /// TypeOfExprType AST's (since expression's are never shared). For example,
3708 /// multiple declarations that refer to "typeof(x)" all contain different
3709 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
3710 /// on canonical type's (which are always unique).
3711 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
3712 TypeOfExprType *toe;
3713 if (tofExpr->isTypeDependent()) {
3714 llvm::FoldingSetNodeID ID;
3715 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3717 void *InsertPos = nullptr;
3718 DependentTypeOfExprType *Canon
3719 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3721 // We already have a "canonical" version of an identical, dependent
3722 // typeof(expr) type. Use that as our canonical type.
3723 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3724 QualType((TypeOfExprType*)Canon, 0));
3726 // Build a new, canonical typeof(expr) type.
3728 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3729 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3733 QualType Canonical = getCanonicalType(tofExpr->getType());
3734 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3736 Types.push_back(toe);
3737 return QualType(toe, 0);
3740 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3741 /// TypeOfType nodes. The only motivation to unique these nodes would be
3742 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3743 /// an issue. This doesn't affect the type checker, since it operates
3744 /// on canonical types (which are always unique).
3745 QualType ASTContext::getTypeOfType(QualType tofType) const {
3746 QualType Canonical = getCanonicalType(tofType);
3747 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3748 Types.push_back(tot);
3749 return QualType(tot, 0);
3753 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3754 /// nodes. This would never be helpful, since each such type has its own
3755 /// expression, and would not give a significant memory saving, since there
3756 /// is an Expr tree under each such type.
3757 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3760 // C++11 [temp.type]p2:
3761 // If an expression e involves a template parameter, decltype(e) denotes a
3762 // unique dependent type. Two such decltype-specifiers refer to the same
3763 // type only if their expressions are equivalent (14.5.6.1).
3764 if (e->isInstantiationDependent()) {
3765 llvm::FoldingSetNodeID ID;
3766 DependentDecltypeType::Profile(ID, *this, e);
3768 void *InsertPos = nullptr;
3769 DependentDecltypeType *Canon
3770 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3772 // Build a new, canonical typeof(expr) type.
3773 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3774 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3776 dt = new (*this, TypeAlignment)
3777 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
3779 dt = new (*this, TypeAlignment)
3780 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
3782 Types.push_back(dt);
3783 return QualType(dt, 0);
3786 /// getUnaryTransformationType - We don't unique these, since the memory
3787 /// savings are minimal and these are rare.
3788 QualType ASTContext::getUnaryTransformType(QualType BaseType,
3789 QualType UnderlyingType,
3790 UnaryTransformType::UTTKind Kind)
3792 UnaryTransformType *Ty =
3793 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3795 UnderlyingType->isDependentType() ?
3796 QualType() : getCanonicalType(UnderlyingType));
3797 Types.push_back(Ty);
3798 return QualType(Ty, 0);
3801 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
3802 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3803 /// canonical deduced-but-dependent 'auto' type.
3804 QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
3805 bool IsDependent) const {
3806 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3807 return getAutoDeductType();
3809 // Look in the folding set for an existing type.
3810 void *InsertPos = nullptr;
3811 llvm::FoldingSetNodeID ID;
3812 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3813 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3814 return QualType(AT, 0);
3816 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
3819 Types.push_back(AT);
3821 AutoTypes.InsertNode(AT, InsertPos);
3822 return QualType(AT, 0);
3825 /// getAtomicType - Return the uniqued reference to the atomic type for
3826 /// the given value type.
3827 QualType ASTContext::getAtomicType(QualType T) const {
3828 // Unique pointers, to guarantee there is only one pointer of a particular
3830 llvm::FoldingSetNodeID ID;
3831 AtomicType::Profile(ID, T);
3833 void *InsertPos = nullptr;
3834 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3835 return QualType(AT, 0);
3837 // If the atomic value type isn't canonical, this won't be a canonical type
3838 // either, so fill in the canonical type field.
3840 if (!T.isCanonical()) {
3841 Canonical = getAtomicType(getCanonicalType(T));
3843 // Get the new insert position for the node we care about.
3844 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3845 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3847 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3848 Types.push_back(New);
3849 AtomicTypes.InsertNode(New, InsertPos);
3850 return QualType(New, 0);
3853 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
3854 QualType ASTContext::getAutoDeductType() const {
3855 if (AutoDeductTy.isNull())
3856 AutoDeductTy = QualType(
3857 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3858 /*dependent*/false),
3860 return AutoDeductTy;
3863 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3864 QualType ASTContext::getAutoRRefDeductType() const {
3865 if (AutoRRefDeductTy.isNull())
3866 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3867 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3868 return AutoRRefDeductTy;
3871 /// getTagDeclType - Return the unique reference to the type for the
3872 /// specified TagDecl (struct/union/class/enum) decl.
3873 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
3875 // FIXME: What is the design on getTagDeclType when it requires casting
3876 // away const? mutable?
3877 return getTypeDeclType(const_cast<TagDecl*>(Decl));
3880 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3881 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3882 /// needs to agree with the definition in <stddef.h>.
3883 CanQualType ASTContext::getSizeType() const {
3884 return getFromTargetType(Target->getSizeType());
3887 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3888 CanQualType ASTContext::getIntMaxType() const {
3889 return getFromTargetType(Target->getIntMaxType());
3892 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3893 CanQualType ASTContext::getUIntMaxType() const {
3894 return getFromTargetType(Target->getUIntMaxType());
3897 /// getSignedWCharType - Return the type of "signed wchar_t".
3898 /// Used when in C++, as a GCC extension.
3899 QualType ASTContext::getSignedWCharType() const {
3900 // FIXME: derive from "Target" ?
3904 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3905 /// Used when in C++, as a GCC extension.
3906 QualType ASTContext::getUnsignedWCharType() const {
3907 // FIXME: derive from "Target" ?
3908 return UnsignedIntTy;
3911 QualType ASTContext::getIntPtrType() const {
3912 return getFromTargetType(Target->getIntPtrType());
3915 QualType ASTContext::getUIntPtrType() const {
3916 return getCorrespondingUnsignedType(getIntPtrType());
3919 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
3920 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3921 QualType ASTContext::getPointerDiffType() const {
3922 return getFromTargetType(Target->getPtrDiffType(0));
3925 /// \brief Return the unique type for "pid_t" defined in
3926 /// <sys/types.h>. We need this to compute the correct type for vfork().
3927 QualType ASTContext::getProcessIDType() const {
3928 return getFromTargetType(Target->getProcessIDType());
3931 //===----------------------------------------------------------------------===//
3933 //===----------------------------------------------------------------------===//
3935 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
3936 // Push qualifiers into arrays, and then discard any remaining
3938 T = getCanonicalType(T);
3939 T = getVariableArrayDecayedType(T);
3940 const Type *Ty = T.getTypePtr();
3942 if (isa<ArrayType>(Ty)) {
3943 Result = getArrayDecayedType(QualType(Ty,0));
3944 } else if (isa<FunctionType>(Ty)) {
3945 Result = getPointerType(QualType(Ty, 0));
3947 Result = QualType(Ty, 0);
3950 return CanQualType::CreateUnsafe(Result);
3953 QualType ASTContext::getUnqualifiedArrayType(QualType type,
3954 Qualifiers &quals) {
3955 SplitQualType splitType = type.getSplitUnqualifiedType();
3957 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3958 // the unqualified desugared type and then drops it on the floor.
3959 // We then have to strip that sugar back off with
3960 // getUnqualifiedDesugaredType(), which is silly.
3961 const ArrayType *AT =
3962 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
3964 // If we don't have an array, just use the results in splitType.
3966 quals = splitType.Quals;
3967 return QualType(splitType.Ty, 0);
3970 // Otherwise, recurse on the array's element type.
3971 QualType elementType = AT->getElementType();
3972 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3974 // If that didn't change the element type, AT has no qualifiers, so we
3975 // can just use the results in splitType.
3976 if (elementType == unqualElementType) {
3977 assert(quals.empty()); // from the recursive call
3978 quals = splitType.Quals;
3979 return QualType(splitType.Ty, 0);
3982 // Otherwise, add in the qualifiers from the outermost type, then
3983 // build the type back up.
3984 quals.addConsistentQualifiers(splitType.Quals);
3986 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3987 return getConstantArrayType(unqualElementType, CAT->getSize(),
3988 CAT->getSizeModifier(), 0);
3991 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
3992 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
3995 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
3996 return getVariableArrayType(unqualElementType,
3998 VAT->getSizeModifier(),
3999 VAT->getIndexTypeCVRQualifiers(),
4000 VAT->getBracketsRange());
4003 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
4004 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
4005 DSAT->getSizeModifier(), 0,
4009 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4010 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4011 /// they point to and return true. If T1 and T2 aren't pointer types
4012 /// or pointer-to-member types, or if they are not similar at this
4013 /// level, returns false and leaves T1 and T2 unchanged. Top-level
4014 /// qualifiers on T1 and T2 are ignored. This function will typically
4015 /// be called in a loop that successively "unwraps" pointer and
4016 /// pointer-to-member types to compare them at each level.
4017 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4018 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4019 *T2PtrType = T2->getAs<PointerType>();
4020 if (T1PtrType && T2PtrType) {
4021 T1 = T1PtrType->getPointeeType();
4022 T2 = T2PtrType->getPointeeType();
4026 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4027 *T2MPType = T2->getAs<MemberPointerType>();
4028 if (T1MPType && T2MPType &&
4029 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4030 QualType(T2MPType->getClass(), 0))) {
4031 T1 = T1MPType->getPointeeType();
4032 T2 = T2MPType->getPointeeType();
4036 if (getLangOpts().ObjC1) {
4037 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4038 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4039 if (T1OPType && T2OPType) {
4040 T1 = T1OPType->getPointeeType();
4041 T2 = T2OPType->getPointeeType();
4046 // FIXME: Block pointers, too?
4052 ASTContext::getNameForTemplate(TemplateName Name,
4053 SourceLocation NameLoc) const {
4054 switch (Name.getKind()) {
4055 case TemplateName::QualifiedTemplate:
4056 case TemplateName::Template:
4057 // DNInfo work in progress: CHECKME: what about DNLoc?
4058 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4061 case TemplateName::OverloadedTemplate: {
4062 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4063 // DNInfo work in progress: CHECKME: what about DNLoc?
4064 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4067 case TemplateName::DependentTemplate: {
4068 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4069 DeclarationName DName;
4070 if (DTN->isIdentifier()) {
4071 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4072 return DeclarationNameInfo(DName, NameLoc);
4074 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4075 // DNInfo work in progress: FIXME: source locations?
4076 DeclarationNameLoc DNLoc;
4077 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4078 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4079 return DeclarationNameInfo(DName, NameLoc, DNLoc);
4083 case TemplateName::SubstTemplateTemplateParm: {
4084 SubstTemplateTemplateParmStorage *subst
4085 = Name.getAsSubstTemplateTemplateParm();
4086 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4090 case TemplateName::SubstTemplateTemplateParmPack: {
4091 SubstTemplateTemplateParmPackStorage *subst
4092 = Name.getAsSubstTemplateTemplateParmPack();
4093 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4098 llvm_unreachable("bad template name kind!");
4101 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4102 switch (Name.getKind()) {
4103 case TemplateName::QualifiedTemplate:
4104 case TemplateName::Template: {
4105 TemplateDecl *Template = Name.getAsTemplateDecl();
4106 if (TemplateTemplateParmDecl *TTP
4107 = dyn_cast<TemplateTemplateParmDecl>(Template))
4108 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4110 // The canonical template name is the canonical template declaration.
4111 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4114 case TemplateName::OverloadedTemplate:
4115 llvm_unreachable("cannot canonicalize overloaded template");
4117 case TemplateName::DependentTemplate: {
4118 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4119 assert(DTN && "Non-dependent template names must refer to template decls.");
4120 return DTN->CanonicalTemplateName;
4123 case TemplateName::SubstTemplateTemplateParm: {
4124 SubstTemplateTemplateParmStorage *subst
4125 = Name.getAsSubstTemplateTemplateParm();
4126 return getCanonicalTemplateName(subst->getReplacement());
4129 case TemplateName::SubstTemplateTemplateParmPack: {
4130 SubstTemplateTemplateParmPackStorage *subst
4131 = Name.getAsSubstTemplateTemplateParmPack();
4132 TemplateTemplateParmDecl *canonParameter
4133 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4134 TemplateArgument canonArgPack
4135 = getCanonicalTemplateArgument(subst->getArgumentPack());
4136 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4140 llvm_unreachable("bad template name!");
4143 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4144 X = getCanonicalTemplateName(X);
4145 Y = getCanonicalTemplateName(Y);
4146 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4150 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4151 switch (Arg.getKind()) {
4152 case TemplateArgument::Null:
4155 case TemplateArgument::Expression:
4158 case TemplateArgument::Declaration: {
4159 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4160 return TemplateArgument(D, Arg.getParamTypeForDecl());
4163 case TemplateArgument::NullPtr:
4164 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4167 case TemplateArgument::Template:
4168 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4170 case TemplateArgument::TemplateExpansion:
4171 return TemplateArgument(getCanonicalTemplateName(
4172 Arg.getAsTemplateOrTemplatePattern()),
4173 Arg.getNumTemplateExpansions());
4175 case TemplateArgument::Integral:
4176 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4178 case TemplateArgument::Type:
4179 return TemplateArgument(getCanonicalType(Arg.getAsType()));
4181 case TemplateArgument::Pack: {
4182 if (Arg.pack_size() == 0)
4185 TemplateArgument *CanonArgs
4186 = new (*this) TemplateArgument[Arg.pack_size()];
4188 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4189 AEnd = Arg.pack_end();
4190 A != AEnd; (void)++A, ++Idx)
4191 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4193 return TemplateArgument(CanonArgs, Arg.pack_size());
4197 // Silence GCC warning
4198 llvm_unreachable("Unhandled template argument kind");
4201 NestedNameSpecifier *
4202 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4206 switch (NNS->getKind()) {
4207 case NestedNameSpecifier::Identifier:
4208 // Canonicalize the prefix but keep the identifier the same.
4209 return NestedNameSpecifier::Create(*this,
4210 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4211 NNS->getAsIdentifier());
4213 case NestedNameSpecifier::Namespace:
4214 // A namespace is canonical; build a nested-name-specifier with
4215 // this namespace and no prefix.
4216 return NestedNameSpecifier::Create(*this, nullptr,
4217 NNS->getAsNamespace()->getOriginalNamespace());
4219 case NestedNameSpecifier::NamespaceAlias:
4220 // A namespace is canonical; build a nested-name-specifier with
4221 // this namespace and no prefix.
4222 return NestedNameSpecifier::Create(*this, nullptr,
4223 NNS->getAsNamespaceAlias()->getNamespace()
4224 ->getOriginalNamespace());
4226 case NestedNameSpecifier::TypeSpec:
4227 case NestedNameSpecifier::TypeSpecWithTemplate: {
4228 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4230 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4231 // break it apart into its prefix and identifier, then reconsititute those
4232 // as the canonical nested-name-specifier. This is required to canonicalize
4233 // a dependent nested-name-specifier involving typedefs of dependent-name
4235 // typedef typename T::type T1;
4236 // typedef typename T1::type T2;
4237 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4238 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4239 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4241 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4242 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4244 return NestedNameSpecifier::Create(*this, nullptr, false,
4245 const_cast<Type *>(T.getTypePtr()));
4248 case NestedNameSpecifier::Global:
4249 case NestedNameSpecifier::Super:
4250 // The global specifier and __super specifer are canonical and unique.
4254 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4258 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4259 // Handle the non-qualified case efficiently.
4260 if (!T.hasLocalQualifiers()) {
4261 // Handle the common positive case fast.
4262 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4266 // Handle the common negative case fast.
4267 if (!isa<ArrayType>(T.getCanonicalType()))
4270 // Apply any qualifiers from the array type to the element type. This
4271 // implements C99 6.7.3p8: "If the specification of an array type includes
4272 // any type qualifiers, the element type is so qualified, not the array type."
4274 // If we get here, we either have type qualifiers on the type, or we have
4275 // sugar such as a typedef in the way. If we have type qualifiers on the type
4276 // we must propagate them down into the element type.
4278 SplitQualType split = T.getSplitDesugaredType();
4279 Qualifiers qs = split.Quals;
4281 // If we have a simple case, just return now.
4282 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4283 if (!ATy || qs.empty())
4286 // Otherwise, we have an array and we have qualifiers on it. Push the
4287 // qualifiers into the array element type and return a new array type.
4288 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4290 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4291 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4292 CAT->getSizeModifier(),
4293 CAT->getIndexTypeCVRQualifiers()));
4294 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4295 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4296 IAT->getSizeModifier(),
4297 IAT->getIndexTypeCVRQualifiers()));
4299 if (const DependentSizedArrayType *DSAT
4300 = dyn_cast<DependentSizedArrayType>(ATy))
4301 return cast<ArrayType>(
4302 getDependentSizedArrayType(NewEltTy,
4303 DSAT->getSizeExpr(),
4304 DSAT->getSizeModifier(),
4305 DSAT->getIndexTypeCVRQualifiers(),
4306 DSAT->getBracketsRange()));
4308 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4309 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4311 VAT->getSizeModifier(),
4312 VAT->getIndexTypeCVRQualifiers(),
4313 VAT->getBracketsRange()));
4316 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4317 if (T->isArrayType() || T->isFunctionType())
4318 return getDecayedType(T);
4322 QualType ASTContext::getSignatureParameterType(QualType T) const {
4323 T = getVariableArrayDecayedType(T);
4324 T = getAdjustedParameterType(T);
4325 return T.getUnqualifiedType();
4328 /// getArrayDecayedType - Return the properly qualified result of decaying the
4329 /// specified array type to a pointer. This operation is non-trivial when
4330 /// handling typedefs etc. The canonical type of "T" must be an array type,
4331 /// this returns a pointer to a properly qualified element of the array.
4333 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4334 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4335 // Get the element type with 'getAsArrayType' so that we don't lose any
4336 // typedefs in the element type of the array. This also handles propagation
4337 // of type qualifiers from the array type into the element type if present
4339 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4340 assert(PrettyArrayType && "Not an array type!");
4342 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4344 // int x[restrict 4] -> int *restrict
4345 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
4348 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4349 return getBaseElementType(array->getElementType());
4352 QualType ASTContext::getBaseElementType(QualType type) const {
4355 SplitQualType split = type.getSplitDesugaredType();
4356 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4359 type = array->getElementType();
4360 qs.addConsistentQualifiers(split.Quals);
4363 return getQualifiedType(type, qs);
4366 /// getConstantArrayElementCount - Returns number of constant array elements.
4368 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4369 uint64_t ElementCount = 1;
4371 ElementCount *= CA->getSize().getZExtValue();
4372 CA = dyn_cast_or_null<ConstantArrayType>(
4373 CA->getElementType()->getAsArrayTypeUnsafe());
4375 return ElementCount;
4378 /// getFloatingRank - Return a relative rank for floating point types.
4379 /// This routine will assert if passed a built-in type that isn't a float.
4380 static FloatingRank getFloatingRank(QualType T) {
4381 if (const ComplexType *CT = T->getAs<ComplexType>())
4382 return getFloatingRank(CT->getElementType());
4384 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4385 switch (T->getAs<BuiltinType>()->getKind()) {
4386 default: llvm_unreachable("getFloatingRank(): not a floating type");
4387 case BuiltinType::Half: return HalfRank;
4388 case BuiltinType::Float: return FloatRank;
4389 case BuiltinType::Double: return DoubleRank;
4390 case BuiltinType::LongDouble: return LongDoubleRank;
4394 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4395 /// point or a complex type (based on typeDomain/typeSize).
4396 /// 'typeDomain' is a real floating point or complex type.
4397 /// 'typeSize' is a real floating point or complex type.
4398 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4399 QualType Domain) const {
4400 FloatingRank EltRank = getFloatingRank(Size);
4401 if (Domain->isComplexType()) {
4403 case HalfRank: llvm_unreachable("Complex half is not supported");
4404 case FloatRank: return FloatComplexTy;
4405 case DoubleRank: return DoubleComplexTy;
4406 case LongDoubleRank: return LongDoubleComplexTy;
4410 assert(Domain->isRealFloatingType() && "Unknown domain!");
4412 case HalfRank: return HalfTy;
4413 case FloatRank: return FloatTy;
4414 case DoubleRank: return DoubleTy;
4415 case LongDoubleRank: return LongDoubleTy;
4417 llvm_unreachable("getFloatingRank(): illegal value for rank");
4420 /// getFloatingTypeOrder - Compare the rank of the two specified floating
4421 /// point types, ignoring the domain of the type (i.e. 'double' ==
4422 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
4423 /// LHS < RHS, return -1.
4424 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
4425 FloatingRank LHSR = getFloatingRank(LHS);
4426 FloatingRank RHSR = getFloatingRank(RHS);
4435 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4436 /// routine will assert if passed a built-in type that isn't an integer or enum,
4437 /// or if it is not canonicalized.
4438 unsigned ASTContext::getIntegerRank(const Type *T) const {
4439 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
4441 switch (cast<BuiltinType>(T)->getKind()) {
4442 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
4443 case BuiltinType::Bool:
4444 return 1 + (getIntWidth(BoolTy) << 3);
4445 case BuiltinType::Char_S:
4446 case BuiltinType::Char_U:
4447 case BuiltinType::SChar:
4448 case BuiltinType::UChar:
4449 return 2 + (getIntWidth(CharTy) << 3);
4450 case BuiltinType::Short:
4451 case BuiltinType::UShort:
4452 return 3 + (getIntWidth(ShortTy) << 3);
4453 case BuiltinType::Int:
4454 case BuiltinType::UInt:
4455 return 4 + (getIntWidth(IntTy) << 3);
4456 case BuiltinType::Long:
4457 case BuiltinType::ULong:
4458 return 5 + (getIntWidth(LongTy) << 3);
4459 case BuiltinType::LongLong:
4460 case BuiltinType::ULongLong:
4461 return 6 + (getIntWidth(LongLongTy) << 3);
4462 case BuiltinType::Int128:
4463 case BuiltinType::UInt128:
4464 return 7 + (getIntWidth(Int128Ty) << 3);
4468 /// \brief Whether this is a promotable bitfield reference according
4469 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4471 /// \returns the type this bit-field will promote to, or NULL if no
4472 /// promotion occurs.
4473 QualType ASTContext::isPromotableBitField(Expr *E) const {
4474 if (E->isTypeDependent() || E->isValueDependent())
4477 // FIXME: We should not do this unless E->refersToBitField() is true. This
4478 // matters in C where getSourceBitField() will find bit-fields for various
4479 // cases where the source expression is not a bit-field designator.
4481 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
4485 QualType FT = Field->getType();
4487 uint64_t BitWidth = Field->getBitWidthValue(*this);
4488 uint64_t IntSize = getTypeSize(IntTy);
4489 // C++ [conv.prom]p5:
4490 // A prvalue for an integral bit-field can be converted to a prvalue of type
4491 // int if int can represent all the values of the bit-field; otherwise, it
4492 // can be converted to unsigned int if unsigned int can represent all the
4493 // values of the bit-field. If the bit-field is larger yet, no integral
4494 // promotion applies to it.
4496 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4497 // If an int can represent all values of the original type (as restricted by
4498 // the width, for a bit-field), the value is converted to an int; otherwise,
4499 // it is converted to an unsigned int.
4501 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4502 // We perform that promotion here to match GCC and C++.
4503 if (BitWidth < IntSize)
4506 if (BitWidth == IntSize)
4507 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4509 // Types bigger than int are not subject to promotions, and therefore act
4510 // like the base type. GCC has some weird bugs in this area that we
4511 // deliberately do not follow (GCC follows a pre-standard resolution to
4512 // C's DR315 which treats bit-width as being part of the type, and this leaks
4513 // into their semantics in some cases).
4517 /// getPromotedIntegerType - Returns the type that Promotable will
4518 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4520 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
4521 assert(!Promotable.isNull());
4522 assert(Promotable->isPromotableIntegerType());
4523 if (const EnumType *ET = Promotable->getAs<EnumType>())
4524 return ET->getDecl()->getPromotionType();
4526 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4527 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4528 // (3.9.1) can be converted to a prvalue of the first of the following
4529 // types that can represent all the values of its underlying type:
4530 // int, unsigned int, long int, unsigned long int, long long int, or
4531 // unsigned long long int [...]
4532 // FIXME: Is there some better way to compute this?
4533 if (BT->getKind() == BuiltinType::WChar_S ||
4534 BT->getKind() == BuiltinType::WChar_U ||
4535 BT->getKind() == BuiltinType::Char16 ||
4536 BT->getKind() == BuiltinType::Char32) {
4537 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4538 uint64_t FromSize = getTypeSize(BT);
4539 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4540 LongLongTy, UnsignedLongLongTy };
4541 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4542 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4543 if (FromSize < ToSize ||
4544 (FromSize == ToSize &&
4545 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4546 return PromoteTypes[Idx];
4548 llvm_unreachable("char type should fit into long long");
4552 // At this point, we should have a signed or unsigned integer type.
4553 if (Promotable->isSignedIntegerType())
4555 uint64_t PromotableSize = getIntWidth(Promotable);
4556 uint64_t IntSize = getIntWidth(IntTy);
4557 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4558 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4561 /// \brief Recurses in pointer/array types until it finds an objc retainable
4562 /// type and returns its ownership.
4563 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4564 while (!T.isNull()) {
4565 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4566 return T.getObjCLifetime();
4567 if (T->isArrayType())
4568 T = getBaseElementType(T);
4569 else if (const PointerType *PT = T->getAs<PointerType>())
4570 T = PT->getPointeeType();
4571 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4572 T = RT->getPointeeType();
4577 return Qualifiers::OCL_None;
4580 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4581 // Incomplete enum types are not treated as integer types.
4582 // FIXME: In C++, enum types are never integer types.
4583 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4584 return ET->getDecl()->getIntegerType().getTypePtr();
4588 /// getIntegerTypeOrder - Returns the highest ranked integer type:
4589 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
4590 /// LHS < RHS, return -1.
4591 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
4592 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4593 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
4595 // Unwrap enums to their underlying type.
4596 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4597 LHSC = getIntegerTypeForEnum(ET);
4598 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4599 RHSC = getIntegerTypeForEnum(ET);
4601 if (LHSC == RHSC) return 0;
4603 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4604 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
4606 unsigned LHSRank = getIntegerRank(LHSC);
4607 unsigned RHSRank = getIntegerRank(RHSC);
4609 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4610 if (LHSRank == RHSRank) return 0;
4611 return LHSRank > RHSRank ? 1 : -1;
4614 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4616 // If the unsigned [LHS] type is larger, return it.
4617 if (LHSRank >= RHSRank)
4620 // If the signed type can represent all values of the unsigned type, it
4621 // wins. Because we are dealing with 2's complement and types that are
4622 // powers of two larger than each other, this is always safe.
4626 // If the unsigned [RHS] type is larger, return it.
4627 if (RHSRank >= LHSRank)
4630 // If the signed type can represent all values of the unsigned type, it
4631 // wins. Because we are dealing with 2's complement and types that are
4632 // powers of two larger than each other, this is always safe.
4636 // getCFConstantStringType - Return the type used for constant CFStrings.
4637 QualType ASTContext::getCFConstantStringType() const {
4638 if (!CFConstantStringTypeDecl) {
4639 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
4640 CFConstantStringTypeDecl->startDefinition();
4642 QualType FieldTypes[4];
4645 FieldTypes[0] = getPointerType(IntTy.withConst());
4647 FieldTypes[1] = IntTy;
4649 FieldTypes[2] = getPointerType(CharTy.withConst());
4651 FieldTypes[3] = LongTy;
4654 for (unsigned i = 0; i < 4; ++i) {
4655 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
4657 SourceLocation(), nullptr,
4658 FieldTypes[i], /*TInfo=*/nullptr,
4659 /*BitWidth=*/nullptr,
4662 Field->setAccess(AS_public);
4663 CFConstantStringTypeDecl->addDecl(Field);
4666 CFConstantStringTypeDecl->completeDefinition();
4669 return getTagDeclType(CFConstantStringTypeDecl);
4672 QualType ASTContext::getObjCSuperType() const {
4673 if (ObjCSuperType.isNull()) {
4674 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
4675 TUDecl->addDecl(ObjCSuperTypeDecl);
4676 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4678 return ObjCSuperType;
4681 void ASTContext::setCFConstantStringType(QualType T) {
4682 const RecordType *Rec = T->getAs<RecordType>();
4683 assert(Rec && "Invalid CFConstantStringType");
4684 CFConstantStringTypeDecl = Rec->getDecl();
4687 QualType ASTContext::getBlockDescriptorType() const {
4688 if (BlockDescriptorType)
4689 return getTagDeclType(BlockDescriptorType);
4692 // FIXME: Needs the FlagAppleBlock bit.
4693 RD = buildImplicitRecord("__block_descriptor");
4694 RD->startDefinition();
4696 QualType FieldTypes[] = {
4701 static const char *const FieldNames[] = {
4706 for (size_t i = 0; i < 2; ++i) {
4707 FieldDecl *Field = FieldDecl::Create(
4708 *this, RD, SourceLocation(), SourceLocation(),
4709 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4710 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
4711 Field->setAccess(AS_public);
4715 RD->completeDefinition();
4717 BlockDescriptorType = RD;
4719 return getTagDeclType(BlockDescriptorType);
4722 QualType ASTContext::getBlockDescriptorExtendedType() const {
4723 if (BlockDescriptorExtendedType)
4724 return getTagDeclType(BlockDescriptorExtendedType);
4727 // FIXME: Needs the FlagAppleBlock bit.
4728 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4729 RD->startDefinition();
4731 QualType FieldTypes[] = {
4734 getPointerType(VoidPtrTy),
4735 getPointerType(VoidPtrTy)
4738 static const char *const FieldNames[] = {
4745 for (size_t i = 0; i < 4; ++i) {
4746 FieldDecl *Field = FieldDecl::Create(
4747 *this, RD, SourceLocation(), SourceLocation(),
4748 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4749 /*BitWidth=*/nullptr,
4750 /*Mutable=*/false, ICIS_NoInit);
4751 Field->setAccess(AS_public);
4755 RD->completeDefinition();
4757 BlockDescriptorExtendedType = RD;
4758 return getTagDeclType(BlockDescriptorExtendedType);
4761 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4762 /// requires copy/dispose. Note that this must match the logic
4763 /// in buildByrefHelpers.
4764 bool ASTContext::BlockRequiresCopying(QualType Ty,
4766 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4767 const Expr *copyExpr = getBlockVarCopyInits(D);
4768 if (!copyExpr && record->hasTrivialDestructor()) return false;
4773 if (!Ty->isObjCRetainableType()) return false;
4775 Qualifiers qs = Ty.getQualifiers();
4777 // If we have lifetime, that dominates.
4778 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4779 assert(getLangOpts().ObjCAutoRefCount);
4782 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4784 // These are just bits as far as the runtime is concerned.
4785 case Qualifiers::OCL_ExplicitNone:
4786 case Qualifiers::OCL_Autoreleasing:
4789 // Tell the runtime that this is ARC __weak, called by the
4791 case Qualifiers::OCL_Weak:
4792 // ARC __strong __block variables need to be retained.
4793 case Qualifiers::OCL_Strong:
4796 llvm_unreachable("fell out of lifetime switch!");
4798 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4799 Ty->isObjCObjectPointerType());
4802 bool ASTContext::getByrefLifetime(QualType Ty,
4803 Qualifiers::ObjCLifetime &LifeTime,
4804 bool &HasByrefExtendedLayout) const {
4806 if (!getLangOpts().ObjC1 ||
4807 getLangOpts().getGC() != LangOptions::NonGC)
4810 HasByrefExtendedLayout = false;
4811 if (Ty->isRecordType()) {
4812 HasByrefExtendedLayout = true;
4813 LifeTime = Qualifiers::OCL_None;
4815 else if (getLangOpts().ObjCAutoRefCount)
4816 LifeTime = Ty.getObjCLifetime();
4818 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4819 LifeTime = Qualifiers::OCL_ExplicitNone;
4821 LifeTime = Qualifiers::OCL_None;
4825 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4826 if (!ObjCInstanceTypeDecl)
4827 ObjCInstanceTypeDecl =
4828 buildImplicitTypedef(getObjCIdType(), "instancetype");
4829 return ObjCInstanceTypeDecl;
4832 // This returns true if a type has been typedefed to BOOL:
4833 // typedef <type> BOOL;
4834 static bool isTypeTypedefedAsBOOL(QualType T) {
4835 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
4836 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4837 return II->isStr("BOOL");
4842 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
4844 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
4845 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4846 return CharUnits::Zero();
4848 CharUnits sz = getTypeSizeInChars(type);
4850 // Make all integer and enum types at least as large as an int
4851 if (sz.isPositive() && type->isIntegralOrEnumerationType())
4852 sz = std::max(sz, getTypeSizeInChars(IntTy));
4853 // Treat arrays as pointers, since that's how they're passed in.
4854 else if (type->isArrayType())
4855 sz = getTypeSizeInChars(VoidPtrTy);
4859 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4860 return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4861 VD->getType()->isIntegralOrEnumerationType() &&
4862 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
4866 std::string charUnitsToString(const CharUnits &CU) {
4867 return llvm::itostr(CU.getQuantity());
4870 /// getObjCEncodingForBlock - Return the encoded type for this block
4872 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4875 const BlockDecl *Decl = Expr->getBlockDecl();
4877 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4878 // Encode result type.
4879 if (getLangOpts().EncodeExtendedBlockSig)
4880 getObjCEncodingForMethodParameter(
4881 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
4884 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
4885 // Compute size of all parameters.
4886 // Start with computing size of a pointer in number of bytes.
4887 // FIXME: There might(should) be a better way of doing this computation!
4889 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4890 CharUnits ParmOffset = PtrSize;
4891 for (auto PI : Decl->params()) {
4892 QualType PType = PI->getType();
4893 CharUnits sz = getObjCEncodingTypeSize(PType);
4896 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
4899 // Size of the argument frame
4900 S += charUnitsToString(ParmOffset);
4901 // Block pointer and offset.
4905 ParmOffset = PtrSize;
4906 for (auto PVDecl : Decl->params()) {
4907 QualType PType = PVDecl->getOriginalType();
4908 if (const ArrayType *AT =
4909 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4910 // Use array's original type only if it has known number of
4912 if (!isa<ConstantArrayType>(AT))
4913 PType = PVDecl->getType();
4914 } else if (PType->isFunctionType())
4915 PType = PVDecl->getType();
4916 if (getLangOpts().EncodeExtendedBlockSig)
4917 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4918 S, true /*Extended*/);
4920 getObjCEncodingForType(PType, S);
4921 S += charUnitsToString(ParmOffset);
4922 ParmOffset += getObjCEncodingTypeSize(PType);
4928 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
4930 // Encode result type.
4931 getObjCEncodingForType(Decl->getReturnType(), S);
4932 CharUnits ParmOffset;
4933 // Compute size of all parameters.
4934 for (auto PI : Decl->params()) {
4935 QualType PType = PI->getType();
4936 CharUnits sz = getObjCEncodingTypeSize(PType);
4940 assert (sz.isPositive() &&
4941 "getObjCEncodingForFunctionDecl - Incomplete param type");
4944 S += charUnitsToString(ParmOffset);
4945 ParmOffset = CharUnits::Zero();
4948 for (auto PVDecl : Decl->params()) {
4949 QualType PType = PVDecl->getOriginalType();
4950 if (const ArrayType *AT =
4951 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4952 // Use array's original type only if it has known number of
4954 if (!isa<ConstantArrayType>(AT))
4955 PType = PVDecl->getType();
4956 } else if (PType->isFunctionType())
4957 PType = PVDecl->getType();
4958 getObjCEncodingForType(PType, S);
4959 S += charUnitsToString(ParmOffset);
4960 ParmOffset += getObjCEncodingTypeSize(PType);
4966 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
4967 /// method parameter or return type. If Extended, include class names and
4968 /// block object types.
4969 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4970 QualType T, std::string& S,
4971 bool Extended) const {
4972 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4973 getObjCEncodingForTypeQualifier(QT, S);
4974 // Encode parameter type.
4975 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
4976 true /*OutermostType*/,
4977 false /*EncodingProperty*/,
4978 false /*StructField*/,
4979 Extended /*EncodeBlockParameters*/,
4980 Extended /*EncodeClassNames*/);
4983 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
4985 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
4987 bool Extended) const {
4988 // FIXME: This is not very efficient.
4989 // Encode return type.
4990 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4991 Decl->getReturnType(), S, Extended);
4992 // Compute size of all parameters.
4993 // Start with computing size of a pointer in number of bytes.
4994 // FIXME: There might(should) be a better way of doing this computation!
4996 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4997 // The first two arguments (self and _cmd) are pointers; account for
4999 CharUnits ParmOffset = 2 * PtrSize;
5000 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5001 E = Decl->sel_param_end(); PI != E; ++PI) {
5002 QualType PType = (*PI)->getType();
5003 CharUnits sz = getObjCEncodingTypeSize(PType);
5007 assert (sz.isPositive() &&
5008 "getObjCEncodingForMethodDecl - Incomplete param type");
5011 S += charUnitsToString(ParmOffset);
5013 S += charUnitsToString(PtrSize);
5016 ParmOffset = 2 * PtrSize;
5017 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5018 E = Decl->sel_param_end(); PI != E; ++PI) {
5019 const ParmVarDecl *PVDecl = *PI;
5020 QualType PType = PVDecl->getOriginalType();
5021 if (const ArrayType *AT =
5022 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5023 // Use array's original type only if it has known number of
5025 if (!isa<ConstantArrayType>(AT))
5026 PType = PVDecl->getType();
5027 } else if (PType->isFunctionType())
5028 PType = PVDecl->getType();
5029 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5030 PType, S, Extended);
5031 S += charUnitsToString(ParmOffset);
5032 ParmOffset += getObjCEncodingTypeSize(PType);
5038 ObjCPropertyImplDecl *
5039 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5040 const ObjCPropertyDecl *PD,
5041 const Decl *Container) const {
5044 if (const ObjCCategoryImplDecl *CID =
5045 dyn_cast<ObjCCategoryImplDecl>(Container)) {
5046 for (auto *PID : CID->property_impls())
5047 if (PID->getPropertyDecl() == PD)
5050 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5051 for (auto *PID : OID->property_impls())
5052 if (PID->getPropertyDecl() == PD)
5058 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
5059 /// property declaration. If non-NULL, Container must be either an
5060 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5061 /// NULL when getting encodings for protocol properties.
5062 /// Property attributes are stored as a comma-delimited C string. The simple
5063 /// attributes readonly and bycopy are encoded as single characters. The
5064 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
5065 /// encoded as single characters, followed by an identifier. Property types
5066 /// are also encoded as a parametrized attribute. The characters used to encode
5067 /// these attributes are defined by the following enumeration:
5069 /// enum PropertyAttributes {
5070 /// kPropertyReadOnly = 'R', // property is read-only.
5071 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5072 /// kPropertyByref = '&', // property is a reference to the value last assigned
5073 /// kPropertyDynamic = 'D', // property is dynamic
5074 /// kPropertyGetter = 'G', // followed by getter selector name
5075 /// kPropertySetter = 'S', // followed by setter selector name
5076 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
5077 /// kPropertyType = 'T' // followed by old-style type encoding.
5078 /// kPropertyWeak = 'W' // 'weak' property
5079 /// kPropertyStrong = 'P' // property GC'able
5080 /// kPropertyNonAtomic = 'N' // property non-atomic
5083 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5084 const Decl *Container,
5085 std::string& S) const {
5086 // Collect information from the property implementation decl(s).
5087 bool Dynamic = false;
5088 ObjCPropertyImplDecl *SynthesizePID = nullptr;
5090 if (ObjCPropertyImplDecl *PropertyImpDecl =
5091 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5092 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5095 SynthesizePID = PropertyImpDecl;
5098 // FIXME: This is not very efficient.
5101 // Encode result type.
5102 // GCC has some special rules regarding encoding of properties which
5103 // closely resembles encoding of ivars.
5104 getObjCEncodingForPropertyType(PD->getType(), S);
5106 if (PD->isReadOnly()) {
5108 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5110 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5112 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5115 switch (PD->getSetterKind()) {
5116 case ObjCPropertyDecl::Assign: break;
5117 case ObjCPropertyDecl::Copy: S += ",C"; break;
5118 case ObjCPropertyDecl::Retain: S += ",&"; break;
5119 case ObjCPropertyDecl::Weak: S += ",W"; break;
5123 // It really isn't clear at all what this means, since properties
5124 // are "dynamic by default".
5128 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5131 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5133 S += PD->getGetterName().getAsString();
5136 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5138 S += PD->getSetterName().getAsString();
5141 if (SynthesizePID) {
5142 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5144 S += OID->getNameAsString();
5147 // FIXME: OBJCGC: weak & strong
5150 /// getLegacyIntegralTypeEncoding -
5151 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5152 /// 'l' or 'L' , but not always. For typedefs, we need to use
5153 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5155 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5156 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5157 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5158 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5159 PointeeTy = UnsignedIntTy;
5161 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5167 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5168 const FieldDecl *Field,
5169 QualType *NotEncodedT) const {
5170 // We follow the behavior of gcc, expanding structures which are
5171 // directly pointed to, and expanding embedded structures. Note that
5172 // these rules are sufficient to prevent recursive encoding of the
5174 getObjCEncodingForTypeImpl(T, S, true, true, Field,
5175 true /* outermost type */, false, false,
5176 false, false, false, NotEncodedT);
5179 void ASTContext::getObjCEncodingForPropertyType(QualType T,
5180 std::string& S) const {
5181 // Encode result type.
5182 // GCC has some special rules regarding encoding of properties which
5183 // closely resembles encoding of ivars.
5184 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5185 true /* outermost type */,
5186 true /* encoding property */);
5189 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5190 BuiltinType::Kind kind) {
5192 case BuiltinType::Void: return 'v';
5193 case BuiltinType::Bool: return 'B';
5194 case BuiltinType::Char_U:
5195 case BuiltinType::UChar: return 'C';
5196 case BuiltinType::Char16:
5197 case BuiltinType::UShort: return 'S';
5198 case BuiltinType::Char32:
5199 case BuiltinType::UInt: return 'I';
5200 case BuiltinType::ULong:
5201 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5202 case BuiltinType::UInt128: return 'T';
5203 case BuiltinType::ULongLong: return 'Q';
5204 case BuiltinType::Char_S:
5205 case BuiltinType::SChar: return 'c';
5206 case BuiltinType::Short: return 's';
5207 case BuiltinType::WChar_S:
5208 case BuiltinType::WChar_U:
5209 case BuiltinType::Int: return 'i';
5210 case BuiltinType::Long:
5211 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5212 case BuiltinType::LongLong: return 'q';
5213 case BuiltinType::Int128: return 't';
5214 case BuiltinType::Float: return 'f';
5215 case BuiltinType::Double: return 'd';
5216 case BuiltinType::LongDouble: return 'D';
5217 case BuiltinType::NullPtr: return '*'; // like char*
5219 case BuiltinType::Half:
5220 // FIXME: potentially need @encodes for these!
5223 case BuiltinType::ObjCId:
5224 case BuiltinType::ObjCClass:
5225 case BuiltinType::ObjCSel:
5226 llvm_unreachable("@encoding ObjC primitive type");
5228 // OpenCL and placeholder types don't need @encodings.
5229 case BuiltinType::OCLImage1d:
5230 case BuiltinType::OCLImage1dArray:
5231 case BuiltinType::OCLImage1dBuffer:
5232 case BuiltinType::OCLImage2d:
5233 case BuiltinType::OCLImage2dArray:
5234 case BuiltinType::OCLImage3d:
5235 case BuiltinType::OCLEvent:
5236 case BuiltinType::OCLSampler:
5237 case BuiltinType::Dependent:
5238 #define BUILTIN_TYPE(KIND, ID)
5239 #define PLACEHOLDER_TYPE(KIND, ID) \
5240 case BuiltinType::KIND:
5241 #include "clang/AST/BuiltinTypes.def"
5242 llvm_unreachable("invalid builtin type for @encode");
5244 llvm_unreachable("invalid BuiltinType::Kind value");
5247 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5248 EnumDecl *Enum = ET->getDecl();
5250 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5251 if (!Enum->isFixed())
5254 // The encoding of a fixed enum type matches its fixed underlying type.
5255 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5256 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5259 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5260 QualType T, const FieldDecl *FD) {
5261 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5263 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5264 // The GNU runtime requires more information; bitfields are encoded as b,
5265 // then the offset (in bits) of the first element, then the type of the
5266 // bitfield, then the size in bits. For example, in this structure:
5273 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5274 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5275 // information is not especially sensible, but we're stuck with it for
5276 // compatibility with GCC, although providing it breaks anything that
5277 // actually uses runtime introspection and wants to work on both runtimes...
5278 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5279 const RecordDecl *RD = FD->getParent();
5280 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5281 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5282 if (const EnumType *ET = T->getAs<EnumType>())
5283 S += ObjCEncodingForEnumType(Ctx, ET);
5285 const BuiltinType *BT = T->castAs<BuiltinType>();
5286 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5289 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5292 // FIXME: Use SmallString for accumulating string.
5293 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5294 bool ExpandPointedToStructures,
5295 bool ExpandStructures,
5296 const FieldDecl *FD,
5298 bool EncodingProperty,
5300 bool EncodeBlockParameters,
5301 bool EncodeClassNames,
5302 bool EncodePointerToObjCTypedef,
5303 QualType *NotEncodedT) const {
5304 CanQualType CT = getCanonicalType(T);
5305 switch (CT->getTypeClass()) {
5308 if (FD && FD->isBitField())
5309 return EncodeBitField(this, S, T, FD);
5310 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5311 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5313 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5316 case Type::Complex: {
5317 const ComplexType *CT = T->castAs<ComplexType>();
5319 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
5323 case Type::Atomic: {
5324 const AtomicType *AT = T->castAs<AtomicType>();
5326 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
5330 // encoding for pointer or reference types.
5332 case Type::LValueReference:
5333 case Type::RValueReference: {
5335 if (isa<PointerType>(CT)) {
5336 const PointerType *PT = T->castAs<PointerType>();
5337 if (PT->isObjCSelType()) {
5341 PointeeTy = PT->getPointeeType();
5343 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5346 bool isReadOnly = false;
5347 // For historical/compatibility reasons, the read-only qualifier of the
5348 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5349 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5350 // Also, do not emit the 'r' for anything but the outermost type!
5351 if (isa<TypedefType>(T.getTypePtr())) {
5352 if (OutermostType && T.isConstQualified()) {
5356 } else if (OutermostType) {
5357 QualType P = PointeeTy;
5358 while (P->getAs<PointerType>())
5359 P = P->getAs<PointerType>()->getPointeeType();
5360 if (P.isConstQualified()) {
5366 // Another legacy compatibility encoding. Some ObjC qualifier and type
5367 // combinations need to be rearranged.
5368 // Rewrite "in const" from "nr" to "rn"
5369 if (StringRef(S).endswith("nr"))
5370 S.replace(S.end()-2, S.end(), "rn");
5373 if (PointeeTy->isCharType()) {
5374 // char pointer types should be encoded as '*' unless it is a
5375 // type that has been typedef'd to 'BOOL'.
5376 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5380 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5381 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5382 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5386 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5387 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5394 getLegacyIntegralTypeEncoding(PointeeTy);
5396 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5397 nullptr, false, false, false, false, false, false,
5402 case Type::ConstantArray:
5403 case Type::IncompleteArray:
5404 case Type::VariableArray: {
5405 const ArrayType *AT = cast<ArrayType>(CT);
5407 if (isa<IncompleteArrayType>(AT) && !StructField) {
5408 // Incomplete arrays are encoded as a pointer to the array element.
5411 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5412 false, ExpandStructures, FD);
5416 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5417 S += llvm::utostr(CAT->getSize().getZExtValue());
5419 //Variable length arrays are encoded as a regular array with 0 elements.
5420 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5421 "Unknown array type!");
5425 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5426 false, ExpandStructures, FD,
5427 false, false, false, false, false, false,
5434 case Type::FunctionNoProto:
5435 case Type::FunctionProto:
5439 case Type::Record: {
5440 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5441 S += RDecl->isUnion() ? '(' : '{';
5442 // Anonymous structures print as '?'
5443 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5445 if (ClassTemplateSpecializationDecl *Spec
5446 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5447 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5448 llvm::raw_string_ostream OS(S);
5449 TemplateSpecializationType::PrintTemplateArgumentList(OS,
5450 TemplateArgs.data(),
5451 TemplateArgs.size(),
5452 (*this).getPrintingPolicy());
5457 if (ExpandStructures) {
5459 if (!RDecl->isUnion()) {
5460 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
5462 for (const auto *Field : RDecl->fields()) {
5465 S += Field->getNameAsString();
5469 // Special case bit-fields.
5470 if (Field->isBitField()) {
5471 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5474 QualType qt = Field->getType();
5475 getLegacyIntegralTypeEncoding(qt);
5476 getObjCEncodingForTypeImpl(qt, S, false, true,
5477 FD, /*OutermostType*/false,
5478 /*EncodingProperty*/false,
5479 /*StructField*/true,
5480 false, false, false, NotEncodedT);
5485 S += RDecl->isUnion() ? ')' : '}';
5489 case Type::BlockPointer: {
5490 const BlockPointerType *BT = T->castAs<BlockPointerType>();
5491 S += "@?"; // Unlike a pointer-to-function, which is "^?".
5492 if (EncodeBlockParameters) {
5493 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5496 // Block return type
5497 getObjCEncodingForTypeImpl(
5498 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5499 FD, false /* OutermostType */, EncodingProperty,
5500 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5505 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5506 for (const auto &I : FPT->param_types())
5507 getObjCEncodingForTypeImpl(
5508 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5509 false /* OutermostType */, EncodingProperty,
5510 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5511 false, NotEncodedT);
5518 case Type::ObjCObject: {
5519 // hack to match legacy encoding of *id and *Class
5520 QualType Ty = getObjCObjectPointerType(CT);
5521 if (Ty->isObjCIdType()) {
5522 S += "{objc_object=}";
5525 else if (Ty->isObjCClassType()) {
5526 S += "{objc_class=}";
5531 case Type::ObjCInterface: {
5532 // Ignore protocol qualifiers when mangling at this level.
5533 T = T->castAs<ObjCObjectType>()->getBaseType();
5535 // The assumption seems to be that this assert will succeed
5536 // because nested levels will have filtered out 'id' and 'Class'.
5537 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
5538 // @encode(class_name)
5539 ObjCInterfaceDecl *OI = OIT->getDecl();
5541 const IdentifierInfo *II = OI->getIdentifier();
5544 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5545 DeepCollectObjCIvars(OI, true, Ivars);
5546 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5547 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5548 if (Field->isBitField())
5549 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5551 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5552 false, false, false, false, false,
5553 EncodePointerToObjCTypedef,
5560 case Type::ObjCObjectPointer: {
5561 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5562 if (OPT->isObjCIdType()) {
5567 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5568 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5569 // Since this is a binary compatibility issue, need to consult with runtime
5570 // folks. Fortunately, this is a *very* obsure construct.
5575 if (OPT->isObjCQualifiedIdType()) {
5576 getObjCEncodingForTypeImpl(getObjCIdType(), S,
5577 ExpandPointedToStructures,
5578 ExpandStructures, FD);
5579 if (FD || EncodingProperty || EncodeClassNames) {
5580 // Note that we do extended encoding of protocol qualifer list
5581 // Only when doing ivar or property encoding.
5583 for (const auto *I : OPT->quals()) {
5585 S += I->getNameAsString();
5593 QualType PointeeTy = OPT->getPointeeType();
5594 if (!EncodingProperty &&
5595 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5596 !EncodePointerToObjCTypedef) {
5597 // Another historical/compatibility reason.
5598 // We encode the underlying type which comes out as
5601 if (FD && OPT->getInterfaceDecl()) {
5602 // Prevent recursive encoding of fields in some rare cases.
5603 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5604 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5605 DeepCollectObjCIvars(OI, true, Ivars);
5606 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5607 if (cast<FieldDecl>(Ivars[i]) == FD) {
5609 S += OI->getIdentifier()->getName();
5615 getObjCEncodingForTypeImpl(PointeeTy, S,
5616 false, ExpandPointedToStructures,
5618 false, false, false, false, false,
5619 /*EncodePointerToObjCTypedef*/true);
5624 if (OPT->getInterfaceDecl() &&
5625 (FD || EncodingProperty || EncodeClassNames)) {
5627 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
5628 for (const auto *I : OPT->quals()) {
5630 S += I->getNameAsString();
5638 // gcc just blithely ignores member pointers.
5639 // FIXME: we shoul do better than that. 'M' is available.
5640 case Type::MemberPointer:
5641 // This matches gcc's encoding, even though technically it is insufficient.
5642 //FIXME. We should do a better job than gcc.
5644 case Type::ExtVector:
5645 // Until we have a coherent encoding of these three types, issue warning.
5651 // We could see an undeduced auto type here during error recovery.
5657 #define ABSTRACT_TYPE(KIND, BASE)
5658 #define TYPE(KIND, BASE)
5659 #define DEPENDENT_TYPE(KIND, BASE) \
5661 #define NON_CANONICAL_TYPE(KIND, BASE) \
5663 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5665 #include "clang/AST/TypeNodes.def"
5666 llvm_unreachable("@encode for dependent type!");
5668 llvm_unreachable("bad type kind!");
5671 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5673 const FieldDecl *FD,
5675 QualType *NotEncodedT) const {
5676 assert(RDecl && "Expected non-null RecordDecl");
5677 assert(!RDecl->isUnion() && "Should not be called for unions");
5678 if (!RDecl->getDefinition())
5681 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5682 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5683 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5686 for (const auto &BI : CXXRec->bases()) {
5687 if (!BI.isVirtual()) {
5688 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5689 if (base->isEmpty())
5691 uint64_t offs = toBits(layout.getBaseClassOffset(base));
5692 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5693 std::make_pair(offs, base));
5699 for (auto *Field : RDecl->fields()) {
5700 uint64_t offs = layout.getFieldOffset(i);
5701 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5702 std::make_pair(offs, Field));
5706 if (CXXRec && includeVBases) {
5707 for (const auto &BI : CXXRec->vbases()) {
5708 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5709 if (base->isEmpty())
5711 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
5712 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5713 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5714 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5715 std::make_pair(offs, base));
5721 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5723 size = layout.getSize();
5727 uint64_t CurOffs = 0;
5729 std::multimap<uint64_t, NamedDecl *>::iterator
5730 CurLayObj = FieldOrBaseOffsets.begin();
5732 if (CXXRec && CXXRec->isDynamicClass() &&
5733 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
5736 std::string recname = CXXRec->getNameAsString();
5737 if (recname.empty()) recname = "?";
5743 CurOffs += getTypeSize(VoidPtrTy);
5747 if (!RDecl->hasFlexibleArrayMember()) {
5748 // Mark the end of the structure.
5749 uint64_t offs = toBits(size);
5750 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5751 std::make_pair(offs, nullptr));
5754 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5756 assert(CurOffs <= CurLayObj->first);
5757 if (CurOffs < CurLayObj->first) {
5758 uint64_t padding = CurLayObj->first - CurOffs;
5759 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5760 // packing/alignment of members is different that normal, in which case
5761 // the encoding will be out-of-sync with the real layout.
5762 // If the runtime switches to just consider the size of types without
5763 // taking into account alignment, we could make padding explicit in the
5764 // encoding (e.g. using arrays of chars). The encoding strings would be
5765 // longer then though.
5770 NamedDecl *dcl = CurLayObj->second;
5772 break; // reached end of structure.
5774 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5775 // We expand the bases without their virtual bases since those are going
5776 // in the initial structure. Note that this differs from gcc which
5777 // expands virtual bases each time one is encountered in the hierarchy,
5778 // making the encoding type bigger than it really is.
5779 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5781 assert(!base->isEmpty());
5783 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
5786 FieldDecl *field = cast<FieldDecl>(dcl);
5789 S += field->getNameAsString();
5793 if (field->isBitField()) {
5794 EncodeBitField(this, S, field->getType(), field);
5796 CurOffs += field->getBitWidthValue(*this);
5799 QualType qt = field->getType();
5800 getLegacyIntegralTypeEncoding(qt);
5801 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5802 /*OutermostType*/false,
5803 /*EncodingProperty*/false,
5804 /*StructField*/true,
5805 false, false, false, NotEncodedT);
5807 CurOffs += getTypeSize(field->getType());
5814 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
5815 std::string& S) const {
5816 if (QT & Decl::OBJC_TQ_In)
5818 if (QT & Decl::OBJC_TQ_Inout)
5820 if (QT & Decl::OBJC_TQ_Out)
5822 if (QT & Decl::OBJC_TQ_Bycopy)
5824 if (QT & Decl::OBJC_TQ_Byref)
5826 if (QT & Decl::OBJC_TQ_Oneway)
5830 TypedefDecl *ASTContext::getObjCIdDecl() const {
5832 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0);
5833 T = getObjCObjectPointerType(T);
5834 ObjCIdDecl = buildImplicitTypedef(T, "id");
5839 TypedefDecl *ASTContext::getObjCSelDecl() const {
5841 QualType T = getPointerType(ObjCBuiltinSelTy);
5842 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
5847 TypedefDecl *ASTContext::getObjCClassDecl() const {
5848 if (!ObjCClassDecl) {
5849 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0);
5850 T = getObjCObjectPointerType(T);
5851 ObjCClassDecl = buildImplicitTypedef(T, "Class");
5853 return ObjCClassDecl;
5856 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5857 if (!ObjCProtocolClassDecl) {
5858 ObjCProtocolClassDecl
5859 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5861 &Idents.get("Protocol"),
5862 /*PrevDecl=*/nullptr,
5863 SourceLocation(), true);
5866 return ObjCProtocolClassDecl;
5869 //===----------------------------------------------------------------------===//
5870 // __builtin_va_list Construction Functions
5871 //===----------------------------------------------------------------------===//
5873 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5874 // typedef char* __builtin_va_list;
5875 QualType T = Context->getPointerType(Context->CharTy);
5876 return Context->buildImplicitTypedef(T, "__builtin_va_list");
5879 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5880 // typedef void* __builtin_va_list;
5881 QualType T = Context->getPointerType(Context->VoidTy);
5882 return Context->buildImplicitTypedef(T, "__builtin_va_list");
5885 static TypedefDecl *
5886 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5888 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
5889 if (Context->getLangOpts().CPlusPlus) {
5890 // namespace std { struct __va_list {
5892 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5893 Context->getTranslationUnitDecl(),
5894 /*Inline*/ false, SourceLocation(),
5895 SourceLocation(), &Context->Idents.get("std"),
5896 /*PrevDecl*/ nullptr);
5898 VaListTagDecl->setDeclContext(NS);
5901 VaListTagDecl->startDefinition();
5903 const size_t NumFields = 5;
5904 QualType FieldTypes[NumFields];
5905 const char *FieldNames[NumFields];
5908 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5909 FieldNames[0] = "__stack";
5912 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5913 FieldNames[1] = "__gr_top";
5916 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5917 FieldNames[2] = "__vr_top";
5920 FieldTypes[3] = Context->IntTy;
5921 FieldNames[3] = "__gr_offs";
5924 FieldTypes[4] = Context->IntTy;
5925 FieldNames[4] = "__vr_offs";
5928 for (unsigned i = 0; i < NumFields; ++i) {
5929 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5933 &Context->Idents.get(FieldNames[i]),
5934 FieldTypes[i], /*TInfo=*/nullptr,
5935 /*BitWidth=*/nullptr,
5938 Field->setAccess(AS_public);
5939 VaListTagDecl->addDecl(Field);
5941 VaListTagDecl->completeDefinition();
5942 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5943 Context->VaListTagTy = VaListTagType;
5945 // } __builtin_va_list;
5946 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
5949 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5950 // typedef struct __va_list_tag {
5951 RecordDecl *VaListTagDecl;
5953 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
5954 VaListTagDecl->startDefinition();
5956 const size_t NumFields = 5;
5957 QualType FieldTypes[NumFields];
5958 const char *FieldNames[NumFields];
5960 // unsigned char gpr;
5961 FieldTypes[0] = Context->UnsignedCharTy;
5962 FieldNames[0] = "gpr";
5964 // unsigned char fpr;
5965 FieldTypes[1] = Context->UnsignedCharTy;
5966 FieldNames[1] = "fpr";
5968 // unsigned short reserved;
5969 FieldTypes[2] = Context->UnsignedShortTy;
5970 FieldNames[2] = "reserved";
5972 // void* overflow_arg_area;
5973 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5974 FieldNames[3] = "overflow_arg_area";
5976 // void* reg_save_area;
5977 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5978 FieldNames[4] = "reg_save_area";
5981 for (unsigned i = 0; i < NumFields; ++i) {
5982 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5985 &Context->Idents.get(FieldNames[i]),
5986 FieldTypes[i], /*TInfo=*/nullptr,
5987 /*BitWidth=*/nullptr,
5990 Field->setAccess(AS_public);
5991 VaListTagDecl->addDecl(Field);
5993 VaListTagDecl->completeDefinition();
5994 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5995 Context->VaListTagTy = VaListTagType;
5998 TypedefDecl *VaListTagTypedefDecl =
5999 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6001 QualType VaListTagTypedefType =
6002 Context->getTypedefType(VaListTagTypedefDecl);
6004 // typedef __va_list_tag __builtin_va_list[1];
6005 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6006 QualType VaListTagArrayType
6007 = Context->getConstantArrayType(VaListTagTypedefType,
6008 Size, ArrayType::Normal, 0);
6009 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6012 static TypedefDecl *
6013 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6014 // typedef struct __va_list_tag {
6015 RecordDecl *VaListTagDecl;
6016 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6017 VaListTagDecl->startDefinition();
6019 const size_t NumFields = 4;
6020 QualType FieldTypes[NumFields];
6021 const char *FieldNames[NumFields];
6023 // unsigned gp_offset;
6024 FieldTypes[0] = Context->UnsignedIntTy;
6025 FieldNames[0] = "gp_offset";
6027 // unsigned fp_offset;
6028 FieldTypes[1] = Context->UnsignedIntTy;
6029 FieldNames[1] = "fp_offset";
6031 // void* overflow_arg_area;
6032 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6033 FieldNames[2] = "overflow_arg_area";
6035 // void* reg_save_area;
6036 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6037 FieldNames[3] = "reg_save_area";
6040 for (unsigned i = 0; i < NumFields; ++i) {
6041 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6045 &Context->Idents.get(FieldNames[i]),
6046 FieldTypes[i], /*TInfo=*/nullptr,
6047 /*BitWidth=*/nullptr,
6050 Field->setAccess(AS_public);
6051 VaListTagDecl->addDecl(Field);
6053 VaListTagDecl->completeDefinition();
6054 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6055 Context->VaListTagTy = VaListTagType;
6058 TypedefDecl *VaListTagTypedefDecl =
6059 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6061 QualType VaListTagTypedefType =
6062 Context->getTypedefType(VaListTagTypedefDecl);
6064 // typedef __va_list_tag __builtin_va_list[1];
6065 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6066 QualType VaListTagArrayType
6067 = Context->getConstantArrayType(VaListTagTypedefType,
6068 Size, ArrayType::Normal,0);
6069 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6072 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6073 // typedef int __builtin_va_list[4];
6074 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6075 QualType IntArrayType
6076 = Context->getConstantArrayType(Context->IntTy,
6077 Size, ArrayType::Normal, 0);
6078 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6081 static TypedefDecl *
6082 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6084 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6085 if (Context->getLangOpts().CPlusPlus) {
6086 // namespace std { struct __va_list {
6088 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6089 Context->getTranslationUnitDecl(),
6090 /*Inline*/false, SourceLocation(),
6091 SourceLocation(), &Context->Idents.get("std"),
6092 /*PrevDecl*/ nullptr);
6094 VaListDecl->setDeclContext(NS);
6097 VaListDecl->startDefinition();
6100 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6104 &Context->Idents.get("__ap"),
6105 Context->getPointerType(Context->VoidTy),
6107 /*BitWidth=*/nullptr,
6110 Field->setAccess(AS_public);
6111 VaListDecl->addDecl(Field);
6114 VaListDecl->completeDefinition();
6116 // typedef struct __va_list __builtin_va_list;
6117 QualType T = Context->getRecordType(VaListDecl);
6118 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6121 static TypedefDecl *
6122 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6123 // typedef struct __va_list_tag {
6124 RecordDecl *VaListTagDecl;
6125 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6126 VaListTagDecl->startDefinition();
6128 const size_t NumFields = 4;
6129 QualType FieldTypes[NumFields];
6130 const char *FieldNames[NumFields];
6133 FieldTypes[0] = Context->LongTy;
6134 FieldNames[0] = "__gpr";
6137 FieldTypes[1] = Context->LongTy;
6138 FieldNames[1] = "__fpr";
6140 // void *__overflow_arg_area;
6141 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6142 FieldNames[2] = "__overflow_arg_area";
6144 // void *__reg_save_area;
6145 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6146 FieldNames[3] = "__reg_save_area";
6149 for (unsigned i = 0; i < NumFields; ++i) {
6150 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6154 &Context->Idents.get(FieldNames[i]),
6155 FieldTypes[i], /*TInfo=*/nullptr,
6156 /*BitWidth=*/nullptr,
6159 Field->setAccess(AS_public);
6160 VaListTagDecl->addDecl(Field);
6162 VaListTagDecl->completeDefinition();
6163 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6164 Context->VaListTagTy = VaListTagType;
6167 TypedefDecl *VaListTagTypedefDecl =
6168 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6169 QualType VaListTagTypedefType =
6170 Context->getTypedefType(VaListTagTypedefDecl);
6172 // typedef __va_list_tag __builtin_va_list[1];
6173 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6174 QualType VaListTagArrayType
6175 = Context->getConstantArrayType(VaListTagTypedefType,
6176 Size, ArrayType::Normal,0);
6178 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6181 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6182 TargetInfo::BuiltinVaListKind Kind) {
6184 case TargetInfo::CharPtrBuiltinVaList:
6185 return CreateCharPtrBuiltinVaListDecl(Context);
6186 case TargetInfo::VoidPtrBuiltinVaList:
6187 return CreateVoidPtrBuiltinVaListDecl(Context);
6188 case TargetInfo::AArch64ABIBuiltinVaList:
6189 return CreateAArch64ABIBuiltinVaListDecl(Context);
6190 case TargetInfo::PowerABIBuiltinVaList:
6191 return CreatePowerABIBuiltinVaListDecl(Context);
6192 case TargetInfo::X86_64ABIBuiltinVaList:
6193 return CreateX86_64ABIBuiltinVaListDecl(Context);
6194 case TargetInfo::PNaClABIBuiltinVaList:
6195 return CreatePNaClABIBuiltinVaListDecl(Context);
6196 case TargetInfo::AAPCSABIBuiltinVaList:
6197 return CreateAAPCSABIBuiltinVaListDecl(Context);
6198 case TargetInfo::SystemZBuiltinVaList:
6199 return CreateSystemZBuiltinVaListDecl(Context);
6202 llvm_unreachable("Unhandled __builtin_va_list type kind");
6205 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6206 if (!BuiltinVaListDecl) {
6207 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6208 assert(BuiltinVaListDecl->isImplicit());
6211 return BuiltinVaListDecl;
6214 QualType ASTContext::getVaListTagType() const {
6215 // Force the creation of VaListTagTy by building the __builtin_va_list
6217 if (VaListTagTy.isNull())
6218 (void) getBuiltinVaListDecl();
6223 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6224 assert(ObjCConstantStringType.isNull() &&
6225 "'NSConstantString' type already set!");
6227 ObjCConstantStringType = getObjCInterfaceType(Decl);
6230 /// \brief Retrieve the template name that corresponds to a non-empty
6233 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6234 UnresolvedSetIterator End) const {
6235 unsigned size = End - Begin;
6236 assert(size > 1 && "set is not overloaded!");
6238 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6239 size * sizeof(FunctionTemplateDecl*));
6240 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6242 NamedDecl **Storage = OT->getStorage();
6243 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6245 assert(isa<FunctionTemplateDecl>(D) ||
6246 (isa<UsingShadowDecl>(D) &&
6247 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6251 return TemplateName(OT);
6254 /// \brief Retrieve the template name that represents a qualified
6255 /// template name such as \c std::vector.
6257 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6258 bool TemplateKeyword,
6259 TemplateDecl *Template) const {
6260 assert(NNS && "Missing nested-name-specifier in qualified template name");
6262 // FIXME: Canonicalization?
6263 llvm::FoldingSetNodeID ID;
6264 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6266 void *InsertPos = nullptr;
6267 QualifiedTemplateName *QTN =
6268 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6270 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6271 QualifiedTemplateName(NNS, TemplateKeyword, Template);
6272 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6275 return TemplateName(QTN);
6278 /// \brief Retrieve the template name that represents a dependent
6279 /// template name such as \c MetaFun::template apply.
6281 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6282 const IdentifierInfo *Name) const {
6283 assert((!NNS || NNS->isDependent()) &&
6284 "Nested name specifier must be dependent");
6286 llvm::FoldingSetNodeID ID;
6287 DependentTemplateName::Profile(ID, NNS, Name);
6289 void *InsertPos = nullptr;
6290 DependentTemplateName *QTN =
6291 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6294 return TemplateName(QTN);
6296 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6297 if (CanonNNS == NNS) {
6298 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6299 DependentTemplateName(NNS, Name);
6301 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6302 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6303 DependentTemplateName(NNS, Name, Canon);
6304 DependentTemplateName *CheckQTN =
6305 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6306 assert(!CheckQTN && "Dependent type name canonicalization broken");
6310 DependentTemplateNames.InsertNode(QTN, InsertPos);
6311 return TemplateName(QTN);
6314 /// \brief Retrieve the template name that represents a dependent
6315 /// template name such as \c MetaFun::template operator+.
6317 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6318 OverloadedOperatorKind Operator) const {
6319 assert((!NNS || NNS->isDependent()) &&
6320 "Nested name specifier must be dependent");
6322 llvm::FoldingSetNodeID ID;
6323 DependentTemplateName::Profile(ID, NNS, Operator);
6325 void *InsertPos = nullptr;
6326 DependentTemplateName *QTN
6327 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6330 return TemplateName(QTN);
6332 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6333 if (CanonNNS == NNS) {
6334 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6335 DependentTemplateName(NNS, Operator);
6337 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6338 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6339 DependentTemplateName(NNS, Operator, Canon);
6341 DependentTemplateName *CheckQTN
6342 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6343 assert(!CheckQTN && "Dependent template name canonicalization broken");
6347 DependentTemplateNames.InsertNode(QTN, InsertPos);
6348 return TemplateName(QTN);
6352 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6353 TemplateName replacement) const {
6354 llvm::FoldingSetNodeID ID;
6355 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6357 void *insertPos = nullptr;
6358 SubstTemplateTemplateParmStorage *subst
6359 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6362 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6363 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6366 return TemplateName(subst);
6370 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6371 const TemplateArgument &ArgPack) const {
6372 ASTContext &Self = const_cast<ASTContext &>(*this);
6373 llvm::FoldingSetNodeID ID;
6374 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6376 void *InsertPos = nullptr;
6377 SubstTemplateTemplateParmPackStorage *Subst
6378 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6381 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6382 ArgPack.pack_size(),
6383 ArgPack.pack_begin());
6384 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6387 return TemplateName(Subst);
6390 /// getFromTargetType - Given one of the integer types provided by
6391 /// TargetInfo, produce the corresponding type. The unsigned @p Type
6392 /// is actually a value of type @c TargetInfo::IntType.
6393 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6395 case TargetInfo::NoInt: return CanQualType();
6396 case TargetInfo::SignedChar: return SignedCharTy;
6397 case TargetInfo::UnsignedChar: return UnsignedCharTy;
6398 case TargetInfo::SignedShort: return ShortTy;
6399 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6400 case TargetInfo::SignedInt: return IntTy;
6401 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6402 case TargetInfo::SignedLong: return LongTy;
6403 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6404 case TargetInfo::SignedLongLong: return LongLongTy;
6405 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6408 llvm_unreachable("Unhandled TargetInfo::IntType value");
6411 //===----------------------------------------------------------------------===//
6413 //===----------------------------------------------------------------------===//
6415 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6416 /// garbage collection attribute.
6418 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6419 if (getLangOpts().getGC() == LangOptions::NonGC)
6420 return Qualifiers::GCNone;
6422 assert(getLangOpts().ObjC1);
6423 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6425 // Default behaviour under objective-C's gc is for ObjC pointers
6426 // (or pointers to them) be treated as though they were declared
6428 if (GCAttrs == Qualifiers::GCNone) {
6429 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6430 return Qualifiers::Strong;
6431 else if (Ty->isPointerType())
6432 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6434 // It's not valid to set GC attributes on anything that isn't a
6437 QualType CT = Ty->getCanonicalTypeInternal();
6438 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6439 CT = AT->getElementType();
6440 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6446 //===----------------------------------------------------------------------===//
6447 // Type Compatibility Testing
6448 //===----------------------------------------------------------------------===//
6450 /// areCompatVectorTypes - Return true if the two specified vector types are
6452 static bool areCompatVectorTypes(const VectorType *LHS,
6453 const VectorType *RHS) {
6454 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6455 return LHS->getElementType() == RHS->getElementType() &&
6456 LHS->getNumElements() == RHS->getNumElements();
6459 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6460 QualType SecondVec) {
6461 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6462 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6464 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6467 // Treat Neon vector types and most AltiVec vector types as if they are the
6468 // equivalent GCC vector types.
6469 const VectorType *First = FirstVec->getAs<VectorType>();
6470 const VectorType *Second = SecondVec->getAs<VectorType>();
6471 if (First->getNumElements() == Second->getNumElements() &&
6472 hasSameType(First->getElementType(), Second->getElementType()) &&
6473 First->getVectorKind() != VectorType::AltiVecPixel &&
6474 First->getVectorKind() != VectorType::AltiVecBool &&
6475 Second->getVectorKind() != VectorType::AltiVecPixel &&
6476 Second->getVectorKind() != VectorType::AltiVecBool)
6482 //===----------------------------------------------------------------------===//
6483 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6484 //===----------------------------------------------------------------------===//
6486 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6487 /// inheritance hierarchy of 'rProto'.
6489 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6490 ObjCProtocolDecl *rProto) const {
6491 if (declaresSameEntity(lProto, rProto))
6493 for (auto *PI : rProto->protocols())
6494 if (ProtocolCompatibleWithProtocol(lProto, PI))
6499 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6500 /// Class<pr1, ...>.
6501 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6503 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6504 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6505 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6507 for (auto *lhsProto : lhsQID->quals()) {
6509 for (auto *rhsProto : rhsOPT->quals()) {
6510 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6521 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6522 /// ObjCQualifiedIDType.
6523 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6525 // Allow id<P..> and an 'id' or void* type in all cases.
6526 if (lhs->isVoidPointerType() ||
6527 lhs->isObjCIdType() || lhs->isObjCClassType())
6529 else if (rhs->isVoidPointerType() ||
6530 rhs->isObjCIdType() || rhs->isObjCClassType())
6533 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6534 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6536 if (!rhsOPT) return false;
6538 if (rhsOPT->qual_empty()) {
6539 // If the RHS is a unqualified interface pointer "NSString*",
6540 // make sure we check the class hierarchy.
6541 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6542 for (auto *I : lhsQID->quals()) {
6543 // when comparing an id<P> on lhs with a static type on rhs,
6544 // see if static class implements all of id's protocols, directly or
6545 // through its super class and categories.
6546 if (!rhsID->ClassImplementsProtocol(I, true))
6550 // If there are no qualifiers and no interface, we have an 'id'.
6553 // Both the right and left sides have qualifiers.
6554 for (auto *lhsProto : lhsQID->quals()) {
6557 // when comparing an id<P> on lhs with a static type on rhs,
6558 // see if static class implements all of id's protocols, directly or
6559 // through its super class and categories.
6560 for (auto *rhsProto : rhsOPT->quals()) {
6561 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6562 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6567 // If the RHS is a qualified interface pointer "NSString<P>*",
6568 // make sure we check the class hierarchy.
6569 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6570 for (auto *I : lhsQID->quals()) {
6571 // when comparing an id<P> on lhs with a static type on rhs,
6572 // see if static class implements all of id's protocols, directly or
6573 // through its super class and categories.
6574 if (rhsID->ClassImplementsProtocol(I, true)) {
6587 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6588 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6590 if (const ObjCObjectPointerType *lhsOPT =
6591 lhs->getAsObjCInterfacePointerType()) {
6592 // If both the right and left sides have qualifiers.
6593 for (auto *lhsProto : lhsOPT->quals()) {
6596 // when comparing an id<P> on rhs with a static type on lhs,
6597 // see if static class implements all of id's protocols, directly or
6598 // through its super class and categories.
6599 // First, lhs protocols in the qualifier list must be found, direct
6600 // or indirect in rhs's qualifier list or it is a mismatch.
6601 for (auto *rhsProto : rhsQID->quals()) {
6602 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6603 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6612 // Static class's protocols, or its super class or category protocols
6613 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6614 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6615 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6616 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6617 // This is rather dubious but matches gcc's behavior. If lhs has
6618 // no type qualifier and its class has no static protocol(s)
6619 // assume that it is mismatch.
6620 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6622 for (auto *lhsProto : LHSInheritedProtocols) {
6624 for (auto *rhsProto : rhsQID->quals()) {
6625 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6626 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6640 /// canAssignObjCInterfaces - Return true if the two interface types are
6641 /// compatible for assignment from RHS to LHS. This handles validation of any
6642 /// protocol qualifiers on the LHS or RHS.
6644 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6645 const ObjCObjectPointerType *RHSOPT) {
6646 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6647 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6649 // If either type represents the built-in 'id' or 'Class' types, return true.
6650 if (LHS->isObjCUnqualifiedIdOrClass() ||
6651 RHS->isObjCUnqualifiedIdOrClass())
6654 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
6655 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6659 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6660 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6661 QualType(RHSOPT,0));
6663 // If we have 2 user-defined types, fall into that path.
6664 if (LHS->getInterface() && RHS->getInterface())
6665 return canAssignObjCInterfaces(LHS, RHS);
6670 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6671 /// for providing type-safety for objective-c pointers used to pass/return
6672 /// arguments in block literals. When passed as arguments, passing 'A*' where
6673 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6674 /// not OK. For the return type, the opposite is not OK.
6675 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6676 const ObjCObjectPointerType *LHSOPT,
6677 const ObjCObjectPointerType *RHSOPT,
6678 bool BlockReturnType) {
6679 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
6682 if (LHSOPT->isObjCBuiltinType()) {
6683 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6686 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
6687 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6691 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6692 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6693 if (LHS && RHS) { // We have 2 user-defined types.
6695 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
6696 return BlockReturnType;
6697 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
6698 return !BlockReturnType;
6706 /// getIntersectionOfProtocols - This routine finds the intersection of set
6707 /// of protocols inherited from two distinct objective-c pointer objects.
6708 /// It is used to build composite qualifier list of the composite type of
6709 /// the conditional expression involving two objective-c pointer objects.
6711 void getIntersectionOfProtocols(ASTContext &Context,
6712 const ObjCObjectPointerType *LHSOPT,
6713 const ObjCObjectPointerType *RHSOPT,
6714 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
6716 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6717 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6718 assert(LHS->getInterface() && "LHS must have an interface base");
6719 assert(RHS->getInterface() && "RHS must have an interface base");
6721 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6722 unsigned LHSNumProtocols = LHS->getNumProtocols();
6723 if (LHSNumProtocols > 0)
6724 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6726 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6727 Context.CollectInheritedProtocols(LHS->getInterface(),
6728 LHSInheritedProtocols);
6729 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6730 LHSInheritedProtocols.end());
6733 unsigned RHSNumProtocols = RHS->getNumProtocols();
6734 if (RHSNumProtocols > 0) {
6735 ObjCProtocolDecl **RHSProtocols =
6736 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
6737 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6738 if (InheritedProtocolSet.count(RHSProtocols[i]))
6739 IntersectionOfProtocols.push_back(RHSProtocols[i]);
6741 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
6742 Context.CollectInheritedProtocols(RHS->getInterface(),
6743 RHSInheritedProtocols);
6744 for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols)
6745 if (InheritedProtocolSet.count(ProtDecl))
6746 IntersectionOfProtocols.push_back(ProtDecl);
6750 /// areCommonBaseCompatible - Returns common base class of the two classes if
6751 /// one found. Note that this is O'2 algorithm. But it will be called as the
6752 /// last type comparison in a ?-exp of ObjC pointer types before a
6753 /// warning is issued. So, its invokation is extremely rare.
6754 QualType ASTContext::areCommonBaseCompatible(
6755 const ObjCObjectPointerType *Lptr,
6756 const ObjCObjectPointerType *Rptr) {
6757 const ObjCObjectType *LHS = Lptr->getObjectType();
6758 const ObjCObjectType *RHS = Rptr->getObjectType();
6759 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6760 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
6761 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
6765 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
6766 if (canAssignObjCInterfaces(LHS, RHS)) {
6767 SmallVector<ObjCProtocolDecl *, 8> Protocols;
6768 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6770 QualType Result = QualType(LHS, 0);
6771 if (!Protocols.empty())
6772 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6773 Result = getObjCObjectPointerType(Result);
6776 } while ((LDecl = LDecl->getSuperClass()));
6781 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6782 const ObjCObjectType *RHS) {
6783 assert(LHS->getInterface() && "LHS is not an interface type");
6784 assert(RHS->getInterface() && "RHS is not an interface type");
6786 // Verify that the base decls are compatible: the RHS must be a subclass of
6788 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
6791 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6792 // protocol qualified at all, then we are good.
6793 if (LHS->getNumProtocols() == 0)
6796 // Okay, we know the LHS has protocol qualifiers. But RHS may or may not.
6797 // More detailed analysis is required.
6798 // OK, if LHS is same or a superclass of RHS *and*
6799 // this LHS, or as RHS's super class is assignment compatible with LHS.
6801 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6803 // OK if conversion of LHS to SuperClass results in narrowing of types
6804 // ; i.e., SuperClass may implement at least one of the protocols
6805 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6806 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6807 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6808 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6809 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
6811 for (auto *RHSPI : RHS->quals())
6812 SuperClassInheritedProtocols.insert(RHSPI->getCanonicalDecl());
6813 // If there is no protocols associated with RHS, it is not a match.
6814 if (SuperClassInheritedProtocols.empty())
6817 for (const auto *LHSProto : LHS->quals()) {
6818 bool SuperImplementsProtocol = false;
6819 for (auto *SuperClassProto : SuperClassInheritedProtocols)
6820 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6821 SuperImplementsProtocol = true;
6824 if (!SuperImplementsProtocol)
6832 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6833 // get the "pointed to" types
6834 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6835 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
6837 if (!LHSOPT || !RHSOPT)
6840 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6841 canAssignObjCInterfaces(RHSOPT, LHSOPT);
6844 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6845 return canAssignObjCInterfaces(
6846 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6847 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6850 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
6851 /// both shall have the identically qualified version of a compatible type.
6852 /// C99 6.2.7p1: Two types have compatible types if their types are the
6853 /// same. See 6.7.[2,3,5] for additional rules.
6854 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6855 bool CompareUnqualified) {
6856 if (getLangOpts().CPlusPlus)
6857 return hasSameType(LHS, RHS);
6859 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
6862 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
6863 return typesAreCompatible(LHS, RHS);
6866 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6867 return !mergeTypes(LHS, RHS, true).isNull();
6870 /// mergeTransparentUnionType - if T is a transparent union type and a member
6871 /// of T is compatible with SubType, return the merged type, else return
6873 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6874 bool OfBlockPointer,
6876 if (const RecordType *UT = T->getAsUnionType()) {
6877 RecordDecl *UD = UT->getDecl();
6878 if (UD->hasAttr<TransparentUnionAttr>()) {
6879 for (const auto *I : UD->fields()) {
6880 QualType ET = I->getType().getUnqualifiedType();
6881 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6891 /// mergeFunctionParameterTypes - merge two types which appear as function
6893 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
6894 bool OfBlockPointer,
6896 // GNU extension: two types are compatible if they appear as a function
6897 // argument, one of the types is a transparent union type and the other
6898 // type is compatible with a union member
6899 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6901 if (!lmerge.isNull())
6904 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6906 if (!rmerge.isNull())
6909 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6912 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
6913 bool OfBlockPointer,
6915 const FunctionType *lbase = lhs->getAs<FunctionType>();
6916 const FunctionType *rbase = rhs->getAs<FunctionType>();
6917 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6918 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
6919 bool allLTypes = true;
6920 bool allRTypes = true;
6922 // Check return type
6924 if (OfBlockPointer) {
6925 QualType RHS = rbase->getReturnType();
6926 QualType LHS = lbase->getReturnType();
6927 bool UnqualifiedResult = Unqualified;
6928 if (!UnqualifiedResult)
6929 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
6930 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
6933 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
6935 if (retType.isNull()) return QualType();
6938 retType = retType.getUnqualifiedType();
6940 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
6941 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
6943 LRetType = LRetType.getUnqualifiedType();
6944 RRetType = RRetType.getUnqualifiedType();
6947 if (getCanonicalType(retType) != LRetType)
6949 if (getCanonicalType(retType) != RRetType)
6952 // FIXME: double check this
6953 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6954 // rbase->getRegParmAttr() != 0 &&
6955 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
6956 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6957 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
6959 // Compatible functions must have compatible calling conventions
6960 if (lbaseInfo.getCC() != rbaseInfo.getCC())
6963 // Regparm is part of the calling convention.
6964 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6966 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6969 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6972 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6973 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
6975 if (lbaseInfo.getNoReturn() != NoReturn)
6977 if (rbaseInfo.getNoReturn() != NoReturn)
6980 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
6982 if (lproto && rproto) { // two C99 style function prototypes
6983 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6984 "C++ shouldn't be here");
6985 // Compatible functions must have the same number of parameters
6986 if (lproto->getNumParams() != rproto->getNumParams())
6989 // Variadic and non-variadic functions aren't compatible
6990 if (lproto->isVariadic() != rproto->isVariadic())
6993 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6996 if (LangOpts.ObjCAutoRefCount &&
6997 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7000 // Check parameter type compatibility
7001 SmallVector<QualType, 10> types;
7002 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7003 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7004 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7005 QualType paramType = mergeFunctionParameterTypes(
7006 lParamType, rParamType, OfBlockPointer, Unqualified);
7007 if (paramType.isNull())
7011 paramType = paramType.getUnqualifiedType();
7013 types.push_back(paramType);
7015 lParamType = lParamType.getUnqualifiedType();
7016 rParamType = rParamType.getUnqualifiedType();
7019 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
7021 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
7025 if (allLTypes) return lhs;
7026 if (allRTypes) return rhs;
7028 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7029 EPI.ExtInfo = einfo;
7030 return getFunctionType(retType, types, EPI);
7033 if (lproto) allRTypes = false;
7034 if (rproto) allLTypes = false;
7036 const FunctionProtoType *proto = lproto ? lproto : rproto;
7038 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7039 if (proto->isVariadic()) return QualType();
7040 // Check that the types are compatible with the types that
7041 // would result from default argument promotions (C99 6.7.5.3p15).
7042 // The only types actually affected are promotable integer
7043 // types and floats, which would be passed as a different
7044 // type depending on whether the prototype is visible.
7045 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7046 QualType paramTy = proto->getParamType(i);
7048 // Look at the converted type of enum types, since that is the type used
7049 // to pass enum values.
7050 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7051 paramTy = Enum->getDecl()->getIntegerType();
7052 if (paramTy.isNull())
7056 if (paramTy->isPromotableIntegerType() ||
7057 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
7061 if (allLTypes) return lhs;
7062 if (allRTypes) return rhs;
7064 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7065 EPI.ExtInfo = einfo;
7066 return getFunctionType(retType, proto->getParamTypes(), EPI);
7069 if (allLTypes) return lhs;
7070 if (allRTypes) return rhs;
7071 return getFunctionNoProtoType(retType, einfo);
7074 /// Given that we have an enum type and a non-enum type, try to merge them.
7075 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7076 QualType other, bool isBlockReturnType) {
7077 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7078 // a signed integer type, or an unsigned integer type.
7079 // Compatibility is based on the underlying type, not the promotion
7081 QualType underlyingType = ET->getDecl()->getIntegerType();
7082 if (underlyingType.isNull()) return QualType();
7083 if (Context.hasSameType(underlyingType, other))
7086 // In block return types, we're more permissive and accept any
7087 // integral type of the same size.
7088 if (isBlockReturnType && other->isIntegerType() &&
7089 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7095 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
7096 bool OfBlockPointer,
7097 bool Unqualified, bool BlockReturnType) {
7098 // C++ [expr]: If an expression initially has the type "reference to T", the
7099 // type is adjusted to "T" prior to any further analysis, the expression
7100 // designates the object or function denoted by the reference, and the
7101 // expression is an lvalue unless the reference is an rvalue reference and
7102 // the expression is a function call (possibly inside parentheses).
7103 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7104 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
7107 LHS = LHS.getUnqualifiedType();
7108 RHS = RHS.getUnqualifiedType();
7111 QualType LHSCan = getCanonicalType(LHS),
7112 RHSCan = getCanonicalType(RHS);
7114 // If two types are identical, they are compatible.
7115 if (LHSCan == RHSCan)
7118 // If the qualifiers are different, the types aren't compatible... mostly.
7119 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7120 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7121 if (LQuals != RQuals) {
7122 // If any of these qualifiers are different, we have a type
7124 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7125 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7126 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
7129 // Exactly one GC qualifier difference is allowed: __strong is
7130 // okay if the other type has no GC qualifier but is an Objective
7131 // C object pointer (i.e. implicitly strong by default). We fix
7132 // this by pretending that the unqualified type was actually
7133 // qualified __strong.
7134 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7135 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7136 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7138 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7141 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7142 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7144 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7145 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7150 // Okay, qualifiers are equal.
7152 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7153 Type::TypeClass RHSClass = RHSCan->getTypeClass();
7155 // We want to consider the two function types to be the same for these
7156 // comparisons, just force one to the other.
7157 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7158 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
7160 // Same as above for arrays
7161 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7162 LHSClass = Type::ConstantArray;
7163 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7164 RHSClass = Type::ConstantArray;
7166 // ObjCInterfaces are just specialized ObjCObjects.
7167 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7168 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7170 // Canonicalize ExtVector -> Vector.
7171 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7172 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
7174 // If the canonical type classes don't match.
7175 if (LHSClass != RHSClass) {
7176 // Note that we only have special rules for turning block enum
7177 // returns into block int returns, not vice-versa.
7178 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
7179 return mergeEnumWithInteger(*this, ETy, RHS, false);
7181 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
7182 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
7184 // allow block pointer type to match an 'id' type.
7185 if (OfBlockPointer && !BlockReturnType) {
7186 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7188 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7195 // The canonical type classes match.
7197 #define TYPE(Class, Base)
7198 #define ABSTRACT_TYPE(Class, Base)
7199 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
7200 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7201 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
7202 #include "clang/AST/TypeNodes.def"
7203 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
7206 case Type::LValueReference:
7207 case Type::RValueReference:
7208 case Type::MemberPointer:
7209 llvm_unreachable("C++ should never be in mergeTypes");
7211 case Type::ObjCInterface:
7212 case Type::IncompleteArray:
7213 case Type::VariableArray:
7214 case Type::FunctionProto:
7215 case Type::ExtVector:
7216 llvm_unreachable("Types are eliminated above");
7220 // Merge two pointer types, while trying to preserve typedef info
7221 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7222 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
7224 LHSPointee = LHSPointee.getUnqualifiedType();
7225 RHSPointee = RHSPointee.getUnqualifiedType();
7227 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7229 if (ResultType.isNull()) return QualType();
7230 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7232 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7234 return getPointerType(ResultType);
7236 case Type::BlockPointer:
7238 // Merge two block pointer types, while trying to preserve typedef info
7239 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7240 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7242 LHSPointee = LHSPointee.getUnqualifiedType();
7243 RHSPointee = RHSPointee.getUnqualifiedType();
7245 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7247 if (ResultType.isNull()) return QualType();
7248 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7250 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7252 return getBlockPointerType(ResultType);
7256 // Merge two pointer types, while trying to preserve typedef info
7257 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7258 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7260 LHSValue = LHSValue.getUnqualifiedType();
7261 RHSValue = RHSValue.getUnqualifiedType();
7263 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7265 if (ResultType.isNull()) return QualType();
7266 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7268 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7270 return getAtomicType(ResultType);
7272 case Type::ConstantArray:
7274 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7275 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7276 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7279 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7280 QualType RHSElem = getAsArrayType(RHS)->getElementType();
7282 LHSElem = LHSElem.getUnqualifiedType();
7283 RHSElem = RHSElem.getUnqualifiedType();
7286 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7287 if (ResultType.isNull()) return QualType();
7288 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7290 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7292 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7293 ArrayType::ArraySizeModifier(), 0);
7294 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7295 ArrayType::ArraySizeModifier(), 0);
7296 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7297 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7298 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7300 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7303 // FIXME: This isn't correct! But tricky to implement because
7304 // the array's size has to be the size of LHS, but the type
7305 // has to be different.
7309 // FIXME: This isn't correct! But tricky to implement because
7310 // the array's size has to be the size of RHS, but the type
7311 // has to be different.
7314 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7315 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7316 return getIncompleteArrayType(ResultType,
7317 ArrayType::ArraySizeModifier(), 0);
7319 case Type::FunctionNoProto:
7320 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7325 // Only exactly equal builtin types are compatible, which is tested above.
7328 // Distinct complex types are incompatible.
7331 // FIXME: The merged type should be an ExtVector!
7332 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7333 RHSCan->getAs<VectorType>()))
7336 case Type::ObjCObject: {
7337 // Check if the types are assignment compatible.
7338 // FIXME: This should be type compatibility, e.g. whether
7339 // "LHS x; RHS x;" at global scope is legal.
7340 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7341 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7342 if (canAssignObjCInterfaces(LHSIface, RHSIface))
7347 case Type::ObjCObjectPointer: {
7348 if (OfBlockPointer) {
7349 if (canAssignObjCInterfacesInBlockPointer(
7350 LHS->getAs<ObjCObjectPointerType>(),
7351 RHS->getAs<ObjCObjectPointerType>(),
7356 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7357 RHS->getAs<ObjCObjectPointerType>()))
7364 llvm_unreachable("Invalid Type::Class!");
7367 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7368 const FunctionProtoType *FromFunctionType,
7369 const FunctionProtoType *ToFunctionType) {
7370 if (FromFunctionType->hasAnyConsumedParams() !=
7371 ToFunctionType->hasAnyConsumedParams())
7373 FunctionProtoType::ExtProtoInfo FromEPI =
7374 FromFunctionType->getExtProtoInfo();
7375 FunctionProtoType::ExtProtoInfo ToEPI =
7376 ToFunctionType->getExtProtoInfo();
7377 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
7378 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7379 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
7385 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7386 /// 'RHS' attributes and returns the merged version; including for function
7388 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7389 QualType LHSCan = getCanonicalType(LHS),
7390 RHSCan = getCanonicalType(RHS);
7391 // If two types are identical, they are compatible.
7392 if (LHSCan == RHSCan)
7394 if (RHSCan->isFunctionType()) {
7395 if (!LHSCan->isFunctionType())
7397 QualType OldReturnType =
7398 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
7399 QualType NewReturnType =
7400 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
7401 QualType ResReturnType =
7402 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7403 if (ResReturnType.isNull())
7405 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7406 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7407 // In either case, use OldReturnType to build the new function type.
7408 const FunctionType *F = LHS->getAs<FunctionType>();
7409 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7410 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7411 EPI.ExtInfo = getFunctionExtInfo(LHS);
7412 QualType ResultType =
7413 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
7420 // If the qualifiers are different, the types can still be merged.
7421 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7422 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7423 if (LQuals != RQuals) {
7424 // If any of these qualifiers are different, we have a type mismatch.
7425 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7426 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7429 // Exactly one GC qualifier difference is allowed: __strong is
7430 // okay if the other type has no GC qualifier but is an Objective
7431 // C object pointer (i.e. implicitly strong by default). We fix
7432 // this by pretending that the unqualified type was actually
7433 // qualified __strong.
7434 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7435 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7436 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7438 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7441 if (GC_L == Qualifiers::Strong)
7443 if (GC_R == Qualifiers::Strong)
7448 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7449 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7450 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7451 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7452 if (ResQT == LHSBaseQT)
7454 if (ResQT == RHSBaseQT)
7460 //===----------------------------------------------------------------------===//
7461 // Integer Predicates
7462 //===----------------------------------------------------------------------===//
7464 unsigned ASTContext::getIntWidth(QualType T) const {
7465 if (const EnumType *ET = T->getAs<EnumType>())
7466 T = ET->getDecl()->getIntegerType();
7467 if (T->isBooleanType())
7469 // For builtin types, just use the standard type sizing method
7470 return (unsigned)getTypeSize(T);
7473 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
7474 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
7476 // Turn <4 x signed int> -> <4 x unsigned int>
7477 if (const VectorType *VTy = T->getAs<VectorType>())
7478 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
7479 VTy->getNumElements(), VTy->getVectorKind());
7481 // For enums, we return the unsigned version of the base type.
7482 if (const EnumType *ETy = T->getAs<EnumType>())
7483 T = ETy->getDecl()->getIntegerType();
7485 const BuiltinType *BTy = T->getAs<BuiltinType>();
7486 assert(BTy && "Unexpected signed integer type");
7487 switch (BTy->getKind()) {
7488 case BuiltinType::Char_S:
7489 case BuiltinType::SChar:
7490 return UnsignedCharTy;
7491 case BuiltinType::Short:
7492 return UnsignedShortTy;
7493 case BuiltinType::Int:
7494 return UnsignedIntTy;
7495 case BuiltinType::Long:
7496 return UnsignedLongTy;
7497 case BuiltinType::LongLong:
7498 return UnsignedLongLongTy;
7499 case BuiltinType::Int128:
7500 return UnsignedInt128Ty;
7502 llvm_unreachable("Unexpected signed integer type");
7506 ASTMutationListener::~ASTMutationListener() { }
7508 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7509 QualType ReturnType) {}
7511 //===----------------------------------------------------------------------===//
7512 // Builtin Type Computation
7513 //===----------------------------------------------------------------------===//
7515 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
7516 /// pointer over the consumed characters. This returns the resultant type. If
7517 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7518 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7519 /// a vector of "i*".
7521 /// RequiresICE is filled in on return to indicate whether the value is required
7522 /// to be an Integer Constant Expression.
7523 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
7524 ASTContext::GetBuiltinTypeError &Error,
7526 bool AllowTypeModifiers) {
7529 bool Signed = false, Unsigned = false;
7530 RequiresICE = false;
7532 // Read the prefixed modifiers first.
7536 default: Done = true; --Str; break;
7541 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7542 assert(!Signed && "Can't use 'S' modifier multiple times!");
7546 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7547 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7551 assert(HowLong <= 2 && "Can't have LLLL modifier");
7555 // This modifier represents int64 type.
7556 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7557 switch (Context.getTargetInfo().getInt64Type()) {
7559 llvm_unreachable("Unexpected integer type");
7560 case TargetInfo::SignedLong:
7563 case TargetInfo::SignedLongLong:
7572 // Read the base type.
7574 default: llvm_unreachable("Unknown builtin type letter!");
7576 assert(HowLong == 0 && !Signed && !Unsigned &&
7577 "Bad modifiers used with 'v'!");
7578 Type = Context.VoidTy;
7581 assert(HowLong == 0 && !Signed && !Unsigned &&
7582 "Bad modifiers used with 'f'!");
7583 Type = Context.HalfTy;
7586 assert(HowLong == 0 && !Signed && !Unsigned &&
7587 "Bad modifiers used with 'f'!");
7588 Type = Context.FloatTy;
7591 assert(HowLong < 2 && !Signed && !Unsigned &&
7592 "Bad modifiers used with 'd'!");
7594 Type = Context.LongDoubleTy;
7596 Type = Context.DoubleTy;
7599 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7601 Type = Context.UnsignedShortTy;
7603 Type = Context.ShortTy;
7607 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7608 else if (HowLong == 2)
7609 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7610 else if (HowLong == 1)
7611 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7613 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7616 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7618 Type = Context.SignedCharTy;
7620 Type = Context.UnsignedCharTy;
7622 Type = Context.CharTy;
7624 case 'b': // boolean
7625 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7626 Type = Context.BoolTy;
7628 case 'z': // size_t.
7629 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7630 Type = Context.getSizeType();
7633 Type = Context.getCFConstantStringType();
7636 Type = Context.getObjCIdType();
7639 Type = Context.getObjCSelType();
7642 Type = Context.getObjCSuperType();
7645 Type = Context.getBuiltinVaListType();
7646 assert(!Type.isNull() && "builtin va list type not initialized!");
7649 // This is a "reference" to a va_list; however, what exactly
7650 // this means depends on how va_list is defined. There are two
7651 // different kinds of va_list: ones passed by value, and ones
7652 // passed by reference. An example of a by-value va_list is
7653 // x86, where va_list is a char*. An example of by-ref va_list
7654 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7655 // we want this argument to be a char*&; for x86-64, we want
7656 // it to be a __va_list_tag*.
7657 Type = Context.getBuiltinVaListType();
7658 assert(!Type.isNull() && "builtin va list type not initialized!");
7659 if (Type->isArrayType())
7660 Type = Context.getArrayDecayedType(Type);
7662 Type = Context.getLValueReferenceType(Type);
7666 unsigned NumElements = strtoul(Str, &End, 10);
7667 assert(End != Str && "Missing vector size");
7670 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7671 RequiresICE, false);
7672 assert(!RequiresICE && "Can't require vector ICE");
7674 // TODO: No way to make AltiVec vectors in builtins yet.
7675 Type = Context.getVectorType(ElementType, NumElements,
7676 VectorType::GenericVector);
7682 unsigned NumElements = strtoul(Str, &End, 10);
7683 assert(End != Str && "Missing vector size");
7687 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7689 Type = Context.getExtVectorType(ElementType, NumElements);
7693 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7695 assert(!RequiresICE && "Can't require complex ICE");
7696 Type = Context.getComplexType(ElementType);
7700 Type = Context.getPointerDiffType();
7704 Type = Context.getFILEType();
7705 if (Type.isNull()) {
7706 Error = ASTContext::GE_Missing_stdio;
7712 Type = Context.getsigjmp_bufType();
7714 Type = Context.getjmp_bufType();
7716 if (Type.isNull()) {
7717 Error = ASTContext::GE_Missing_setjmp;
7722 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7723 Type = Context.getucontext_tType();
7725 if (Type.isNull()) {
7726 Error = ASTContext::GE_Missing_ucontext;
7731 Type = Context.getProcessIDType();
7735 // If there are modifiers and if we're allowed to parse them, go for it.
7736 Done = !AllowTypeModifiers;
7738 switch (char c = *Str++) {
7739 default: Done = true; --Str; break;
7742 // Both pointers and references can have their pointee types
7743 // qualified with an address space.
7745 unsigned AddrSpace = strtoul(Str, &End, 10);
7746 if (End != Str && AddrSpace != 0) {
7747 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7751 Type = Context.getPointerType(Type);
7753 Type = Context.getLValueReferenceType(Type);
7756 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7758 Type = Type.withConst();
7761 Type = Context.getVolatileType(Type);
7764 Type = Type.withRestrict();
7769 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
7770 "Integer constant 'I' type must be an integer");
7775 /// GetBuiltinType - Return the type for the specified builtin.
7776 QualType ASTContext::GetBuiltinType(unsigned Id,
7777 GetBuiltinTypeError &Error,
7778 unsigned *IntegerConstantArgs) const {
7779 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
7781 SmallVector<QualType, 8> ArgTypes;
7783 bool RequiresICE = false;
7785 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7787 if (Error != GE_None)
7790 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7792 while (TypeStr[0] && TypeStr[0] != '.') {
7793 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
7794 if (Error != GE_None)
7797 // If this argument is required to be an IntegerConstantExpression and the
7798 // caller cares, fill in the bitmask we return.
7799 if (RequiresICE && IntegerConstantArgs)
7800 *IntegerConstantArgs |= 1 << ArgTypes.size();
7802 // Do array -> pointer decay. The builtin should use the decayed type.
7803 if (Ty->isArrayType())
7804 Ty = getArrayDecayedType(Ty);
7806 ArgTypes.push_back(Ty);
7809 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7810 "'.' should only occur at end of builtin type list!");
7812 FunctionType::ExtInfo EI(CC_C);
7813 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7815 bool Variadic = (TypeStr[0] == '.');
7817 // We really shouldn't be making a no-proto type here, especially in C++.
7818 if (ArgTypes.empty() && Variadic)
7819 return getFunctionNoProtoType(ResType, EI);
7821 FunctionProtoType::ExtProtoInfo EPI;
7823 EPI.Variadic = Variadic;
7825 return getFunctionType(ResType, ArgTypes, EPI);
7828 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
7829 const FunctionDecl *FD) {
7830 if (!FD->isExternallyVisible())
7831 return GVA_Internal;
7833 GVALinkage External = GVA_StrongExternal;
7834 switch (FD->getTemplateSpecializationKind()) {
7835 case TSK_Undeclared:
7836 case TSK_ExplicitSpecialization:
7837 External = GVA_StrongExternal;
7840 case TSK_ExplicitInstantiationDefinition:
7841 return GVA_StrongODR;
7843 // C++11 [temp.explicit]p10:
7844 // [ Note: The intent is that an inline function that is the subject of
7845 // an explicit instantiation declaration will still be implicitly
7846 // instantiated when used so that the body can be considered for
7847 // inlining, but that no out-of-line copy of the inline function would be
7848 // generated in the translation unit. -- end note ]
7849 case TSK_ExplicitInstantiationDeclaration:
7850 return GVA_AvailableExternally;
7852 case TSK_ImplicitInstantiation:
7853 External = GVA_DiscardableODR;
7857 if (!FD->isInlined())
7860 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
7861 !FD->hasAttr<DLLExportAttr>()) ||
7862 FD->hasAttr<GNUInlineAttr>()) {
7863 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
7865 // GNU or C99 inline semantics. Determine whether this symbol should be
7866 // externally visible.
7867 if (FD->isInlineDefinitionExternallyVisible())
7870 // C99 inline semantics, where the symbol is not externally visible.
7871 return GVA_AvailableExternally;
7874 // Functions specified with extern and inline in -fms-compatibility mode
7875 // forcibly get emitted. While the body of the function cannot be later
7876 // replaced, the function definition cannot be discarded.
7877 if (FD->isMSExternInline())
7878 return GVA_StrongODR;
7880 return GVA_DiscardableODR;
7883 static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
7884 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
7885 // dllexport/dllimport on inline functions.
7886 if (D->hasAttr<DLLImportAttr>()) {
7887 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
7888 return GVA_AvailableExternally;
7889 } else if (D->hasAttr<DLLExportAttr>()) {
7890 if (L == GVA_DiscardableODR)
7891 return GVA_StrongODR;
7896 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
7897 return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
7901 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
7902 const VarDecl *VD) {
7903 if (!VD->isExternallyVisible())
7904 return GVA_Internal;
7906 if (VD->isStaticLocal()) {
7907 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
7908 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
7909 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
7910 LexicalContext = LexicalContext->getLexicalParent();
7912 // Let the static local variable inherit it's linkage from the nearest
7913 // enclosing function.
7915 StaticLocalLinkage =
7916 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
7918 // GVA_StrongODR function linkage is stronger than what we need,
7919 // downgrade to GVA_DiscardableODR.
7920 // This allows us to discard the variable if we never end up needing it.
7921 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
7922 : StaticLocalLinkage;
7925 // MSVC treats in-class initialized static data members as definitions.
7926 // By giving them non-strong linkage, out-of-line definitions won't
7927 // cause link errors.
7928 if (Context.isMSStaticDataMemberInlineDefinition(VD))
7929 return GVA_DiscardableODR;
7931 switch (VD->getTemplateSpecializationKind()) {
7932 case TSK_Undeclared:
7933 case TSK_ExplicitSpecialization:
7934 return GVA_StrongExternal;
7936 case TSK_ExplicitInstantiationDefinition:
7937 return GVA_StrongODR;
7939 case TSK_ExplicitInstantiationDeclaration:
7940 return GVA_AvailableExternally;
7942 case TSK_ImplicitInstantiation:
7943 return GVA_DiscardableODR;
7946 llvm_unreachable("Invalid Linkage!");
7949 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7950 return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
7954 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
7955 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7956 if (!VD->isFileVarDecl())
7958 // Global named register variables (GNU extension) are never emitted.
7959 if (VD->getStorageClass() == SC_Register)
7961 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7962 // We never need to emit an uninstantiated function template.
7963 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7965 } else if (isa<OMPThreadPrivateDecl>(D))
7970 // If this is a member of a class template, we do not need to emit it.
7971 if (D->getDeclContext()->isDependentContext())
7974 // Weak references don't produce any output by themselves.
7975 if (D->hasAttr<WeakRefAttr>())
7978 // Aliases and used decls are required.
7979 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7982 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7983 // Forward declarations aren't required.
7984 if (!FD->doesThisDeclarationHaveABody())
7985 return FD->doesDeclarationForceExternallyVisibleDefinition();
7987 // Constructors and destructors are required.
7988 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7991 // The key function for a class is required. This rule only comes
7992 // into play when inline functions can be key functions, though.
7993 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7994 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7995 const CXXRecordDecl *RD = MD->getParent();
7996 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7997 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7998 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8004 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8006 // static, static inline, always_inline, and extern inline functions can
8007 // always be deferred. Normal inline functions can be deferred in C99/C++.
8008 // Implicit template instantiations can also be deferred in C++.
8009 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8010 Linkage == GVA_DiscardableODR)
8015 const VarDecl *VD = cast<VarDecl>(D);
8016 assert(VD->isFileVarDecl() && "Expected file scoped var");
8018 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8019 !isMSStaticDataMemberInlineDefinition(VD))
8022 // Variables that can be needed in other TUs are required.
8023 GVALinkage L = GetGVALinkageForVariable(VD);
8024 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8025 L != GVA_DiscardableODR)
8028 // Variables that have destruction with side-effects are required.
8029 if (VD->getType().isDestructedType())
8032 // Variables that have initialization with side-effects are required.
8033 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
8039 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8040 bool IsCXXMethod) const {
8041 // Pass through to the C++ ABI object
8043 return ABI->getDefaultMethodCallConv(IsVariadic);
8045 return (LangOpts.MRTD && !IsVariadic) ? CC_X86StdCall : CC_C;
8048 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
8049 // Pass through to the C++ ABI object
8050 return ABI->isNearlyEmpty(RD);
8053 VTableContextBase *ASTContext::getVTableContext() {
8054 if (!VTContext.get()) {
8055 if (Target->getCXXABI().isMicrosoft())
8056 VTContext.reset(new MicrosoftVTableContext(*this));
8058 VTContext.reset(new ItaniumVTableContext(*this));
8060 return VTContext.get();
8063 MangleContext *ASTContext::createMangleContext() {
8064 switch (Target->getCXXABI().getKind()) {
8065 case TargetCXXABI::GenericAArch64:
8066 case TargetCXXABI::GenericItanium:
8067 case TargetCXXABI::GenericARM:
8068 case TargetCXXABI::GenericMIPS:
8069 case TargetCXXABI::iOS:
8070 case TargetCXXABI::iOS64:
8071 return ItaniumMangleContext::create(*this, getDiagnostics());
8072 case TargetCXXABI::Microsoft:
8073 return MicrosoftMangleContext::create(*this, getDiagnostics());
8075 llvm_unreachable("Unsupported ABI");
8078 CXXABI::~CXXABI() {}
8080 size_t ASTContext::getSideTableAllocatedMemory() const {
8081 return ASTRecordLayouts.getMemorySize() +
8082 llvm::capacity_in_bytes(ObjCLayouts) +
8083 llvm::capacity_in_bytes(KeyFunctions) +
8084 llvm::capacity_in_bytes(ObjCImpls) +
8085 llvm::capacity_in_bytes(BlockVarCopyInits) +
8086 llvm::capacity_in_bytes(DeclAttrs) +
8087 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8088 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8089 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8090 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8091 llvm::capacity_in_bytes(OverriddenMethods) +
8092 llvm::capacity_in_bytes(Types) +
8093 llvm::capacity_in_bytes(VariableArrayTypes) +
8094 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
8097 /// getIntTypeForBitwidth -
8098 /// sets integer QualTy according to specified details:
8099 /// bitwidth, signed/unsigned.
8100 /// Returns empty type if there is no appropriate target types.
8101 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8102 unsigned Signed) const {
8103 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8104 CanQualType QualTy = getFromTargetType(Ty);
8105 if (!QualTy && DestWidth == 128)
8106 return Signed ? Int128Ty : UnsignedInt128Ty;
8110 /// getRealTypeForBitwidth -
8111 /// sets floating point QualTy according to specified bitwidth.
8112 /// Returns empty type if there is no appropriate target types.
8113 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8114 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8116 case TargetInfo::Float:
8118 case TargetInfo::Double:
8120 case TargetInfo::LongDouble:
8121 return LongDoubleTy;
8122 case TargetInfo::NoFloat:
8126 llvm_unreachable("Unhandled TargetInfo::RealType value");
8129 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8131 MangleNumbers[ND] = Number;
8134 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8135 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8136 MangleNumbers.find(ND);
8137 return I != MangleNumbers.end() ? I->second : 1;
8140 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8142 StaticLocalNumbers[VD] = Number;
8145 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8146 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8147 StaticLocalNumbers.find(VD);
8148 return I != StaticLocalNumbers.end() ? I->second : 1;
8151 MangleNumberingContext &
8152 ASTContext::getManglingNumberContext(const DeclContext *DC) {
8153 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8154 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8156 MCtx = createMangleNumberingContext();
8160 MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8161 return ABI->createMangleNumberingContext();
8164 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8165 ParamIndices[D] = index;
8168 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8169 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8170 assert(I != ParamIndices.end() &&
8171 "ParmIndices lacks entry set by ParmVarDecl");
8176 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8178 assert(E && E->getStorageDuration() == SD_Static &&
8179 "don't need to cache the computed value for this temporary");
8181 return &MaterializedTemporaryValues[E];
8183 llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8184 MaterializedTemporaryValues.find(E);
8185 return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
8188 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8189 const llvm::Triple &T = getTargetInfo().getTriple();
8190 if (!T.isOSDarwin())
8193 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8194 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8197 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8198 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8199 uint64_t Size = sizeChars.getQuantity();
8200 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8201 unsigned Align = alignChars.getQuantity();
8202 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8203 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8208 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8209 /// parents as defined by the \c RecursiveASTVisitor.
8211 /// Note that the relationship described here is purely in terms of AST
8212 /// traversal - there are other relationships (for example declaration context)
8213 /// in the AST that are better modeled by special matchers.
8215 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8216 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8219 /// \brief Builds and returns the translation unit's parent map.
8221 /// The caller takes ownership of the returned \c ParentMap.
8222 static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8223 ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8224 Visitor.TraverseDecl(&TU);
8225 return Visitor.Parents;
8229 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8231 ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8234 bool shouldVisitTemplateInstantiations() const {
8237 bool shouldVisitImplicitCode() const {
8240 // Disables data recursion. We intercept Traverse* methods in the RAV, which
8241 // are not triggered during data recursion.
8242 bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8246 template <typename T>
8247 bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8250 if (ParentStack.size() > 0) {
8251 // FIXME: Currently we add the same parent multiple times, but only
8252 // when no memoization data is available for the type.
8253 // For example when we visit all subexpressions of template
8254 // instantiations; this is suboptimal, but benign: the only way to
8255 // visit those is with hasAncestor / hasParent, and those do not create
8257 // The plan is to enable DynTypedNode to be storable in a map or hash
8258 // map. The main problem there is to implement hash functions /
8259 // comparison operators for all types that DynTypedNode supports that
8260 // do not have pointer identity.
8261 auto &NodeOrVector = (*Parents)[Node];
8262 if (NodeOrVector.isNull()) {
8263 NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
8265 if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8267 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8268 auto *Vector = new ASTContext::ParentVector(1, *Node);
8269 NodeOrVector = Vector;
8272 assert(NodeOrVector.template is<ASTContext::ParentVector *>());
8275 NodeOrVector.template get<ASTContext::ParentVector *>();
8276 // Skip duplicates for types that have memoization data.
8277 // We must check that the type has memoization data before calling
8278 // std::find() because DynTypedNode::operator== can't compare all
8280 bool Found = ParentStack.back().getMemoizationData() &&
8281 std::find(Vector->begin(), Vector->end(),
8282 ParentStack.back()) != Vector->end();
8284 Vector->push_back(ParentStack.back());
8287 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8288 bool Result = (this ->* traverse) (Node);
8289 ParentStack.pop_back();
8293 bool TraverseDecl(Decl *DeclNode) {
8294 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8297 bool TraverseStmt(Stmt *StmtNode) {
8298 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8301 ASTContext::ParentMap *Parents;
8302 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8304 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8309 ArrayRef<ast_type_traits::DynTypedNode>
8310 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8311 assert(Node.getMemoizationData() &&
8312 "Invariant broken: only nodes that support memoization may be "
8313 "used in the parent map.");
8315 // We always need to run over the whole translation unit, as
8316 // hasAncestor can escape any subtree.
8318 ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8320 ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8321 if (I == AllParents->end()) {
8324 if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8325 return llvm::makeArrayRef(N, 1);
8327 return *I->second.get<ParentVector *>();
8331 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8332 const ObjCMethodDecl *MethodImpl) {
8333 // No point trying to match an unavailable/deprecated mothod.
8334 if (MethodDecl->hasAttr<UnavailableAttr>()
8335 || MethodDecl->hasAttr<DeprecatedAttr>())
8337 if (MethodDecl->getObjCDeclQualifier() !=
8338 MethodImpl->getObjCDeclQualifier())
8340 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
8343 if (MethodDecl->param_size() != MethodImpl->param_size())
8346 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8347 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8348 EF = MethodDecl->param_end();
8349 IM != EM && IF != EF; ++IM, ++IF) {
8350 const ParmVarDecl *DeclVar = (*IF);
8351 const ParmVarDecl *ImplVar = (*IM);
8352 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8354 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8357 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8361 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8362 // doesn't include ASTContext.h
8364 clang::LazyGenerationalUpdatePtr<
8365 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8366 clang::LazyGenerationalUpdatePtr<
8367 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8368 const clang::ASTContext &Ctx, Decl *Value);