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/DeclContextInternals.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExternalASTSource.h"
28 #include "clang/AST/Mangle.h"
29 #include "clang/AST/MangleNumberingContext.h"
30 #include "clang/AST/RecordLayout.h"
31 #include "clang/AST/RecursiveASTVisitor.h"
32 #include "clang/AST/TypeLoc.h"
33 #include "clang/AST/VTableBuilder.h"
34 #include "clang/Basic/Builtins.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/Support/Capacity.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/raw_ostream.h"
45 using namespace clang;
47 unsigned ASTContext::NumImplicitDefaultConstructors;
48 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
49 unsigned ASTContext::NumImplicitCopyConstructors;
50 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
51 unsigned ASTContext::NumImplicitMoveConstructors;
52 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
53 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
54 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
55 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
56 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
57 unsigned ASTContext::NumImplicitDestructors;
58 unsigned ASTContext::NumImplicitDestructorsDeclared;
61 HalfRank, FloatRank, DoubleRank, LongDoubleRank
64 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
65 if (!CommentsLoaded && ExternalSource) {
66 ExternalSource->ReadComments();
69 ArrayRef<RawComment *> RawComments = Comments.getComments();
70 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
71 BeforeThanCompare<RawComment>(SourceMgr)));
74 CommentsLoaded = true;
79 // User can not attach documentation to implicit declarations.
83 // User can not attach documentation to implicit instantiations.
84 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
85 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
89 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
90 if (VD->isStaticDataMember() &&
91 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
95 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
96 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
100 if (const ClassTemplateSpecializationDecl *CTSD =
101 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
102 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
103 if (TSK == TSK_ImplicitInstantiation ||
104 TSK == TSK_Undeclared)
108 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
109 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
112 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
113 // When tag declaration (but not definition!) is part of the
114 // decl-specifier-seq of some other declaration, it doesn't get comment
115 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
118 // TODO: handle comments for function parameters properly.
119 if (isa<ParmVarDecl>(D))
122 // TODO: we could look up template parameter documentation in the template
124 if (isa<TemplateTypeParmDecl>(D) ||
125 isa<NonTypeTemplateParmDecl>(D) ||
126 isa<TemplateTemplateParmDecl>(D))
129 ArrayRef<RawComment *> RawComments = Comments.getComments();
131 // If there are no comments anywhere, we won't find anything.
132 if (RawComments.empty())
135 // Find declaration location.
136 // For Objective-C declarations we generally don't expect to have multiple
137 // declarators, thus use declaration starting location as the "declaration
139 // For all other declarations multiple declarators are used quite frequently,
140 // so we use the location of the identifier as the "declaration location".
141 SourceLocation DeclLoc;
142 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
143 isa<ObjCPropertyDecl>(D) ||
144 isa<RedeclarableTemplateDecl>(D) ||
145 isa<ClassTemplateSpecializationDecl>(D))
146 DeclLoc = D->getLocStart();
148 DeclLoc = D->getLocation();
149 if (DeclLoc.isMacroID()) {
150 if (isa<TypedefDecl>(D)) {
151 // If location of the typedef name is in a macro, it is because being
152 // declared via a macro. Try using declaration's starting location as
153 // the "declaration location".
154 DeclLoc = D->getLocStart();
155 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
156 // If location of the tag decl is inside a macro, but the spelling of
157 // the tag name comes from a macro argument, it looks like a special
158 // macro like NS_ENUM is being used to define the tag decl. In that
159 // case, adjust the source location to the expansion loc so that we can
160 // attach the comment to the tag decl.
161 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
162 TD->isCompleteDefinition())
163 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
168 // If the declaration doesn't map directly to a location in a file, we
169 // can't find the comment.
170 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
173 // Find the comment that occurs just after this declaration.
174 ArrayRef<RawComment *>::iterator Comment;
176 // When searching for comments during parsing, the comment we are looking
177 // for is usually among the last two comments we parsed -- check them
179 RawComment CommentAtDeclLoc(
180 SourceMgr, SourceRange(DeclLoc), false,
181 LangOpts.CommentOpts.ParseAllComments);
182 BeforeThanCompare<RawComment> Compare(SourceMgr);
183 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
184 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
185 if (!Found && RawComments.size() >= 2) {
187 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
191 Comment = MaybeBeforeDecl + 1;
192 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
193 &CommentAtDeclLoc, Compare));
196 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
197 &CommentAtDeclLoc, Compare);
201 // Decompose the location for the declaration and find the beginning of the
203 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
205 // First check whether we have a trailing comment.
206 if (Comment != RawComments.end() &&
207 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
208 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
209 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
210 std::pair<FileID, unsigned> CommentBeginDecomp
211 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
212 // Check that Doxygen trailing comment comes after the declaration, starts
213 // on the same line and in the same file as the declaration.
214 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
215 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
216 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
217 CommentBeginDecomp.second)) {
222 // The comment just after the declaration was not a trailing comment.
223 // Let's look at the previous comment.
224 if (Comment == RawComments.begin())
228 // Check that we actually have a non-member Doxygen comment.
229 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
232 // Decompose the end of the comment.
233 std::pair<FileID, unsigned> CommentEndDecomp
234 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
236 // If the comment and the declaration aren't in the same file, then they
238 if (DeclLocDecomp.first != CommentEndDecomp.first)
241 // Get the corresponding buffer.
242 bool Invalid = false;
243 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
248 // Extract text between the comment and declaration.
249 StringRef Text(Buffer + CommentEndDecomp.second,
250 DeclLocDecomp.second - CommentEndDecomp.second);
252 // There should be no other declarations or preprocessor directives between
253 // comment and declaration.
254 if (Text.find_first_of(";{}#@") != StringRef::npos)
261 /// If we have a 'templated' declaration for a template, adjust 'D' to
262 /// refer to the actual template.
263 /// If we have an implicit instantiation, adjust 'D' to refer to template.
264 const Decl *adjustDeclToTemplate(const Decl *D) {
265 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
266 // Is this function declaration part of a function template?
267 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
270 // Nothing to do if function is not an implicit instantiation.
271 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
274 // Function is an implicit instantiation of a function template?
275 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
278 // Function is instantiated from a member definition of a class template?
279 if (const FunctionDecl *MemberDecl =
280 FD->getInstantiatedFromMemberFunction())
285 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
286 // Static data member is instantiated from a member definition of a class
288 if (VD->isStaticDataMember())
289 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
294 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
295 // Is this class declaration part of a class template?
296 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
299 // Class is an implicit instantiation of a class template or partial
301 if (const ClassTemplateSpecializationDecl *CTSD =
302 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
303 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
305 llvm::PointerUnion<ClassTemplateDecl *,
306 ClassTemplatePartialSpecializationDecl *>
307 PU = CTSD->getSpecializedTemplateOrPartial();
308 return PU.is<ClassTemplateDecl*>() ?
309 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
310 static_cast<const Decl*>(
311 PU.get<ClassTemplatePartialSpecializationDecl *>());
314 // Class is instantiated from a member definition of a class template?
315 if (const MemberSpecializationInfo *Info =
316 CRD->getMemberSpecializationInfo())
317 return Info->getInstantiatedFrom();
321 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
322 // Enum is instantiated from a member definition of a class template?
323 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
328 // FIXME: Adjust alias templates?
331 } // anonymous namespace
333 const RawComment *ASTContext::getRawCommentForAnyRedecl(
335 const Decl **OriginalDecl) const {
336 D = adjustDeclToTemplate(D);
338 // Check whether we have cached a comment for this declaration already.
340 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
341 RedeclComments.find(D);
342 if (Pos != RedeclComments.end()) {
343 const RawCommentAndCacheFlags &Raw = Pos->second;
344 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
346 *OriginalDecl = Raw.getOriginalDecl();
352 // Search for comments attached to declarations in the redeclaration chain.
353 const RawComment *RC = nullptr;
354 const Decl *OriginalDeclForRC = nullptr;
355 for (auto I : D->redecls()) {
356 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
357 RedeclComments.find(I);
358 if (Pos != RedeclComments.end()) {
359 const RawCommentAndCacheFlags &Raw = Pos->second;
360 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
362 OriginalDeclForRC = Raw.getOriginalDecl();
366 RC = getRawCommentForDeclNoCache(I);
367 OriginalDeclForRC = I;
368 RawCommentAndCacheFlags Raw;
370 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
371 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
372 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
375 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
376 Raw.setOriginalDecl(I);
377 RedeclComments[I] = Raw;
383 // If we found a comment, it should be a documentation comment.
384 assert(!RC || RC->isDocumentation());
387 *OriginalDecl = OriginalDeclForRC;
389 // Update cache for every declaration in the redeclaration chain.
390 RawCommentAndCacheFlags Raw;
392 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
393 Raw.setOriginalDecl(OriginalDeclForRC);
395 for (auto I : D->redecls()) {
396 RawCommentAndCacheFlags &R = RedeclComments[I];
397 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
404 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
405 SmallVectorImpl<const NamedDecl *> &Redeclared) {
406 const DeclContext *DC = ObjCMethod->getDeclContext();
407 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
408 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
411 // Add redeclared method here.
412 for (const auto *Ext : ID->known_extensions()) {
413 if (ObjCMethodDecl *RedeclaredMethod =
414 Ext->getMethod(ObjCMethod->getSelector(),
415 ObjCMethod->isInstanceMethod()))
416 Redeclared.push_back(RedeclaredMethod);
421 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
422 const Decl *D) const {
423 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
424 ThisDeclInfo->CommentDecl = D;
425 ThisDeclInfo->IsFilled = false;
426 ThisDeclInfo->fill();
427 ThisDeclInfo->CommentDecl = FC->getDecl();
428 if (!ThisDeclInfo->TemplateParameters)
429 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
430 comments::FullComment *CFC =
431 new (*this) comments::FullComment(FC->getBlocks(),
436 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
437 const RawComment *RC = getRawCommentForDeclNoCache(D);
438 return RC ? RC->parse(*this, nullptr, D) : nullptr;
441 comments::FullComment *ASTContext::getCommentForDecl(
443 const Preprocessor *PP) const {
444 if (D->isInvalidDecl())
446 D = adjustDeclToTemplate(D);
448 const Decl *Canonical = D->getCanonicalDecl();
449 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
450 ParsedComments.find(Canonical);
452 if (Pos != ParsedComments.end()) {
453 if (Canonical != D) {
454 comments::FullComment *FC = Pos->second;
455 comments::FullComment *CFC = cloneFullComment(FC, D);
461 const Decl *OriginalDecl;
463 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
465 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
466 SmallVector<const NamedDecl*, 8> Overridden;
467 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
468 if (OMD && OMD->isPropertyAccessor())
469 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
470 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
471 return cloneFullComment(FC, D);
473 addRedeclaredMethods(OMD, Overridden);
474 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
475 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
476 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
477 return cloneFullComment(FC, D);
479 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
480 // Attach any tag type's documentation to its typedef if latter
481 // does not have one of its own.
482 QualType QT = TD->getUnderlyingType();
483 if (const TagType *TT = QT->getAs<TagType>())
484 if (const Decl *TD = TT->getDecl())
485 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
486 return cloneFullComment(FC, D);
488 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
489 while (IC->getSuperClass()) {
490 IC = IC->getSuperClass();
491 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
492 return cloneFullComment(FC, D);
495 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
496 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
497 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
498 return cloneFullComment(FC, D);
500 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
501 if (!(RD = RD->getDefinition()))
503 // Check non-virtual bases.
504 for (const auto &I : RD->bases()) {
505 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
507 QualType Ty = I.getType();
510 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
511 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
514 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
515 return cloneFullComment(FC, D);
518 // Check virtual bases.
519 for (const auto &I : RD->vbases()) {
520 if (I.getAccessSpecifier() != AS_public)
522 QualType Ty = I.getType();
525 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
526 if (!(VirtualBase= VirtualBase->getDefinition()))
528 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
529 return cloneFullComment(FC, D);
536 // If the RawComment was attached to other redeclaration of this Decl, we
537 // should parse the comment in context of that other Decl. This is important
538 // because comments can contain references to parameter names which can be
539 // different across redeclarations.
540 if (D != OriginalDecl)
541 return getCommentForDecl(OriginalDecl, PP);
543 comments::FullComment *FC = RC->parse(*this, PP, D);
544 ParsedComments[Canonical] = FC;
549 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
550 TemplateTemplateParmDecl *Parm) {
551 ID.AddInteger(Parm->getDepth());
552 ID.AddInteger(Parm->getPosition());
553 ID.AddBoolean(Parm->isParameterPack());
555 TemplateParameterList *Params = Parm->getTemplateParameters();
556 ID.AddInteger(Params->size());
557 for (TemplateParameterList::const_iterator P = Params->begin(),
558 PEnd = Params->end();
560 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
562 ID.AddBoolean(TTP->isParameterPack());
566 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
568 ID.AddBoolean(NTTP->isParameterPack());
569 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
570 if (NTTP->isExpandedParameterPack()) {
572 ID.AddInteger(NTTP->getNumExpansionTypes());
573 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
574 QualType T = NTTP->getExpansionType(I);
575 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
578 ID.AddBoolean(false);
582 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
588 TemplateTemplateParmDecl *
589 ASTContext::getCanonicalTemplateTemplateParmDecl(
590 TemplateTemplateParmDecl *TTP) const {
591 // Check if we already have a canonical template template parameter.
592 llvm::FoldingSetNodeID ID;
593 CanonicalTemplateTemplateParm::Profile(ID, TTP);
594 void *InsertPos = nullptr;
595 CanonicalTemplateTemplateParm *Canonical
596 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
598 return Canonical->getParam();
600 // Build a canonical template parameter list.
601 TemplateParameterList *Params = TTP->getTemplateParameters();
602 SmallVector<NamedDecl *, 4> CanonParams;
603 CanonParams.reserve(Params->size());
604 for (TemplateParameterList::const_iterator P = Params->begin(),
605 PEnd = Params->end();
607 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
608 CanonParams.push_back(
609 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
613 TTP->getIndex(), nullptr, false,
614 TTP->isParameterPack()));
615 else if (NonTypeTemplateParmDecl *NTTP
616 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
617 QualType T = getCanonicalType(NTTP->getType());
618 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
619 NonTypeTemplateParmDecl *Param;
620 if (NTTP->isExpandedParameterPack()) {
621 SmallVector<QualType, 2> ExpandedTypes;
622 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
623 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
624 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
625 ExpandedTInfos.push_back(
626 getTrivialTypeSourceInfo(ExpandedTypes.back()));
629 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
633 NTTP->getPosition(), nullptr,
636 ExpandedTypes.data(),
637 ExpandedTypes.size(),
638 ExpandedTInfos.data());
640 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
644 NTTP->getPosition(), nullptr,
646 NTTP->isParameterPack(),
649 CanonParams.push_back(Param);
652 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
653 cast<TemplateTemplateParmDecl>(*P)));
656 TemplateTemplateParmDecl *CanonTTP
657 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
658 SourceLocation(), TTP->getDepth(),
660 TTP->isParameterPack(),
662 TemplateParameterList::Create(*this, SourceLocation(),
667 // Get the new insert position for the node we care about.
668 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
669 assert(!Canonical && "Shouldn't be in the map!");
672 // Create the canonical template template parameter entry.
673 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
674 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
678 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
679 if (!LangOpts.CPlusPlus) return nullptr;
681 switch (T.getCXXABI().getKind()) {
682 case TargetCXXABI::GenericARM: // Same as Itanium at this level
683 case TargetCXXABI::iOS:
684 case TargetCXXABI::iOS64:
685 case TargetCXXABI::WatchOS:
686 case TargetCXXABI::GenericAArch64:
687 case TargetCXXABI::GenericMIPS:
688 case TargetCXXABI::GenericItanium:
689 case TargetCXXABI::WebAssembly:
690 return CreateItaniumCXXABI(*this);
691 case TargetCXXABI::Microsoft:
692 return CreateMicrosoftCXXABI(*this);
694 llvm_unreachable("Invalid CXXABI type!");
697 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
698 const LangOptions &LOpts) {
699 if (LOpts.FakeAddressSpaceMap) {
700 // The fake address space map must have a distinct entry for each
701 // language-specific address space.
702 static const unsigned FakeAddrSpaceMap[] = {
705 3, // opencl_constant
711 return &FakeAddrSpaceMap;
713 return &T.getAddressSpaceMap();
717 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
718 const LangOptions &LangOpts) {
719 switch (LangOpts.getAddressSpaceMapMangling()) {
720 case LangOptions::ASMM_Target:
721 return TI.useAddressSpaceMapMangling();
722 case LangOptions::ASMM_On:
724 case LangOptions::ASMM_Off:
727 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
730 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
731 IdentifierTable &idents, SelectorTable &sels,
732 Builtin::Context &builtins)
733 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
734 DependentTemplateSpecializationTypes(this_()),
735 SubstTemplateTemplateParmPacks(this_()),
736 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
737 UInt128Decl(nullptr), Float128StubDecl(nullptr),
738 BuiltinVaListDecl(nullptr), BuiltinMSVaListDecl(nullptr),
739 ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
740 ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
741 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
742 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
743 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
744 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
745 FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
746 MakeIntegerSeqDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
747 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
748 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
749 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
750 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
751 Listener(nullptr), Comments(SM), CommentsLoaded(false),
752 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
753 TUDecl = TranslationUnitDecl::Create(*this);
756 ASTContext::~ASTContext() {
757 ReleaseParentMapEntries();
759 // Release the DenseMaps associated with DeclContext objects.
760 // FIXME: Is this the ideal solution?
761 ReleaseDeclContextMaps();
763 // Call all of the deallocation functions on all of their targets.
764 for (auto &Pair : Deallocations)
765 (Pair.first)(Pair.second);
767 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
768 // because they can contain DenseMaps.
769 for (llvm::DenseMap<const ObjCContainerDecl*,
770 const ASTRecordLayout*>::iterator
771 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
772 // Increment in loop to prevent using deallocated memory.
773 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
776 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
777 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
778 // Increment in loop to prevent using deallocated memory.
779 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
783 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
784 AEnd = DeclAttrs.end();
786 A->second->~AttrVec();
788 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
789 MaterializedTemporaryValues)
790 MTVPair.second->~APValue();
792 llvm::DeleteContainerSeconds(MangleNumberingContexts);
795 void ASTContext::ReleaseParentMapEntries() {
796 if (!PointerParents) return;
797 for (const auto &Entry : *PointerParents) {
798 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
799 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
800 } else if (Entry.second.is<ParentVector *>()) {
801 delete Entry.second.get<ParentVector *>();
804 for (const auto &Entry : *OtherParents) {
805 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
806 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
807 } else if (Entry.second.is<ParentVector *>()) {
808 delete Entry.second.get<ParentVector *>();
813 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
814 Deallocations.push_back({Callback, Data});
818 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
819 ExternalSource = Source;
822 void ASTContext::PrintStats() const {
823 llvm::errs() << "\n*** AST Context Stats:\n";
824 llvm::errs() << " " << Types.size() << " types total.\n";
826 unsigned counts[] = {
827 #define TYPE(Name, Parent) 0,
828 #define ABSTRACT_TYPE(Name, Parent)
829 #include "clang/AST/TypeNodes.def"
833 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
835 counts[(unsigned)T->getTypeClass()]++;
839 unsigned TotalBytes = 0;
840 #define TYPE(Name, Parent) \
842 llvm::errs() << " " << counts[Idx] << " " << #Name \
844 TotalBytes += counts[Idx] * sizeof(Name##Type); \
846 #define ABSTRACT_TYPE(Name, Parent)
847 #include "clang/AST/TypeNodes.def"
849 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
851 // Implicit special member functions.
852 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
853 << NumImplicitDefaultConstructors
854 << " implicit default constructors created\n";
855 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
856 << NumImplicitCopyConstructors
857 << " implicit copy constructors created\n";
858 if (getLangOpts().CPlusPlus)
859 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
860 << NumImplicitMoveConstructors
861 << " implicit move constructors created\n";
862 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
863 << NumImplicitCopyAssignmentOperators
864 << " implicit copy assignment operators created\n";
865 if (getLangOpts().CPlusPlus)
866 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
867 << NumImplicitMoveAssignmentOperators
868 << " implicit move assignment operators created\n";
869 llvm::errs() << NumImplicitDestructorsDeclared << "/"
870 << NumImplicitDestructors
871 << " implicit destructors created\n";
873 if (ExternalSource) {
874 llvm::errs() << "\n";
875 ExternalSource->PrintStats();
878 BumpAlloc.PrintStats();
881 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
882 bool NotifyListeners) {
884 if (auto *Listener = getASTMutationListener())
885 Listener->RedefinedHiddenDefinition(ND, M);
887 if (getLangOpts().ModulesLocalVisibility)
888 MergedDefModules[ND].push_back(M);
890 ND->setHidden(false);
893 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
894 auto It = MergedDefModules.find(ND);
895 if (It == MergedDefModules.end())
898 auto &Merged = It->second;
899 llvm::DenseSet<Module*> Found;
900 for (Module *&M : Merged)
901 if (!Found.insert(M).second)
903 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
906 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
908 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
910 return ExternCContext;
913 BuiltinTemplateDecl *
914 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
915 const IdentifierInfo *II) const {
916 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
917 BuiltinTemplate->setImplicit();
918 TUDecl->addDecl(BuiltinTemplate);
920 return BuiltinTemplate;
923 BuiltinTemplateDecl *
924 ASTContext::getMakeIntegerSeqDecl() const {
925 if (!MakeIntegerSeqDecl)
926 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
927 getMakeIntegerSeqName());
928 return MakeIntegerSeqDecl;
931 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
932 RecordDecl::TagKind TK) const {
935 if (getLangOpts().CPlusPlus)
936 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
937 Loc, &Idents.get(Name));
939 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
941 NewDecl->setImplicit();
942 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
943 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
947 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
948 StringRef Name) const {
949 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
950 TypedefDecl *NewDecl = TypedefDecl::Create(
951 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
952 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
953 NewDecl->setImplicit();
957 TypedefDecl *ASTContext::getInt128Decl() const {
959 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
963 TypedefDecl *ASTContext::getUInt128Decl() const {
965 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
969 TypeDecl *ASTContext::getFloat128StubType() const {
970 assert(LangOpts.CPlusPlus && "should only be called for c++");
971 if (!Float128StubDecl)
972 Float128StubDecl = buildImplicitRecord("__float128");
974 return Float128StubDecl;
977 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
978 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
979 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
983 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
984 const TargetInfo *AuxTarget) {
985 assert((!this->Target || this->Target == &Target) &&
986 "Incorrect target reinitialization");
987 assert(VoidTy.isNull() && "Context reinitialized?");
989 this->Target = &Target;
990 this->AuxTarget = AuxTarget;
992 ABI.reset(createCXXABI(Target));
993 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
994 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
997 InitBuiltinType(VoidTy, BuiltinType::Void);
1000 InitBuiltinType(BoolTy, BuiltinType::Bool);
1002 if (LangOpts.CharIsSigned)
1003 InitBuiltinType(CharTy, BuiltinType::Char_S);
1005 InitBuiltinType(CharTy, BuiltinType::Char_U);
1007 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1008 InitBuiltinType(ShortTy, BuiltinType::Short);
1009 InitBuiltinType(IntTy, BuiltinType::Int);
1010 InitBuiltinType(LongTy, BuiltinType::Long);
1011 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1014 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1015 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1016 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1017 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1018 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1021 InitBuiltinType(FloatTy, BuiltinType::Float);
1022 InitBuiltinType(DoubleTy, BuiltinType::Double);
1023 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1025 // GNU extension, 128-bit integers.
1026 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1027 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1030 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1031 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1032 else // -fshort-wchar makes wchar_t be unsigned.
1033 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1034 if (LangOpts.CPlusPlus && LangOpts.WChar)
1035 WideCharTy = WCharTy;
1037 // C99 (or C++ using -fno-wchar).
1038 WideCharTy = getFromTargetType(Target.getWCharType());
1041 WIntTy = getFromTargetType(Target.getWIntType());
1043 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1044 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1046 Char16Ty = getFromTargetType(Target.getChar16Type());
1048 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1049 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1051 Char32Ty = getFromTargetType(Target.getChar32Type());
1053 // Placeholder type for type-dependent expressions whose type is
1054 // completely unknown. No code should ever check a type against
1055 // DependentTy and users should never see it; however, it is here to
1056 // help diagnose failures to properly check for type-dependent
1058 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1060 // Placeholder type for functions.
1061 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1063 // Placeholder type for bound members.
1064 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1066 // Placeholder type for pseudo-objects.
1067 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1069 // "any" type; useful for debugger-like clients.
1070 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1072 // Placeholder type for unbridged ARC casts.
1073 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1075 // Placeholder type for builtin functions.
1076 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1078 // Placeholder type for OMP array sections.
1079 if (LangOpts.OpenMP)
1080 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1083 FloatComplexTy = getComplexType(FloatTy);
1084 DoubleComplexTy = getComplexType(DoubleTy);
1085 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1087 // Builtin types for 'id', 'Class', and 'SEL'.
1088 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1089 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1090 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1092 if (LangOpts.OpenCL) {
1093 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1094 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1095 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1096 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1097 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1098 InitBuiltinType(OCLImage2dDepthTy, BuiltinType::OCLImage2dDepth);
1099 InitBuiltinType(OCLImage2dArrayDepthTy, BuiltinType::OCLImage2dArrayDepth);
1100 InitBuiltinType(OCLImage2dMSAATy, BuiltinType::OCLImage2dMSAA);
1101 InitBuiltinType(OCLImage2dArrayMSAATy, BuiltinType::OCLImage2dArrayMSAA);
1102 InitBuiltinType(OCLImage2dMSAADepthTy, BuiltinType::OCLImage2dMSAADepth);
1103 InitBuiltinType(OCLImage2dArrayMSAADepthTy,
1104 BuiltinType::OCLImage2dArrayMSAADepth);
1105 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
1107 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1108 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1109 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1110 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1111 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1112 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1115 // Builtin type for __objc_yes and __objc_no
1116 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1117 SignedCharTy : BoolTy);
1119 ObjCConstantStringType = QualType();
1121 ObjCSuperType = QualType();
1124 VoidPtrTy = getPointerType(VoidTy);
1126 // nullptr type (C++0x 2.14.7)
1127 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1129 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1130 InitBuiltinType(HalfTy, BuiltinType::Half);
1132 // Builtin type used to help define __builtin_va_list.
1133 VaListTagDecl = nullptr;
1136 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1137 return SourceMgr.getDiagnostics();
1140 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1141 AttrVec *&Result = DeclAttrs[D];
1143 void *Mem = Allocate(sizeof(AttrVec));
1144 Result = new (Mem) AttrVec;
1150 /// \brief Erase the attributes corresponding to the given declaration.
1151 void ASTContext::eraseDeclAttrs(const Decl *D) {
1152 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1153 if (Pos != DeclAttrs.end()) {
1154 Pos->second->~AttrVec();
1155 DeclAttrs.erase(Pos);
1160 MemberSpecializationInfo *
1161 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1162 assert(Var->isStaticDataMember() && "Not a static data member");
1163 return getTemplateOrSpecializationInfo(Var)
1164 .dyn_cast<MemberSpecializationInfo *>();
1167 ASTContext::TemplateOrSpecializationInfo
1168 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1169 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1170 TemplateOrInstantiation.find(Var);
1171 if (Pos == TemplateOrInstantiation.end())
1172 return TemplateOrSpecializationInfo();
1178 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1179 TemplateSpecializationKind TSK,
1180 SourceLocation PointOfInstantiation) {
1181 assert(Inst->isStaticDataMember() && "Not a static data member");
1182 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1183 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1184 Tmpl, TSK, PointOfInstantiation));
1188 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1189 TemplateOrSpecializationInfo TSI) {
1190 assert(!TemplateOrInstantiation[Inst] &&
1191 "Already noted what the variable was instantiated from");
1192 TemplateOrInstantiation[Inst] = TSI;
1195 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1196 const FunctionDecl *FD){
1197 assert(FD && "Specialization is 0");
1198 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1199 = ClassScopeSpecializationPattern.find(FD);
1200 if (Pos == ClassScopeSpecializationPattern.end())
1206 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1207 FunctionDecl *Pattern) {
1208 assert(FD && "Specialization is 0");
1209 assert(Pattern && "Class scope specialization pattern is 0");
1210 ClassScopeSpecializationPattern[FD] = Pattern;
1214 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
1215 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
1216 = InstantiatedFromUsingDecl.find(UUD);
1217 if (Pos == InstantiatedFromUsingDecl.end())
1224 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1225 assert((isa<UsingDecl>(Pattern) ||
1226 isa<UnresolvedUsingValueDecl>(Pattern) ||
1227 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1228 "pattern decl is not a using decl");
1229 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1230 InstantiatedFromUsingDecl[Inst] = Pattern;
1234 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1235 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1236 = InstantiatedFromUsingShadowDecl.find(Inst);
1237 if (Pos == InstantiatedFromUsingShadowDecl.end())
1244 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1245 UsingShadowDecl *Pattern) {
1246 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1247 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1250 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1251 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1252 = InstantiatedFromUnnamedFieldDecl.find(Field);
1253 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1259 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1261 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1262 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1263 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1264 "Already noted what unnamed field was instantiated from");
1266 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1269 ASTContext::overridden_cxx_method_iterator
1270 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1271 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1272 = OverriddenMethods.find(Method->getCanonicalDecl());
1273 if (Pos == OverriddenMethods.end())
1276 return Pos->second.begin();
1279 ASTContext::overridden_cxx_method_iterator
1280 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1281 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1282 = OverriddenMethods.find(Method->getCanonicalDecl());
1283 if (Pos == OverriddenMethods.end())
1286 return Pos->second.end();
1290 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1291 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1292 = OverriddenMethods.find(Method->getCanonicalDecl());
1293 if (Pos == OverriddenMethods.end())
1296 return Pos->second.size();
1299 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1300 const CXXMethodDecl *Overridden) {
1301 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1302 OverriddenMethods[Method].push_back(Overridden);
1305 void ASTContext::getOverriddenMethods(
1307 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1310 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1311 Overridden.append(overridden_methods_begin(CXXMethod),
1312 overridden_methods_end(CXXMethod));
1316 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1320 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1321 Method->getOverriddenMethods(OverDecls);
1322 Overridden.append(OverDecls.begin(), OverDecls.end());
1325 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1326 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1327 assert(!Import->isFromASTFile() && "Non-local import declaration");
1328 if (!FirstLocalImport) {
1329 FirstLocalImport = Import;
1330 LastLocalImport = Import;
1334 LastLocalImport->NextLocalImport = Import;
1335 LastLocalImport = Import;
1338 //===----------------------------------------------------------------------===//
1339 // Type Sizing and Analysis
1340 //===----------------------------------------------------------------------===//
1342 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1343 /// scalar floating point type.
1344 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1345 const BuiltinType *BT = T->getAs<BuiltinType>();
1346 assert(BT && "Not a floating point type!");
1347 switch (BT->getKind()) {
1348 default: llvm_unreachable("Not a floating point type!");
1349 case BuiltinType::Half: return Target->getHalfFormat();
1350 case BuiltinType::Float: return Target->getFloatFormat();
1351 case BuiltinType::Double: return Target->getDoubleFormat();
1352 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1356 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1357 unsigned Align = Target->getCharWidth();
1359 bool UseAlignAttrOnly = false;
1360 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1361 Align = AlignFromAttr;
1363 // __attribute__((aligned)) can increase or decrease alignment
1364 // *except* on a struct or struct member, where it only increases
1365 // alignment unless 'packed' is also specified.
1367 // It is an error for alignas to decrease alignment, so we can
1368 // ignore that possibility; Sema should diagnose it.
1369 if (isa<FieldDecl>(D)) {
1370 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1371 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1373 UseAlignAttrOnly = true;
1376 else if (isa<FieldDecl>(D))
1378 D->hasAttr<PackedAttr>() ||
1379 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1381 // If we're using the align attribute only, just ignore everything
1382 // else about the declaration and its type.
1383 if (UseAlignAttrOnly) {
1386 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1387 QualType T = VD->getType();
1388 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
1390 T = RT->getPointeeType();
1392 T = getPointerType(RT->getPointeeType());
1394 QualType BaseT = getBaseElementType(T);
1395 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
1396 // Adjust alignments of declarations with array type by the
1397 // large-array alignment on the target.
1398 if (const ArrayType *arrayType = getAsArrayType(T)) {
1399 unsigned MinWidth = Target->getLargeArrayMinWidth();
1400 if (!ForAlignof && MinWidth) {
1401 if (isa<VariableArrayType>(arrayType))
1402 Align = std::max(Align, Target->getLargeArrayAlign());
1403 else if (isa<ConstantArrayType>(arrayType) &&
1404 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1405 Align = std::max(Align, Target->getLargeArrayAlign());
1408 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1409 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1410 if (VD->hasGlobalStorage() && !ForAlignof)
1411 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1415 // Fields can be subject to extra alignment constraints, like if
1416 // the field is packed, the struct is packed, or the struct has a
1417 // a max-field-alignment constraint (#pragma pack). So calculate
1418 // the actual alignment of the field within the struct, and then
1419 // (as we're expected to) constrain that by the alignment of the type.
1420 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1421 const RecordDecl *Parent = Field->getParent();
1422 // We can only produce a sensible answer if the record is valid.
1423 if (!Parent->isInvalidDecl()) {
1424 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1426 // Start with the record's overall alignment.
1427 unsigned FieldAlign = toBits(Layout.getAlignment());
1429 // Use the GCD of that and the offset within the record.
1430 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1432 // Alignment is always a power of 2, so the GCD will be a power of 2,
1433 // which means we get to do this crazy thing instead of Euclid's.
1434 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1435 if (LowBitOfOffset < FieldAlign)
1436 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1439 Align = std::min(Align, FieldAlign);
1444 return toCharUnitsFromBits(Align);
1447 // getTypeInfoDataSizeInChars - Return the size of a type, in
1448 // chars. If the type is a record, its data size is returned. This is
1449 // the size of the memcpy that's performed when assigning this type
1450 // using a trivial copy/move assignment operator.
1451 std::pair<CharUnits, CharUnits>
1452 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1453 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1455 // In C++, objects can sometimes be allocated into the tail padding
1456 // of a base-class subobject. We decide whether that's possible
1457 // during class layout, so here we can just trust the layout results.
1458 if (getLangOpts().CPlusPlus) {
1459 if (const RecordType *RT = T->getAs<RecordType>()) {
1460 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1461 sizeAndAlign.first = layout.getDataSize();
1465 return sizeAndAlign;
1468 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1469 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1470 std::pair<CharUnits, CharUnits>
1471 static getConstantArrayInfoInChars(const ASTContext &Context,
1472 const ConstantArrayType *CAT) {
1473 std::pair<CharUnits, CharUnits> EltInfo =
1474 Context.getTypeInfoInChars(CAT->getElementType());
1475 uint64_t Size = CAT->getSize().getZExtValue();
1476 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1477 (uint64_t)(-1)/Size) &&
1478 "Overflow in array type char size evaluation");
1479 uint64_t Width = EltInfo.first.getQuantity() * Size;
1480 unsigned Align = EltInfo.second.getQuantity();
1481 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1482 Context.getTargetInfo().getPointerWidth(0) == 64)
1483 Width = llvm::RoundUpToAlignment(Width, Align);
1484 return std::make_pair(CharUnits::fromQuantity(Width),
1485 CharUnits::fromQuantity(Align));
1488 std::pair<CharUnits, CharUnits>
1489 ASTContext::getTypeInfoInChars(const Type *T) const {
1490 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1491 return getConstantArrayInfoInChars(*this, CAT);
1492 TypeInfo Info = getTypeInfo(T);
1493 return std::make_pair(toCharUnitsFromBits(Info.Width),
1494 toCharUnitsFromBits(Info.Align));
1497 std::pair<CharUnits, CharUnits>
1498 ASTContext::getTypeInfoInChars(QualType T) const {
1499 return getTypeInfoInChars(T.getTypePtr());
1502 bool ASTContext::isAlignmentRequired(const Type *T) const {
1503 return getTypeInfo(T).AlignIsRequired;
1506 bool ASTContext::isAlignmentRequired(QualType T) const {
1507 return isAlignmentRequired(T.getTypePtr());
1510 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1511 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1512 if (I != MemoizedTypeInfo.end())
1515 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1516 TypeInfo TI = getTypeInfoImpl(T);
1517 MemoizedTypeInfo[T] = TI;
1521 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1522 /// method does not work on incomplete types.
1524 /// FIXME: Pointers into different addr spaces could have different sizes and
1525 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1526 /// should take a QualType, &c.
1527 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1530 bool AlignIsRequired = false;
1531 switch (T->getTypeClass()) {
1532 #define TYPE(Class, Base)
1533 #define ABSTRACT_TYPE(Class, Base)
1534 #define NON_CANONICAL_TYPE(Class, Base)
1535 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1536 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1538 assert(!T->isDependentType() && "should not see dependent types here"); \
1539 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1540 #include "clang/AST/TypeNodes.def"
1541 llvm_unreachable("Should not see dependent types");
1543 case Type::FunctionNoProto:
1544 case Type::FunctionProto:
1545 // GCC extension: alignof(function) = 32 bits
1550 case Type::IncompleteArray:
1551 case Type::VariableArray:
1553 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1556 case Type::ConstantArray: {
1557 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1559 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1560 uint64_t Size = CAT->getSize().getZExtValue();
1561 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1562 "Overflow in array type bit size evaluation");
1563 Width = EltInfo.Width * Size;
1564 Align = EltInfo.Align;
1565 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1566 getTargetInfo().getPointerWidth(0) == 64)
1567 Width = llvm::RoundUpToAlignment(Width, Align);
1570 case Type::ExtVector:
1571 case Type::Vector: {
1572 const VectorType *VT = cast<VectorType>(T);
1573 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1574 Width = EltInfo.Width * VT->getNumElements();
1576 // If the alignment is not a power of 2, round up to the next power of 2.
1577 // This happens for non-power-of-2 length vectors.
1578 if (Align & (Align-1)) {
1579 Align = llvm::NextPowerOf2(Align);
1580 Width = llvm::RoundUpToAlignment(Width, Align);
1582 // Adjust the alignment based on the target max.
1583 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1584 if (TargetVectorAlign && TargetVectorAlign < Align)
1585 Align = TargetVectorAlign;
1590 switch (cast<BuiltinType>(T)->getKind()) {
1591 default: llvm_unreachable("Unknown builtin type!");
1592 case BuiltinType::Void:
1593 // GCC extension: alignof(void) = 8 bits.
1598 case BuiltinType::Bool:
1599 Width = Target->getBoolWidth();
1600 Align = Target->getBoolAlign();
1602 case BuiltinType::Char_S:
1603 case BuiltinType::Char_U:
1604 case BuiltinType::UChar:
1605 case BuiltinType::SChar:
1606 Width = Target->getCharWidth();
1607 Align = Target->getCharAlign();
1609 case BuiltinType::WChar_S:
1610 case BuiltinType::WChar_U:
1611 Width = Target->getWCharWidth();
1612 Align = Target->getWCharAlign();
1614 case BuiltinType::Char16:
1615 Width = Target->getChar16Width();
1616 Align = Target->getChar16Align();
1618 case BuiltinType::Char32:
1619 Width = Target->getChar32Width();
1620 Align = Target->getChar32Align();
1622 case BuiltinType::UShort:
1623 case BuiltinType::Short:
1624 Width = Target->getShortWidth();
1625 Align = Target->getShortAlign();
1627 case BuiltinType::UInt:
1628 case BuiltinType::Int:
1629 Width = Target->getIntWidth();
1630 Align = Target->getIntAlign();
1632 case BuiltinType::ULong:
1633 case BuiltinType::Long:
1634 Width = Target->getLongWidth();
1635 Align = Target->getLongAlign();
1637 case BuiltinType::ULongLong:
1638 case BuiltinType::LongLong:
1639 Width = Target->getLongLongWidth();
1640 Align = Target->getLongLongAlign();
1642 case BuiltinType::Int128:
1643 case BuiltinType::UInt128:
1645 Align = 128; // int128_t is 128-bit aligned on all targets.
1647 case BuiltinType::Half:
1648 Width = Target->getHalfWidth();
1649 Align = Target->getHalfAlign();
1651 case BuiltinType::Float:
1652 Width = Target->getFloatWidth();
1653 Align = Target->getFloatAlign();
1655 case BuiltinType::Double:
1656 Width = Target->getDoubleWidth();
1657 Align = Target->getDoubleAlign();
1659 case BuiltinType::LongDouble:
1660 Width = Target->getLongDoubleWidth();
1661 Align = Target->getLongDoubleAlign();
1663 case BuiltinType::NullPtr:
1664 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1665 Align = Target->getPointerAlign(0); // == sizeof(void*)
1667 case BuiltinType::ObjCId:
1668 case BuiltinType::ObjCClass:
1669 case BuiltinType::ObjCSel:
1670 Width = Target->getPointerWidth(0);
1671 Align = Target->getPointerAlign(0);
1673 case BuiltinType::OCLSampler:
1674 // Samplers are modeled as integers.
1675 Width = Target->getIntWidth();
1676 Align = Target->getIntAlign();
1678 case BuiltinType::OCLEvent:
1679 case BuiltinType::OCLClkEvent:
1680 case BuiltinType::OCLQueue:
1681 case BuiltinType::OCLNDRange:
1682 case BuiltinType::OCLReserveID:
1683 case BuiltinType::OCLImage1d:
1684 case BuiltinType::OCLImage1dArray:
1685 case BuiltinType::OCLImage1dBuffer:
1686 case BuiltinType::OCLImage2d:
1687 case BuiltinType::OCLImage2dArray:
1688 case BuiltinType::OCLImage2dDepth:
1689 case BuiltinType::OCLImage2dArrayDepth:
1690 case BuiltinType::OCLImage2dMSAA:
1691 case BuiltinType::OCLImage2dArrayMSAA:
1692 case BuiltinType::OCLImage2dMSAADepth:
1693 case BuiltinType::OCLImage2dArrayMSAADepth:
1694 case BuiltinType::OCLImage3d:
1695 // Currently these types are pointers to opaque types.
1696 Width = Target->getPointerWidth(0);
1697 Align = Target->getPointerAlign(0);
1701 case Type::ObjCObjectPointer:
1702 Width = Target->getPointerWidth(0);
1703 Align = Target->getPointerAlign(0);
1705 case Type::BlockPointer: {
1706 unsigned AS = getTargetAddressSpace(
1707 cast<BlockPointerType>(T)->getPointeeType());
1708 Width = Target->getPointerWidth(AS);
1709 Align = Target->getPointerAlign(AS);
1712 case Type::LValueReference:
1713 case Type::RValueReference: {
1714 // alignof and sizeof should never enter this code path here, so we go
1715 // the pointer route.
1716 unsigned AS = getTargetAddressSpace(
1717 cast<ReferenceType>(T)->getPointeeType());
1718 Width = Target->getPointerWidth(AS);
1719 Align = Target->getPointerAlign(AS);
1722 case Type::Pointer: {
1723 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1724 Width = Target->getPointerWidth(AS);
1725 Align = Target->getPointerAlign(AS);
1728 case Type::MemberPointer: {
1729 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1730 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1733 case Type::Complex: {
1734 // Complex types have the same alignment as their elements, but twice the
1736 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1737 Width = EltInfo.Width * 2;
1738 Align = EltInfo.Align;
1741 case Type::ObjCObject:
1742 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1743 case Type::Adjusted:
1745 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1746 case Type::ObjCInterface: {
1747 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1748 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1749 Width = toBits(Layout.getSize());
1750 Align = toBits(Layout.getAlignment());
1755 const TagType *TT = cast<TagType>(T);
1757 if (TT->getDecl()->isInvalidDecl()) {
1763 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1764 const EnumDecl *ED = ET->getDecl();
1766 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1767 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1768 Info.Align = AttrAlign;
1769 Info.AlignIsRequired = true;
1774 const RecordType *RT = cast<RecordType>(TT);
1775 const RecordDecl *RD = RT->getDecl();
1776 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
1777 Width = toBits(Layout.getSize());
1778 Align = toBits(Layout.getAlignment());
1779 AlignIsRequired = RD->hasAttr<AlignedAttr>();
1783 case Type::SubstTemplateTypeParm:
1784 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1785 getReplacementType().getTypePtr());
1788 const AutoType *A = cast<AutoType>(T);
1789 assert(!A->getDeducedType().isNull() &&
1790 "cannot request the size of an undeduced or dependent auto type");
1791 return getTypeInfo(A->getDeducedType().getTypePtr());
1795 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1797 case Type::Typedef: {
1798 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1799 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1800 // If the typedef has an aligned attribute on it, it overrides any computed
1801 // alignment we have. This violates the GCC documentation (which says that
1802 // attribute(aligned) can only round up) but matches its implementation.
1803 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
1805 AlignIsRequired = true;
1808 AlignIsRequired = Info.AlignIsRequired;
1814 case Type::Elaborated:
1815 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1817 case Type::Attributed:
1819 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1821 case Type::Atomic: {
1822 // Start with the base type information.
1823 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1827 // If the size of the type doesn't exceed the platform's max
1828 // atomic promotion width, make the size and alignment more
1829 // favorable to atomic operations:
1830 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1831 // Round the size up to a power of 2.
1832 if (!llvm::isPowerOf2_64(Width))
1833 Width = llvm::NextPowerOf2(Width);
1835 // Set the alignment equal to the size.
1836 Align = static_cast<unsigned>(Width);
1842 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1843 return TypeInfo(Width, Align, AlignIsRequired);
1846 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1847 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1848 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1849 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1850 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1851 getTargetInfo().getABI() == "elfv1-qpx" &&
1852 T->isSpecificBuiltinType(BuiltinType::Double))
1857 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1858 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1859 return CharUnits::fromQuantity(BitSize / getCharWidth());
1862 /// toBits - Convert a size in characters to a size in characters.
1863 int64_t ASTContext::toBits(CharUnits CharSize) const {
1864 return CharSize.getQuantity() * getCharWidth();
1867 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1868 /// This method does not work on incomplete types.
1869 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1870 return getTypeInfoInChars(T).first;
1872 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1873 return getTypeInfoInChars(T).first;
1876 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1877 /// characters. This method does not work on incomplete types.
1878 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1879 return toCharUnitsFromBits(getTypeAlign(T));
1881 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1882 return toCharUnitsFromBits(getTypeAlign(T));
1885 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1886 /// type for the current target in bits. This can be different than the ABI
1887 /// alignment in cases where it is beneficial for performance to overalign
1889 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1890 TypeInfo TI = getTypeInfo(T);
1891 unsigned ABIAlign = TI.Align;
1893 T = T->getBaseElementTypeUnsafe();
1895 // The preferred alignment of member pointers is that of a pointer.
1896 if (T->isMemberPointerType())
1897 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1899 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1900 return ABIAlign; // Never overalign on XCore.
1902 // Double and long long should be naturally aligned if possible.
1903 if (const ComplexType *CT = T->getAs<ComplexType>())
1904 T = CT->getElementType().getTypePtr();
1905 if (const EnumType *ET = T->getAs<EnumType>())
1906 T = ET->getDecl()->getIntegerType().getTypePtr();
1907 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1908 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1909 T->isSpecificBuiltinType(BuiltinType::ULongLong))
1910 // Don't increase the alignment if an alignment attribute was specified on a
1911 // typedef declaration.
1912 if (!TI.AlignIsRequired)
1913 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1918 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1919 /// for __attribute__((aligned)) on this target, to be used if no alignment
1920 /// value is specified.
1921 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
1922 return getTargetInfo().getDefaultAlignForAttributeAligned();
1925 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
1926 /// to a global variable of the specified type.
1927 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1928 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1931 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
1932 /// should be given to a global variable of the specified type.
1933 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1934 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1937 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1938 CharUnits Offset = CharUnits::Zero();
1939 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1940 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1941 Offset += Layout->getBaseClassOffset(Base);
1942 Layout = &getASTRecordLayout(Base);
1947 /// DeepCollectObjCIvars -
1948 /// This routine first collects all declared, but not synthesized, ivars in
1949 /// super class and then collects all ivars, including those synthesized for
1950 /// current class. This routine is used for implementation of current class
1951 /// when all ivars, declared and synthesized are known.
1953 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1955 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1956 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1957 DeepCollectObjCIvars(SuperClass, false, Ivars);
1959 for (const auto *I : OI->ivars())
1962 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1963 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1964 Iv= Iv->getNextIvar())
1965 Ivars.push_back(Iv);
1969 /// CollectInheritedProtocols - Collect all protocols in current class and
1970 /// those inherited by it.
1971 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1972 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1973 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1974 // We can use protocol_iterator here instead of
1975 // all_referenced_protocol_iterator since we are walking all categories.
1976 for (auto *Proto : OI->all_referenced_protocols()) {
1977 CollectInheritedProtocols(Proto, Protocols);
1980 // Categories of this Interface.
1981 for (const auto *Cat : OI->visible_categories())
1982 CollectInheritedProtocols(Cat, Protocols);
1984 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1986 CollectInheritedProtocols(SD, Protocols);
1987 SD = SD->getSuperClass();
1989 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1990 for (auto *Proto : OC->protocols()) {
1991 CollectInheritedProtocols(Proto, Protocols);
1993 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1994 // Insert the protocol.
1995 if (!Protocols.insert(
1996 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1999 for (auto *Proto : OP->protocols())
2000 CollectInheritedProtocols(Proto, Protocols);
2004 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2006 // Count ivars declared in class extension.
2007 for (const auto *Ext : OI->known_extensions())
2008 count += Ext->ivar_size();
2010 // Count ivar defined in this class's implementation. This
2011 // includes synthesized ivars.
2012 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2013 count += ImplDecl->ivar_size();
2018 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2022 // nullptr_t is always treated as null.
2023 if (E->getType()->isNullPtrType()) return true;
2025 if (E->getType()->isAnyPointerType() &&
2026 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2027 Expr::NPC_ValueDependentIsNull))
2030 // Unfortunately, __null has type 'int'.
2031 if (isa<GNUNullExpr>(E)) return true;
2036 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2037 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2038 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2039 I = ObjCImpls.find(D);
2040 if (I != ObjCImpls.end())
2041 return cast<ObjCImplementationDecl>(I->second);
2044 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2045 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2046 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2047 I = ObjCImpls.find(D);
2048 if (I != ObjCImpls.end())
2049 return cast<ObjCCategoryImplDecl>(I->second);
2053 /// \brief Set the implementation of ObjCInterfaceDecl.
2054 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2055 ObjCImplementationDecl *ImplD) {
2056 assert(IFaceD && ImplD && "Passed null params");
2057 ObjCImpls[IFaceD] = ImplD;
2059 /// \brief Set the implementation of ObjCCategoryDecl.
2060 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2061 ObjCCategoryImplDecl *ImplD) {
2062 assert(CatD && ImplD && "Passed null params");
2063 ObjCImpls[CatD] = ImplD;
2066 const ObjCMethodDecl *
2067 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2068 return ObjCMethodRedecls.lookup(MD);
2071 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2072 const ObjCMethodDecl *Redecl) {
2073 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2074 ObjCMethodRedecls[MD] = Redecl;
2077 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2078 const NamedDecl *ND) const {
2079 if (const ObjCInterfaceDecl *ID =
2080 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2082 if (const ObjCCategoryDecl *CD =
2083 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2084 return CD->getClassInterface();
2085 if (const ObjCImplDecl *IMD =
2086 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2087 return IMD->getClassInterface();
2092 /// \brief Get the copy initialization expression of VarDecl,or NULL if
2094 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
2095 assert(VD && "Passed null params");
2096 assert(VD->hasAttr<BlocksAttr>() &&
2097 "getBlockVarCopyInits - not __block var");
2098 llvm::DenseMap<const VarDecl*, Expr*>::iterator
2099 I = BlockVarCopyInits.find(VD);
2100 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
2103 /// \brief Set the copy inialization expression of a block var decl.
2104 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2105 assert(VD && Init && "Passed null params");
2106 assert(VD->hasAttr<BlocksAttr>() &&
2107 "setBlockVarCopyInits - not __block var");
2108 BlockVarCopyInits[VD] = Init;
2111 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2112 unsigned DataSize) const {
2114 DataSize = TypeLoc::getFullDataSizeForType(T);
2116 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2117 "incorrect data size provided to CreateTypeSourceInfo!");
2119 TypeSourceInfo *TInfo =
2120 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2121 new (TInfo) TypeSourceInfo(T);
2125 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2126 SourceLocation L) const {
2127 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2128 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2132 const ASTRecordLayout &
2133 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2134 return getObjCLayout(D, nullptr);
2137 const ASTRecordLayout &
2138 ASTContext::getASTObjCImplementationLayout(
2139 const ObjCImplementationDecl *D) const {
2140 return getObjCLayout(D->getClassInterface(), D);
2143 //===----------------------------------------------------------------------===//
2144 // Type creation/memoization methods
2145 //===----------------------------------------------------------------------===//
2148 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2149 unsigned fastQuals = quals.getFastQualifiers();
2150 quals.removeFastQualifiers();
2152 // Check if we've already instantiated this type.
2153 llvm::FoldingSetNodeID ID;
2154 ExtQuals::Profile(ID, baseType, quals);
2155 void *insertPos = nullptr;
2156 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2157 assert(eq->getQualifiers() == quals);
2158 return QualType(eq, fastQuals);
2161 // If the base type is not canonical, make the appropriate canonical type.
2163 if (!baseType->isCanonicalUnqualified()) {
2164 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2165 canonSplit.Quals.addConsistentQualifiers(quals);
2166 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2168 // Re-find the insert position.
2169 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2172 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2173 ExtQualNodes.InsertNode(eq, insertPos);
2174 return QualType(eq, fastQuals);
2178 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2179 QualType CanT = getCanonicalType(T);
2180 if (CanT.getAddressSpace() == AddressSpace)
2183 // If we are composing extended qualifiers together, merge together
2184 // into one ExtQuals node.
2185 QualifierCollector Quals;
2186 const Type *TypeNode = Quals.strip(T);
2188 // If this type already has an address space specified, it cannot get
2190 assert(!Quals.hasAddressSpace() &&
2191 "Type cannot be in multiple addr spaces!");
2192 Quals.addAddressSpace(AddressSpace);
2194 return getExtQualType(TypeNode, Quals);
2197 QualType ASTContext::getObjCGCQualType(QualType T,
2198 Qualifiers::GC GCAttr) const {
2199 QualType CanT = getCanonicalType(T);
2200 if (CanT.getObjCGCAttr() == GCAttr)
2203 if (const PointerType *ptr = T->getAs<PointerType>()) {
2204 QualType Pointee = ptr->getPointeeType();
2205 if (Pointee->isAnyPointerType()) {
2206 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2207 return getPointerType(ResultType);
2211 // If we are composing extended qualifiers together, merge together
2212 // into one ExtQuals node.
2213 QualifierCollector Quals;
2214 const Type *TypeNode = Quals.strip(T);
2216 // If this type already has an ObjCGC specified, it cannot get
2218 assert(!Quals.hasObjCGCAttr() &&
2219 "Type cannot have multiple ObjCGCs!");
2220 Quals.addObjCGCAttr(GCAttr);
2222 return getExtQualType(TypeNode, Quals);
2225 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2226 FunctionType::ExtInfo Info) {
2227 if (T->getExtInfo() == Info)
2231 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2232 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2234 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2235 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2237 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2240 return cast<FunctionType>(Result.getTypePtr());
2243 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2244 QualType ResultType) {
2245 FD = FD->getMostRecentDecl();
2247 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2248 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2249 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2250 if (FunctionDecl *Next = FD->getPreviousDecl())
2255 if (ASTMutationListener *L = getASTMutationListener())
2256 L->DeducedReturnType(FD, ResultType);
2259 /// Get a function type and produce the equivalent function type with the
2260 /// specified exception specification. Type sugar that can be present on a
2261 /// declaration of a function with an exception specification is permitted
2262 /// and preserved. Other type sugar (for instance, typedefs) is not.
2263 static QualType getFunctionTypeWithExceptionSpec(
2264 ASTContext &Context, QualType Orig,
2265 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2266 // Might have some parens.
2267 if (auto *PT = dyn_cast<ParenType>(Orig))
2268 return Context.getParenType(
2269 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2271 // Might have a calling-convention attribute.
2272 if (auto *AT = dyn_cast<AttributedType>(Orig))
2273 return Context.getAttributedType(
2275 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2276 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2279 // Anything else must be a function type. Rebuild it with the new exception
2281 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2282 return Context.getFunctionType(
2283 Proto->getReturnType(), Proto->getParamTypes(),
2284 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2287 void ASTContext::adjustExceptionSpec(
2288 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2292 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2293 FD->setType(Updated);
2298 // Update the type in the type source information too.
2299 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2300 // If the type and the type-as-written differ, we may need to update
2301 // the type-as-written too.
2302 if (TSInfo->getType() != FD->getType())
2303 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2305 // FIXME: When we get proper type location information for exceptions,
2306 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2307 // up the TypeSourceInfo;
2308 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2309 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2310 "TypeLoc size mismatch from updating exception specification");
2311 TSInfo->overrideType(Updated);
2315 /// getComplexType - Return the uniqued reference to the type for a complex
2316 /// number with the specified element type.
2317 QualType ASTContext::getComplexType(QualType T) const {
2318 // Unique pointers, to guarantee there is only one pointer of a particular
2320 llvm::FoldingSetNodeID ID;
2321 ComplexType::Profile(ID, T);
2323 void *InsertPos = nullptr;
2324 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2325 return QualType(CT, 0);
2327 // If the pointee type isn't canonical, this won't be a canonical type either,
2328 // so fill in the canonical type field.
2330 if (!T.isCanonical()) {
2331 Canonical = getComplexType(getCanonicalType(T));
2333 // Get the new insert position for the node we care about.
2334 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2335 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2337 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2338 Types.push_back(New);
2339 ComplexTypes.InsertNode(New, InsertPos);
2340 return QualType(New, 0);
2343 /// getPointerType - Return the uniqued reference to the type for a pointer to
2344 /// the specified type.
2345 QualType ASTContext::getPointerType(QualType T) const {
2346 // Unique pointers, to guarantee there is only one pointer of a particular
2348 llvm::FoldingSetNodeID ID;
2349 PointerType::Profile(ID, T);
2351 void *InsertPos = nullptr;
2352 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2353 return QualType(PT, 0);
2355 // If the pointee type isn't canonical, this won't be a canonical type either,
2356 // so fill in the canonical type field.
2358 if (!T.isCanonical()) {
2359 Canonical = getPointerType(getCanonicalType(T));
2361 // Get the new insert position for the node we care about.
2362 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2363 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2365 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2366 Types.push_back(New);
2367 PointerTypes.InsertNode(New, InsertPos);
2368 return QualType(New, 0);
2371 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2372 llvm::FoldingSetNodeID ID;
2373 AdjustedType::Profile(ID, Orig, New);
2374 void *InsertPos = nullptr;
2375 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2377 return QualType(AT, 0);
2379 QualType Canonical = getCanonicalType(New);
2381 // Get the new insert position for the node we care about.
2382 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2383 assert(!AT && "Shouldn't be in the map!");
2385 AT = new (*this, TypeAlignment)
2386 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2387 Types.push_back(AT);
2388 AdjustedTypes.InsertNode(AT, InsertPos);
2389 return QualType(AT, 0);
2392 QualType ASTContext::getDecayedType(QualType T) const {
2393 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2398 // A declaration of a parameter as "array of type" shall be
2399 // adjusted to "qualified pointer to type", where the type
2400 // qualifiers (if any) are those specified within the [ and ] of
2401 // the array type derivation.
2402 if (T->isArrayType())
2403 Decayed = getArrayDecayedType(T);
2406 // A declaration of a parameter as "function returning type"
2407 // shall be adjusted to "pointer to function returning type", as
2409 if (T->isFunctionType())
2410 Decayed = getPointerType(T);
2412 llvm::FoldingSetNodeID ID;
2413 AdjustedType::Profile(ID, T, Decayed);
2414 void *InsertPos = nullptr;
2415 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2417 return QualType(AT, 0);
2419 QualType Canonical = getCanonicalType(Decayed);
2421 // Get the new insert position for the node we care about.
2422 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2423 assert(!AT && "Shouldn't be in the map!");
2425 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2426 Types.push_back(AT);
2427 AdjustedTypes.InsertNode(AT, InsertPos);
2428 return QualType(AT, 0);
2431 /// getBlockPointerType - Return the uniqued reference to the type for
2432 /// a pointer to the specified block.
2433 QualType ASTContext::getBlockPointerType(QualType T) const {
2434 assert(T->isFunctionType() && "block of function types only");
2435 // Unique pointers, to guarantee there is only one block of a particular
2437 llvm::FoldingSetNodeID ID;
2438 BlockPointerType::Profile(ID, T);
2440 void *InsertPos = nullptr;
2441 if (BlockPointerType *PT =
2442 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2443 return QualType(PT, 0);
2445 // If the block pointee type isn't canonical, this won't be a canonical
2446 // type either so fill in the canonical type field.
2448 if (!T.isCanonical()) {
2449 Canonical = getBlockPointerType(getCanonicalType(T));
2451 // Get the new insert position for the node we care about.
2452 BlockPointerType *NewIP =
2453 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2454 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2456 BlockPointerType *New
2457 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2458 Types.push_back(New);
2459 BlockPointerTypes.InsertNode(New, InsertPos);
2460 return QualType(New, 0);
2463 /// getLValueReferenceType - Return the uniqued reference to the type for an
2464 /// lvalue reference to the specified type.
2466 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2467 assert(getCanonicalType(T) != OverloadTy &&
2468 "Unresolved overloaded function type");
2470 // Unique pointers, to guarantee there is only one pointer of a particular
2472 llvm::FoldingSetNodeID ID;
2473 ReferenceType::Profile(ID, T, SpelledAsLValue);
2475 void *InsertPos = nullptr;
2476 if (LValueReferenceType *RT =
2477 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2478 return QualType(RT, 0);
2480 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2482 // If the referencee type isn't canonical, this won't be a canonical type
2483 // either, so fill in the canonical type field.
2485 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2486 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2487 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2489 // Get the new insert position for the node we care about.
2490 LValueReferenceType *NewIP =
2491 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2492 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2495 LValueReferenceType *New
2496 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2498 Types.push_back(New);
2499 LValueReferenceTypes.InsertNode(New, InsertPos);
2501 return QualType(New, 0);
2504 /// getRValueReferenceType - Return the uniqued reference to the type for an
2505 /// rvalue reference to the specified type.
2506 QualType ASTContext::getRValueReferenceType(QualType T) const {
2507 // Unique pointers, to guarantee there is only one pointer of a particular
2509 llvm::FoldingSetNodeID ID;
2510 ReferenceType::Profile(ID, T, false);
2512 void *InsertPos = nullptr;
2513 if (RValueReferenceType *RT =
2514 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2515 return QualType(RT, 0);
2517 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2519 // If the referencee type isn't canonical, this won't be a canonical type
2520 // either, so fill in the canonical type field.
2522 if (InnerRef || !T.isCanonical()) {
2523 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2524 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2526 // Get the new insert position for the node we care about.
2527 RValueReferenceType *NewIP =
2528 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2529 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2532 RValueReferenceType *New
2533 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2534 Types.push_back(New);
2535 RValueReferenceTypes.InsertNode(New, InsertPos);
2536 return QualType(New, 0);
2539 /// getMemberPointerType - Return the uniqued reference to the type for a
2540 /// member pointer to the specified type, in the specified class.
2541 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2542 // Unique pointers, to guarantee there is only one pointer of a particular
2544 llvm::FoldingSetNodeID ID;
2545 MemberPointerType::Profile(ID, T, Cls);
2547 void *InsertPos = nullptr;
2548 if (MemberPointerType *PT =
2549 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2550 return QualType(PT, 0);
2552 // If the pointee or class type isn't canonical, this won't be a canonical
2553 // type either, so fill in the canonical type field.
2555 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2556 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2558 // Get the new insert position for the node we care about.
2559 MemberPointerType *NewIP =
2560 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2561 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2563 MemberPointerType *New
2564 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2565 Types.push_back(New);
2566 MemberPointerTypes.InsertNode(New, InsertPos);
2567 return QualType(New, 0);
2570 /// getConstantArrayType - Return the unique reference to the type for an
2571 /// array of the specified element type.
2572 QualType ASTContext::getConstantArrayType(QualType EltTy,
2573 const llvm::APInt &ArySizeIn,
2574 ArrayType::ArraySizeModifier ASM,
2575 unsigned IndexTypeQuals) const {
2576 assert((EltTy->isDependentType() ||
2577 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2578 "Constant array of VLAs is illegal!");
2580 // Convert the array size into a canonical width matching the pointer size for
2582 llvm::APInt ArySize(ArySizeIn);
2584 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2586 llvm::FoldingSetNodeID ID;
2587 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2589 void *InsertPos = nullptr;
2590 if (ConstantArrayType *ATP =
2591 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2592 return QualType(ATP, 0);
2594 // If the element type isn't canonical or has qualifiers, this won't
2595 // be a canonical type either, so fill in the canonical type field.
2597 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2598 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2599 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2600 ASM, IndexTypeQuals);
2601 Canon = getQualifiedType(Canon, canonSplit.Quals);
2603 // Get the new insert position for the node we care about.
2604 ConstantArrayType *NewIP =
2605 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2606 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2609 ConstantArrayType *New = new(*this,TypeAlignment)
2610 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2611 ConstantArrayTypes.InsertNode(New, InsertPos);
2612 Types.push_back(New);
2613 return QualType(New, 0);
2616 /// getVariableArrayDecayedType - Turns the given type, which may be
2617 /// variably-modified, into the corresponding type with all the known
2618 /// sizes replaced with [*].
2619 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2620 // Vastly most common case.
2621 if (!type->isVariablyModifiedType()) return type;
2625 SplitQualType split = type.getSplitDesugaredType();
2626 const Type *ty = split.Ty;
2627 switch (ty->getTypeClass()) {
2628 #define TYPE(Class, Base)
2629 #define ABSTRACT_TYPE(Class, Base)
2630 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2631 #include "clang/AST/TypeNodes.def"
2632 llvm_unreachable("didn't desugar past all non-canonical types?");
2634 // These types should never be variably-modified.
2638 case Type::ExtVector:
2639 case Type::DependentSizedExtVector:
2640 case Type::ObjCObject:
2641 case Type::ObjCInterface:
2642 case Type::ObjCObjectPointer:
2645 case Type::UnresolvedUsing:
2646 case Type::TypeOfExpr:
2648 case Type::Decltype:
2649 case Type::UnaryTransform:
2650 case Type::DependentName:
2651 case Type::InjectedClassName:
2652 case Type::TemplateSpecialization:
2653 case Type::DependentTemplateSpecialization:
2654 case Type::TemplateTypeParm:
2655 case Type::SubstTemplateTypeParmPack:
2657 case Type::PackExpansion:
2658 llvm_unreachable("type should never be variably-modified");
2660 // These types can be variably-modified but should never need to
2662 case Type::FunctionNoProto:
2663 case Type::FunctionProto:
2664 case Type::BlockPointer:
2665 case Type::MemberPointer:
2668 // These types can be variably-modified. All these modifications
2669 // preserve structure except as noted by comments.
2670 // TODO: if we ever care about optimizing VLAs, there are no-op
2671 // optimizations available here.
2673 result = getPointerType(getVariableArrayDecayedType(
2674 cast<PointerType>(ty)->getPointeeType()));
2677 case Type::LValueReference: {
2678 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2679 result = getLValueReferenceType(
2680 getVariableArrayDecayedType(lv->getPointeeType()),
2681 lv->isSpelledAsLValue());
2685 case Type::RValueReference: {
2686 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2687 result = getRValueReferenceType(
2688 getVariableArrayDecayedType(lv->getPointeeType()));
2692 case Type::Atomic: {
2693 const AtomicType *at = cast<AtomicType>(ty);
2694 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2698 case Type::ConstantArray: {
2699 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2700 result = getConstantArrayType(
2701 getVariableArrayDecayedType(cat->getElementType()),
2703 cat->getSizeModifier(),
2704 cat->getIndexTypeCVRQualifiers());
2708 case Type::DependentSizedArray: {
2709 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2710 result = getDependentSizedArrayType(
2711 getVariableArrayDecayedType(dat->getElementType()),
2713 dat->getSizeModifier(),
2714 dat->getIndexTypeCVRQualifiers(),
2715 dat->getBracketsRange());
2719 // Turn incomplete types into [*] types.
2720 case Type::IncompleteArray: {
2721 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2722 result = getVariableArrayType(
2723 getVariableArrayDecayedType(iat->getElementType()),
2726 iat->getIndexTypeCVRQualifiers(),
2731 // Turn VLA types into [*] types.
2732 case Type::VariableArray: {
2733 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2734 result = getVariableArrayType(
2735 getVariableArrayDecayedType(vat->getElementType()),
2738 vat->getIndexTypeCVRQualifiers(),
2739 vat->getBracketsRange());
2744 // Apply the top-level qualifiers from the original.
2745 return getQualifiedType(result, split.Quals);
2748 /// getVariableArrayType - Returns a non-unique reference to the type for a
2749 /// variable array of the specified element type.
2750 QualType ASTContext::getVariableArrayType(QualType EltTy,
2752 ArrayType::ArraySizeModifier ASM,
2753 unsigned IndexTypeQuals,
2754 SourceRange Brackets) const {
2755 // Since we don't unique expressions, it isn't possible to unique VLA's
2756 // that have an expression provided for their size.
2759 // Be sure to pull qualifiers off the element type.
2760 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2761 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2762 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2763 IndexTypeQuals, Brackets);
2764 Canon = getQualifiedType(Canon, canonSplit.Quals);
2767 VariableArrayType *New = new(*this, TypeAlignment)
2768 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2770 VariableArrayTypes.push_back(New);
2771 Types.push_back(New);
2772 return QualType(New, 0);
2775 /// getDependentSizedArrayType - Returns a non-unique reference to
2776 /// the type for a dependently-sized array of the specified element
2778 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2780 ArrayType::ArraySizeModifier ASM,
2781 unsigned elementTypeQuals,
2782 SourceRange brackets) const {
2783 assert((!numElements || numElements->isTypeDependent() ||
2784 numElements->isValueDependent()) &&
2785 "Size must be type- or value-dependent!");
2787 // Dependently-sized array types that do not have a specified number
2788 // of elements will have their sizes deduced from a dependent
2789 // initializer. We do no canonicalization here at all, which is okay
2790 // because they can't be used in most locations.
2792 DependentSizedArrayType *newType
2793 = new (*this, TypeAlignment)
2794 DependentSizedArrayType(*this, elementType, QualType(),
2795 numElements, ASM, elementTypeQuals,
2797 Types.push_back(newType);
2798 return QualType(newType, 0);
2801 // Otherwise, we actually build a new type every time, but we
2802 // also build a canonical type.
2804 SplitQualType canonElementType = getCanonicalType(elementType).split();
2806 void *insertPos = nullptr;
2807 llvm::FoldingSetNodeID ID;
2808 DependentSizedArrayType::Profile(ID, *this,
2809 QualType(canonElementType.Ty, 0),
2810 ASM, elementTypeQuals, numElements);
2812 // Look for an existing type with these properties.
2813 DependentSizedArrayType *canonTy =
2814 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2816 // If we don't have one, build one.
2818 canonTy = new (*this, TypeAlignment)
2819 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2820 QualType(), numElements, ASM, elementTypeQuals,
2822 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2823 Types.push_back(canonTy);
2826 // Apply qualifiers from the element type to the array.
2827 QualType canon = getQualifiedType(QualType(canonTy,0),
2828 canonElementType.Quals);
2830 // If we didn't need extra canonicalization for the element type or the size
2831 // expression, then just use that as our result.
2832 if (QualType(canonElementType.Ty, 0) == elementType &&
2833 canonTy->getSizeExpr() == numElements)
2836 // Otherwise, we need to build a type which follows the spelling
2837 // of the element type.
2838 DependentSizedArrayType *sugaredType
2839 = new (*this, TypeAlignment)
2840 DependentSizedArrayType(*this, elementType, canon, numElements,
2841 ASM, elementTypeQuals, brackets);
2842 Types.push_back(sugaredType);
2843 return QualType(sugaredType, 0);
2846 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2847 ArrayType::ArraySizeModifier ASM,
2848 unsigned elementTypeQuals) const {
2849 llvm::FoldingSetNodeID ID;
2850 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2852 void *insertPos = nullptr;
2853 if (IncompleteArrayType *iat =
2854 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2855 return QualType(iat, 0);
2857 // If the element type isn't canonical, this won't be a canonical type
2858 // either, so fill in the canonical type field. We also have to pull
2859 // qualifiers off the element type.
2862 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2863 SplitQualType canonSplit = getCanonicalType(elementType).split();
2864 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2865 ASM, elementTypeQuals);
2866 canon = getQualifiedType(canon, canonSplit.Quals);
2868 // Get the new insert position for the node we care about.
2869 IncompleteArrayType *existing =
2870 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2871 assert(!existing && "Shouldn't be in the map!"); (void) existing;
2874 IncompleteArrayType *newType = new (*this, TypeAlignment)
2875 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2877 IncompleteArrayTypes.InsertNode(newType, insertPos);
2878 Types.push_back(newType);
2879 return QualType(newType, 0);
2882 /// getVectorType - Return the unique reference to a vector type of
2883 /// the specified element type and size. VectorType must be a built-in type.
2884 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2885 VectorType::VectorKind VecKind) const {
2886 assert(vecType->isBuiltinType());
2888 // Check if we've already instantiated a vector of this type.
2889 llvm::FoldingSetNodeID ID;
2890 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2892 void *InsertPos = nullptr;
2893 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2894 return QualType(VTP, 0);
2896 // If the element type isn't canonical, this won't be a canonical type either,
2897 // so fill in the canonical type field.
2899 if (!vecType.isCanonical()) {
2900 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2902 // Get the new insert position for the node we care about.
2903 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2904 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2906 VectorType *New = new (*this, TypeAlignment)
2907 VectorType(vecType, NumElts, Canonical, VecKind);
2908 VectorTypes.InsertNode(New, InsertPos);
2909 Types.push_back(New);
2910 return QualType(New, 0);
2913 /// getExtVectorType - Return the unique reference to an extended vector type of
2914 /// the specified element type and size. VectorType must be a built-in type.
2916 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2917 assert(vecType->isBuiltinType() || vecType->isDependentType());
2919 // Check if we've already instantiated a vector of this type.
2920 llvm::FoldingSetNodeID ID;
2921 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2922 VectorType::GenericVector);
2923 void *InsertPos = nullptr;
2924 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2925 return QualType(VTP, 0);
2927 // If the element type isn't canonical, this won't be a canonical type either,
2928 // so fill in the canonical type field.
2930 if (!vecType.isCanonical()) {
2931 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2933 // Get the new insert position for the node we care about.
2934 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2935 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2937 ExtVectorType *New = new (*this, TypeAlignment)
2938 ExtVectorType(vecType, NumElts, Canonical);
2939 VectorTypes.InsertNode(New, InsertPos);
2940 Types.push_back(New);
2941 return QualType(New, 0);
2945 ASTContext::getDependentSizedExtVectorType(QualType vecType,
2947 SourceLocation AttrLoc) const {
2948 llvm::FoldingSetNodeID ID;
2949 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2952 void *InsertPos = nullptr;
2953 DependentSizedExtVectorType *Canon
2954 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2955 DependentSizedExtVectorType *New;
2957 // We already have a canonical version of this array type; use it as
2958 // the canonical type for a newly-built type.
2959 New = new (*this, TypeAlignment)
2960 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2963 QualType CanonVecTy = getCanonicalType(vecType);
2964 if (CanonVecTy == vecType) {
2965 New = new (*this, TypeAlignment)
2966 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2969 DependentSizedExtVectorType *CanonCheck
2970 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2971 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2973 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2975 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2977 New = new (*this, TypeAlignment)
2978 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2982 Types.push_back(New);
2983 return QualType(New, 0);
2986 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2989 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2990 const FunctionType::ExtInfo &Info) const {
2991 const CallingConv CallConv = Info.getCC();
2993 // Unique functions, to guarantee there is only one function of a particular
2995 llvm::FoldingSetNodeID ID;
2996 FunctionNoProtoType::Profile(ID, ResultTy, Info);
2998 void *InsertPos = nullptr;
2999 if (FunctionNoProtoType *FT =
3000 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3001 return QualType(FT, 0);
3004 if (!ResultTy.isCanonical()) {
3005 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
3007 // Get the new insert position for the node we care about.
3008 FunctionNoProtoType *NewIP =
3009 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3010 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3013 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
3014 FunctionNoProtoType *New = new (*this, TypeAlignment)
3015 FunctionNoProtoType(ResultTy, Canonical, newInfo);
3016 Types.push_back(New);
3017 FunctionNoProtoTypes.InsertNode(New, InsertPos);
3018 return QualType(New, 0);
3021 /// \brief Determine whether \p T is canonical as the result type of a function.
3022 static bool isCanonicalResultType(QualType T) {
3023 return T.isCanonical() &&
3024 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3025 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3029 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3030 CanQualType CanResultType = getCanonicalType(ResultType);
3032 // Canonical result types do not have ARC lifetime qualifiers.
3033 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3034 Qualifiers Qs = CanResultType.getQualifiers();
3035 Qs.removeObjCLifetime();
3036 return CanQualType::CreateUnsafe(
3037 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3040 return CanResultType;
3044 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
3045 const FunctionProtoType::ExtProtoInfo &EPI) const {
3046 size_t NumArgs = ArgArray.size();
3048 // Unique functions, to guarantee there is only one function of a particular
3050 llvm::FoldingSetNodeID ID;
3051 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3054 void *InsertPos = nullptr;
3055 if (FunctionProtoType *FTP =
3056 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3057 return QualType(FTP, 0);
3059 // Determine whether the type being created is already canonical or not.
3061 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
3062 !EPI.HasTrailingReturn;
3063 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
3064 if (!ArgArray[i].isCanonicalAsParam())
3065 isCanonical = false;
3067 // If this type isn't canonical, get the canonical version of it.
3068 // The exception spec is not part of the canonical type.
3071 SmallVector<QualType, 16> CanonicalArgs;
3072 CanonicalArgs.reserve(NumArgs);
3073 for (unsigned i = 0; i != NumArgs; ++i)
3074 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
3076 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
3077 CanonicalEPI.HasTrailingReturn = false;
3078 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3080 // Adjust the canonical function result type.
3081 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
3082 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
3084 // Get the new insert position for the node we care about.
3085 FunctionProtoType *NewIP =
3086 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3087 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3090 // FunctionProtoType objects are allocated with extra bytes after
3091 // them for three variable size arrays at the end:
3092 // - parameter types
3093 // - exception types
3094 // - consumed-arguments flags
3095 // Instead of the exception types, there could be a noexcept
3096 // expression, or information used to resolve the exception
3098 size_t Size = sizeof(FunctionProtoType) +
3099 NumArgs * sizeof(QualType);
3100 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3101 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3102 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3103 Size += sizeof(Expr*);
3104 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3105 Size += 2 * sizeof(FunctionDecl*);
3106 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3107 Size += sizeof(FunctionDecl*);
3109 if (EPI.ConsumedParameters)
3110 Size += NumArgs * sizeof(bool);
3112 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
3113 FunctionProtoType::ExtProtoInfo newEPI = EPI;
3114 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3115 Types.push_back(FTP);
3116 FunctionProtoTypes.InsertNode(FTP, InsertPos);
3117 return QualType(FTP, 0);
3121 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3122 if (!isa<CXXRecordDecl>(D)) return false;
3123 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3124 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3126 if (RD->getDescribedClassTemplate() &&
3127 !isa<ClassTemplateSpecializationDecl>(RD))
3133 /// getInjectedClassNameType - Return the unique reference to the
3134 /// injected class name type for the specified templated declaration.
3135 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
3136 QualType TST) const {
3137 assert(NeedsInjectedClassNameType(Decl));
3138 if (Decl->TypeForDecl) {
3139 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3140 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
3141 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3142 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3143 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3146 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
3147 Decl->TypeForDecl = newType;
3148 Types.push_back(newType);
3150 return QualType(Decl->TypeForDecl, 0);
3153 /// getTypeDeclType - Return the unique reference to the type for the
3154 /// specified type declaration.
3155 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3156 assert(Decl && "Passed null for Decl param");
3157 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3159 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3160 return getTypedefType(Typedef);
3162 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3163 "Template type parameter types are always available.");
3165 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
3166 assert(Record->isFirstDecl() && "struct/union has previous declaration");
3167 assert(!NeedsInjectedClassNameType(Record));
3168 return getRecordType(Record);
3169 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
3170 assert(Enum->isFirstDecl() && "enum has previous declaration");
3171 return getEnumType(Enum);
3172 } else if (const UnresolvedUsingTypenameDecl *Using =
3173 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3174 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3175 Decl->TypeForDecl = newType;
3176 Types.push_back(newType);
3178 llvm_unreachable("TypeDecl without a type?");
3180 return QualType(Decl->TypeForDecl, 0);
3183 /// getTypedefType - Return the unique reference to the type for the
3184 /// specified typedef name decl.
3186 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3187 QualType Canonical) const {
3188 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3190 if (Canonical.isNull())
3191 Canonical = getCanonicalType(Decl->getUnderlyingType());
3192 TypedefType *newType = new(*this, TypeAlignment)
3193 TypedefType(Type::Typedef, Decl, Canonical);
3194 Decl->TypeForDecl = newType;
3195 Types.push_back(newType);
3196 return QualType(newType, 0);
3199 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
3200 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3202 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3203 if (PrevDecl->TypeForDecl)
3204 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3206 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3207 Decl->TypeForDecl = newType;
3208 Types.push_back(newType);
3209 return QualType(newType, 0);
3212 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3213 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3215 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3216 if (PrevDecl->TypeForDecl)
3217 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3219 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3220 Decl->TypeForDecl = newType;
3221 Types.push_back(newType);
3222 return QualType(newType, 0);
3225 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3226 QualType modifiedType,
3227 QualType equivalentType) {
3228 llvm::FoldingSetNodeID id;
3229 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3231 void *insertPos = nullptr;
3232 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3233 if (type) return QualType(type, 0);
3235 QualType canon = getCanonicalType(equivalentType);
3236 type = new (*this, TypeAlignment)
3237 AttributedType(canon, attrKind, modifiedType, equivalentType);
3239 Types.push_back(type);
3240 AttributedTypes.InsertNode(type, insertPos);
3242 return QualType(type, 0);
3245 /// \brief Retrieve a substitution-result type.
3247 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3248 QualType Replacement) const {
3249 assert(Replacement.isCanonical()
3250 && "replacement types must always be canonical");
3252 llvm::FoldingSetNodeID ID;
3253 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3254 void *InsertPos = nullptr;
3255 SubstTemplateTypeParmType *SubstParm
3256 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3259 SubstParm = new (*this, TypeAlignment)
3260 SubstTemplateTypeParmType(Parm, Replacement);
3261 Types.push_back(SubstParm);
3262 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3265 return QualType(SubstParm, 0);
3268 /// \brief Retrieve a
3269 QualType ASTContext::getSubstTemplateTypeParmPackType(
3270 const TemplateTypeParmType *Parm,
3271 const TemplateArgument &ArgPack) {
3273 for (const auto &P : ArgPack.pack_elements()) {
3274 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3275 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
3279 llvm::FoldingSetNodeID ID;
3280 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3281 void *InsertPos = nullptr;
3282 if (SubstTemplateTypeParmPackType *SubstParm
3283 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3284 return QualType(SubstParm, 0);
3287 if (!Parm->isCanonicalUnqualified()) {
3288 Canon = getCanonicalType(QualType(Parm, 0));
3289 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3291 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3294 SubstTemplateTypeParmPackType *SubstParm
3295 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3297 Types.push_back(SubstParm);
3298 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3299 return QualType(SubstParm, 0);
3302 /// \brief Retrieve the template type parameter type for a template
3303 /// parameter or parameter pack with the given depth, index, and (optionally)
3305 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3307 TemplateTypeParmDecl *TTPDecl) const {
3308 llvm::FoldingSetNodeID ID;
3309 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3310 void *InsertPos = nullptr;
3311 TemplateTypeParmType *TypeParm
3312 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3315 return QualType(TypeParm, 0);
3318 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3319 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3321 TemplateTypeParmType *TypeCheck
3322 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3323 assert(!TypeCheck && "Template type parameter canonical type broken");
3326 TypeParm = new (*this, TypeAlignment)
3327 TemplateTypeParmType(Depth, Index, ParameterPack);
3329 Types.push_back(TypeParm);
3330 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3332 return QualType(TypeParm, 0);
3336 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3337 SourceLocation NameLoc,
3338 const TemplateArgumentListInfo &Args,
3339 QualType Underlying) const {
3340 assert(!Name.getAsDependentTemplateName() &&
3341 "No dependent template names here!");
3342 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3344 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3345 TemplateSpecializationTypeLoc TL =
3346 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3347 TL.setTemplateKeywordLoc(SourceLocation());
3348 TL.setTemplateNameLoc(NameLoc);
3349 TL.setLAngleLoc(Args.getLAngleLoc());
3350 TL.setRAngleLoc(Args.getRAngleLoc());
3351 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3352 TL.setArgLocInfo(i, Args[i].getLocInfo());
3357 ASTContext::getTemplateSpecializationType(TemplateName Template,
3358 const TemplateArgumentListInfo &Args,
3359 QualType Underlying) const {
3360 assert(!Template.getAsDependentTemplateName() &&
3361 "No dependent template names here!");
3363 unsigned NumArgs = Args.size();
3365 SmallVector<TemplateArgument, 4> ArgVec;
3366 ArgVec.reserve(NumArgs);
3367 for (unsigned i = 0; i != NumArgs; ++i)
3368 ArgVec.push_back(Args[i].getArgument());
3370 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
3375 static bool hasAnyPackExpansions(const TemplateArgument *Args,
3377 for (unsigned I = 0; I != NumArgs; ++I)
3378 if (Args[I].isPackExpansion())
3386 ASTContext::getTemplateSpecializationType(TemplateName Template,
3387 const TemplateArgument *Args,
3389 QualType Underlying) const {
3390 assert(!Template.getAsDependentTemplateName() &&
3391 "No dependent template names here!");
3392 // Look through qualified template names.
3393 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3394 Template = TemplateName(QTN->getTemplateDecl());
3397 Template.getAsTemplateDecl() &&
3398 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3400 if (!Underlying.isNull())
3401 CanonType = getCanonicalType(Underlying);
3403 // We can get here with an alias template when the specialization contains
3404 // a pack expansion that does not match up with a parameter pack.
3405 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3406 "Caller must compute aliased type");
3407 IsTypeAlias = false;
3408 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3412 // Allocate the (non-canonical) template specialization type, but don't
3413 // try to unique it: these types typically have location information that
3414 // we don't unique and don't want to lose.
3415 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3416 sizeof(TemplateArgument) * NumArgs +
3417 (IsTypeAlias? sizeof(QualType) : 0),
3419 TemplateSpecializationType *Spec
3420 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3421 IsTypeAlias ? Underlying : QualType());
3423 Types.push_back(Spec);
3424 return QualType(Spec, 0);
3428 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3429 const TemplateArgument *Args,
3430 unsigned NumArgs) const {
3431 assert(!Template.getAsDependentTemplateName() &&
3432 "No dependent template names here!");
3434 // Look through qualified template names.
3435 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3436 Template = TemplateName(QTN->getTemplateDecl());
3438 // Build the canonical template specialization type.
3439 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3440 SmallVector<TemplateArgument, 4> CanonArgs;
3441 CanonArgs.reserve(NumArgs);
3442 for (unsigned I = 0; I != NumArgs; ++I)
3443 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3445 // Determine whether this canonical template specialization type already
3447 llvm::FoldingSetNodeID ID;
3448 TemplateSpecializationType::Profile(ID, CanonTemplate,
3449 CanonArgs.data(), NumArgs, *this);
3451 void *InsertPos = nullptr;
3452 TemplateSpecializationType *Spec
3453 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3456 // Allocate a new canonical template specialization type.
3457 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3458 sizeof(TemplateArgument) * NumArgs),
3460 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3461 CanonArgs.data(), NumArgs,
3462 QualType(), QualType());
3463 Types.push_back(Spec);
3464 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3467 assert(Spec->isDependentType() &&
3468 "Non-dependent template-id type must have a canonical type");
3469 return QualType(Spec, 0);
3473 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3474 NestedNameSpecifier *NNS,
3475 QualType NamedType) const {
3476 llvm::FoldingSetNodeID ID;
3477 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3479 void *InsertPos = nullptr;
3480 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3482 return QualType(T, 0);
3484 QualType Canon = NamedType;
3485 if (!Canon.isCanonical()) {
3486 Canon = getCanonicalType(NamedType);
3487 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3488 assert(!CheckT && "Elaborated canonical type broken");
3492 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
3494 ElaboratedTypes.InsertNode(T, InsertPos);
3495 return QualType(T, 0);
3499 ASTContext::getParenType(QualType InnerType) const {
3500 llvm::FoldingSetNodeID ID;
3501 ParenType::Profile(ID, InnerType);
3503 void *InsertPos = nullptr;
3504 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3506 return QualType(T, 0);
3508 QualType Canon = InnerType;
3509 if (!Canon.isCanonical()) {
3510 Canon = getCanonicalType(InnerType);
3511 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3512 assert(!CheckT && "Paren canonical type broken");
3516 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
3518 ParenTypes.InsertNode(T, InsertPos);
3519 return QualType(T, 0);
3522 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3523 NestedNameSpecifier *NNS,
3524 const IdentifierInfo *Name,
3525 QualType Canon) const {
3526 if (Canon.isNull()) {
3527 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3528 ElaboratedTypeKeyword CanonKeyword = Keyword;
3529 if (Keyword == ETK_None)
3530 CanonKeyword = ETK_Typename;
3532 if (CanonNNS != NNS || CanonKeyword != Keyword)
3533 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3536 llvm::FoldingSetNodeID ID;
3537 DependentNameType::Profile(ID, Keyword, NNS, Name);
3539 void *InsertPos = nullptr;
3540 DependentNameType *T
3541 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3543 return QualType(T, 0);
3545 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
3547 DependentNameTypes.InsertNode(T, InsertPos);
3548 return QualType(T, 0);
3552 ASTContext::getDependentTemplateSpecializationType(
3553 ElaboratedTypeKeyword Keyword,
3554 NestedNameSpecifier *NNS,
3555 const IdentifierInfo *Name,
3556 const TemplateArgumentListInfo &Args) const {
3557 // TODO: avoid this copy
3558 SmallVector<TemplateArgument, 16> ArgCopy;
3559 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3560 ArgCopy.push_back(Args[I].getArgument());
3561 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3567 ASTContext::getDependentTemplateSpecializationType(
3568 ElaboratedTypeKeyword Keyword,
3569 NestedNameSpecifier *NNS,
3570 const IdentifierInfo *Name,
3572 const TemplateArgument *Args) const {
3573 assert((!NNS || NNS->isDependent()) &&
3574 "nested-name-specifier must be dependent");
3576 llvm::FoldingSetNodeID ID;
3577 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3578 Name, NumArgs, Args);
3580 void *InsertPos = nullptr;
3581 DependentTemplateSpecializationType *T
3582 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3584 return QualType(T, 0);
3586 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3588 ElaboratedTypeKeyword CanonKeyword = Keyword;
3589 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3591 bool AnyNonCanonArgs = false;
3592 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3593 for (unsigned I = 0; I != NumArgs; ++I) {
3594 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3595 if (!CanonArgs[I].structurallyEquals(Args[I]))
3596 AnyNonCanonArgs = true;
3600 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3601 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3605 // Find the insert position again.
3606 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3609 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3610 sizeof(TemplateArgument) * NumArgs),
3612 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3613 Name, NumArgs, Args, Canon);
3615 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3616 return QualType(T, 0);
3619 QualType ASTContext::getPackExpansionType(QualType Pattern,
3620 Optional<unsigned> NumExpansions) {
3621 llvm::FoldingSetNodeID ID;
3622 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3624 assert(Pattern->containsUnexpandedParameterPack() &&
3625 "Pack expansions must expand one or more parameter packs");
3626 void *InsertPos = nullptr;
3627 PackExpansionType *T
3628 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3630 return QualType(T, 0);
3633 if (!Pattern.isCanonical()) {
3634 Canon = getCanonicalType(Pattern);
3635 // The canonical type might not contain an unexpanded parameter pack, if it
3636 // contains an alias template specialization which ignores one of its
3638 if (Canon->containsUnexpandedParameterPack()) {
3639 Canon = getPackExpansionType(Canon, NumExpansions);
3641 // Find the insert position again, in case we inserted an element into
3642 // PackExpansionTypes and invalidated our insert position.
3643 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3647 T = new (*this, TypeAlignment)
3648 PackExpansionType(Pattern, Canon, NumExpansions);
3650 PackExpansionTypes.InsertNode(T, InsertPos);
3651 return QualType(T, 0);
3654 /// CmpProtocolNames - Comparison predicate for sorting protocols
3656 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3657 ObjCProtocolDecl *const *RHS) {
3658 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
3661 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
3662 unsigned NumProtocols) {
3663 if (NumProtocols == 0) return true;
3665 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3668 for (unsigned i = 1; i != NumProtocols; ++i)
3669 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
3670 Protocols[i]->getCanonicalDecl() != Protocols[i])
3676 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
3677 // Sort protocols, keyed by name.
3678 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
3681 for (ObjCProtocolDecl *&P : Protocols)
3682 P = P->getCanonicalDecl();
3684 // Remove duplicates.
3685 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3686 Protocols.erase(ProtocolsEnd, Protocols.end());
3689 QualType ASTContext::getObjCObjectType(QualType BaseType,
3690 ObjCProtocolDecl * const *Protocols,
3691 unsigned NumProtocols) const {
3692 return getObjCObjectType(BaseType, { },
3693 llvm::makeArrayRef(Protocols, NumProtocols),
3694 /*isKindOf=*/false);
3697 QualType ASTContext::getObjCObjectType(
3699 ArrayRef<QualType> typeArgs,
3700 ArrayRef<ObjCProtocolDecl *> protocols,
3701 bool isKindOf) const {
3702 // If the base type is an interface and there aren't any protocols or
3703 // type arguments to add, then the interface type will do just fine.
3704 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3705 isa<ObjCInterfaceType>(baseType))
3708 // Look in the folding set for an existing type.
3709 llvm::FoldingSetNodeID ID;
3710 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
3711 void *InsertPos = nullptr;
3712 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3713 return QualType(QT, 0);
3715 // Determine the type arguments to be used for canonicalization,
3716 // which may be explicitly specified here or written on the base
3718 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3719 if (effectiveTypeArgs.empty()) {
3720 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3721 effectiveTypeArgs = baseObject->getTypeArgs();
3724 // Build the canonical type, which has the canonical base type and a
3725 // sorted-and-uniqued list of protocols and the type arguments
3728 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3729 effectiveTypeArgs.end(),
3730 [&](QualType type) {
3731 return type.isCanonical();
3733 bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3735 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3736 // Determine the canonical type arguments.
3737 ArrayRef<QualType> canonTypeArgs;
3738 SmallVector<QualType, 4> canonTypeArgsVec;
3739 if (!typeArgsAreCanonical) {
3740 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3741 for (auto typeArg : effectiveTypeArgs)
3742 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3743 canonTypeArgs = canonTypeArgsVec;
3745 canonTypeArgs = effectiveTypeArgs;
3748 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3749 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3750 if (!protocolsSorted) {
3751 canonProtocolsVec.append(protocols.begin(), protocols.end());
3752 SortAndUniqueProtocols(canonProtocolsVec);
3753 canonProtocols = canonProtocolsVec;
3755 canonProtocols = protocols;
3758 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
3759 canonProtocols, isKindOf);
3761 // Regenerate InsertPos.
3762 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3765 unsigned size = sizeof(ObjCObjectTypeImpl);
3766 size += typeArgs.size() * sizeof(QualType);
3767 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3768 void *mem = Allocate(size, TypeAlignment);
3769 ObjCObjectTypeImpl *T =
3770 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3774 ObjCObjectTypes.InsertNode(T, InsertPos);
3775 return QualType(T, 0);
3778 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3779 /// protocol list adopt all protocols in QT's qualified-id protocol
3781 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3782 ObjCInterfaceDecl *IC) {
3783 if (!QT->isObjCQualifiedIdType())
3786 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3787 // If both the right and left sides have qualifiers.
3788 for (auto *Proto : OPT->quals()) {
3789 if (!IC->ClassImplementsProtocol(Proto, false))
3797 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3798 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
3800 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3801 ObjCInterfaceDecl *IDecl) {
3802 if (!QT->isObjCQualifiedIdType())
3804 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3807 if (!IDecl->hasDefinition())
3809 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3810 CollectInheritedProtocols(IDecl, InheritedProtocols);
3811 if (InheritedProtocols.empty())
3813 // Check that if every protocol in list of id<plist> conforms to a protcol
3814 // of IDecl's, then bridge casting is ok.
3815 bool Conforms = false;
3816 for (auto *Proto : OPT->quals()) {
3818 for (auto *PI : InheritedProtocols) {
3819 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3830 for (auto *PI : InheritedProtocols) {
3831 // If both the right and left sides have qualifiers.
3832 bool Adopts = false;
3833 for (auto *Proto : OPT->quals()) {
3834 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
3835 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
3844 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3845 /// the given object type.
3846 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
3847 llvm::FoldingSetNodeID ID;
3848 ObjCObjectPointerType::Profile(ID, ObjectT);
3850 void *InsertPos = nullptr;
3851 if (ObjCObjectPointerType *QT =
3852 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3853 return QualType(QT, 0);
3855 // Find the canonical object type.
3857 if (!ObjectT.isCanonical()) {
3858 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3860 // Regenerate InsertPos.
3861 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3865 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3866 ObjCObjectPointerType *QType =
3867 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
3869 Types.push_back(QType);
3870 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
3871 return QualType(QType, 0);
3874 /// getObjCInterfaceType - Return the unique reference to the type for the
3875 /// specified ObjC interface decl. The list of protocols is optional.
3876 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3877 ObjCInterfaceDecl *PrevDecl) const {
3878 if (Decl->TypeForDecl)
3879 return QualType(Decl->TypeForDecl, 0);
3882 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3883 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3884 return QualType(PrevDecl->TypeForDecl, 0);
3887 // Prefer the definition, if there is one.
3888 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3891 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3892 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3893 Decl->TypeForDecl = T;
3895 return QualType(T, 0);
3898 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3899 /// TypeOfExprType AST's (since expression's are never shared). For example,
3900 /// multiple declarations that refer to "typeof(x)" all contain different
3901 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
3902 /// on canonical type's (which are always unique).
3903 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
3904 TypeOfExprType *toe;
3905 if (tofExpr->isTypeDependent()) {
3906 llvm::FoldingSetNodeID ID;
3907 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3909 void *InsertPos = nullptr;
3910 DependentTypeOfExprType *Canon
3911 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3913 // We already have a "canonical" version of an identical, dependent
3914 // typeof(expr) type. Use that as our canonical type.
3915 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3916 QualType((TypeOfExprType*)Canon, 0));
3918 // Build a new, canonical typeof(expr) type.
3920 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3921 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3925 QualType Canonical = getCanonicalType(tofExpr->getType());
3926 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3928 Types.push_back(toe);
3929 return QualType(toe, 0);
3932 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3933 /// TypeOfType nodes. The only motivation to unique these nodes would be
3934 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3935 /// an issue. This doesn't affect the type checker, since it operates
3936 /// on canonical types (which are always unique).
3937 QualType ASTContext::getTypeOfType(QualType tofType) const {
3938 QualType Canonical = getCanonicalType(tofType);
3939 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3940 Types.push_back(tot);
3941 return QualType(tot, 0);
3944 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3945 /// nodes. This would never be helpful, since each such type has its own
3946 /// expression, and would not give a significant memory saving, since there
3947 /// is an Expr tree under each such type.
3948 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3951 // C++11 [temp.type]p2:
3952 // If an expression e involves a template parameter, decltype(e) denotes a
3953 // unique dependent type. Two such decltype-specifiers refer to the same
3954 // type only if their expressions are equivalent (14.5.6.1).
3955 if (e->isInstantiationDependent()) {
3956 llvm::FoldingSetNodeID ID;
3957 DependentDecltypeType::Profile(ID, *this, e);
3959 void *InsertPos = nullptr;
3960 DependentDecltypeType *Canon
3961 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3963 // Build a new, canonical typeof(expr) type.
3964 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3965 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3967 dt = new (*this, TypeAlignment)
3968 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
3970 dt = new (*this, TypeAlignment)
3971 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
3973 Types.push_back(dt);
3974 return QualType(dt, 0);
3977 /// getUnaryTransformationType - We don't unique these, since the memory
3978 /// savings are minimal and these are rare.
3979 QualType ASTContext::getUnaryTransformType(QualType BaseType,
3980 QualType UnderlyingType,
3981 UnaryTransformType::UTTKind Kind)
3983 UnaryTransformType *Ty =
3984 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3986 UnderlyingType->isDependentType() ?
3987 QualType() : getCanonicalType(UnderlyingType));
3988 Types.push_back(Ty);
3989 return QualType(Ty, 0);
3992 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
3993 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3994 /// canonical deduced-but-dependent 'auto' type.
3995 QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
3996 bool IsDependent) const {
3997 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
3998 return getAutoDeductType();
4000 // Look in the folding set for an existing type.
4001 void *InsertPos = nullptr;
4002 llvm::FoldingSetNodeID ID;
4003 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
4004 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4005 return QualType(AT, 0);
4007 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
4010 Types.push_back(AT);
4012 AutoTypes.InsertNode(AT, InsertPos);
4013 return QualType(AT, 0);
4016 /// getAtomicType - Return the uniqued reference to the atomic type for
4017 /// the given value type.
4018 QualType ASTContext::getAtomicType(QualType T) const {
4019 // Unique pointers, to guarantee there is only one pointer of a particular
4021 llvm::FoldingSetNodeID ID;
4022 AtomicType::Profile(ID, T);
4024 void *InsertPos = nullptr;
4025 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4026 return QualType(AT, 0);
4028 // If the atomic value type isn't canonical, this won't be a canonical type
4029 // either, so fill in the canonical type field.
4031 if (!T.isCanonical()) {
4032 Canonical = getAtomicType(getCanonicalType(T));
4034 // Get the new insert position for the node we care about.
4035 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
4036 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4038 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4039 Types.push_back(New);
4040 AtomicTypes.InsertNode(New, InsertPos);
4041 return QualType(New, 0);
4044 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
4045 QualType ASTContext::getAutoDeductType() const {
4046 if (AutoDeductTy.isNull())
4047 AutoDeductTy = QualType(
4048 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
4049 /*dependent*/false),
4051 return AutoDeductTy;
4054 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4055 QualType ASTContext::getAutoRRefDeductType() const {
4056 if (AutoRRefDeductTy.isNull())
4057 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4058 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4059 return AutoRRefDeductTy;
4062 /// getTagDeclType - Return the unique reference to the type for the
4063 /// specified TagDecl (struct/union/class/enum) decl.
4064 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
4066 // FIXME: What is the design on getTagDeclType when it requires casting
4067 // away const? mutable?
4068 return getTypeDeclType(const_cast<TagDecl*>(Decl));
4071 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4072 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4073 /// needs to agree with the definition in <stddef.h>.
4074 CanQualType ASTContext::getSizeType() const {
4075 return getFromTargetType(Target->getSizeType());
4078 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4079 CanQualType ASTContext::getIntMaxType() const {
4080 return getFromTargetType(Target->getIntMaxType());
4083 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4084 CanQualType ASTContext::getUIntMaxType() const {
4085 return getFromTargetType(Target->getUIntMaxType());
4088 /// getSignedWCharType - Return the type of "signed wchar_t".
4089 /// Used when in C++, as a GCC extension.
4090 QualType ASTContext::getSignedWCharType() const {
4091 // FIXME: derive from "Target" ?
4095 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4096 /// Used when in C++, as a GCC extension.
4097 QualType ASTContext::getUnsignedWCharType() const {
4098 // FIXME: derive from "Target" ?
4099 return UnsignedIntTy;
4102 QualType ASTContext::getIntPtrType() const {
4103 return getFromTargetType(Target->getIntPtrType());
4106 QualType ASTContext::getUIntPtrType() const {
4107 return getCorrespondingUnsignedType(getIntPtrType());
4110 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
4111 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4112 QualType ASTContext::getPointerDiffType() const {
4113 return getFromTargetType(Target->getPtrDiffType(0));
4116 /// \brief Return the unique type for "pid_t" defined in
4117 /// <sys/types.h>. We need this to compute the correct type for vfork().
4118 QualType ASTContext::getProcessIDType() const {
4119 return getFromTargetType(Target->getProcessIDType());
4122 //===----------------------------------------------------------------------===//
4124 //===----------------------------------------------------------------------===//
4126 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
4127 // Push qualifiers into arrays, and then discard any remaining
4129 T = getCanonicalType(T);
4130 T = getVariableArrayDecayedType(T);
4131 const Type *Ty = T.getTypePtr();
4133 if (isa<ArrayType>(Ty)) {
4134 Result = getArrayDecayedType(QualType(Ty,0));
4135 } else if (isa<FunctionType>(Ty)) {
4136 Result = getPointerType(QualType(Ty, 0));
4138 Result = QualType(Ty, 0);
4141 return CanQualType::CreateUnsafe(Result);
4144 QualType ASTContext::getUnqualifiedArrayType(QualType type,
4145 Qualifiers &quals) {
4146 SplitQualType splitType = type.getSplitUnqualifiedType();
4148 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4149 // the unqualified desugared type and then drops it on the floor.
4150 // We then have to strip that sugar back off with
4151 // getUnqualifiedDesugaredType(), which is silly.
4152 const ArrayType *AT =
4153 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
4155 // If we don't have an array, just use the results in splitType.
4157 quals = splitType.Quals;
4158 return QualType(splitType.Ty, 0);
4161 // Otherwise, recurse on the array's element type.
4162 QualType elementType = AT->getElementType();
4163 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4165 // If that didn't change the element type, AT has no qualifiers, so we
4166 // can just use the results in splitType.
4167 if (elementType == unqualElementType) {
4168 assert(quals.empty()); // from the recursive call
4169 quals = splitType.Quals;
4170 return QualType(splitType.Ty, 0);
4173 // Otherwise, add in the qualifiers from the outermost type, then
4174 // build the type back up.
4175 quals.addConsistentQualifiers(splitType.Quals);
4177 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4178 return getConstantArrayType(unqualElementType, CAT->getSize(),
4179 CAT->getSizeModifier(), 0);
4182 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
4183 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
4186 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
4187 return getVariableArrayType(unqualElementType,
4189 VAT->getSizeModifier(),
4190 VAT->getIndexTypeCVRQualifiers(),
4191 VAT->getBracketsRange());
4194 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
4195 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
4196 DSAT->getSizeModifier(), 0,
4200 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4201 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4202 /// they point to and return true. If T1 and T2 aren't pointer types
4203 /// or pointer-to-member types, or if they are not similar at this
4204 /// level, returns false and leaves T1 and T2 unchanged. Top-level
4205 /// qualifiers on T1 and T2 are ignored. This function will typically
4206 /// be called in a loop that successively "unwraps" pointer and
4207 /// pointer-to-member types to compare them at each level.
4208 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4209 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4210 *T2PtrType = T2->getAs<PointerType>();
4211 if (T1PtrType && T2PtrType) {
4212 T1 = T1PtrType->getPointeeType();
4213 T2 = T2PtrType->getPointeeType();
4217 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4218 *T2MPType = T2->getAs<MemberPointerType>();
4219 if (T1MPType && T2MPType &&
4220 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4221 QualType(T2MPType->getClass(), 0))) {
4222 T1 = T1MPType->getPointeeType();
4223 T2 = T2MPType->getPointeeType();
4227 if (getLangOpts().ObjC1) {
4228 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4229 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4230 if (T1OPType && T2OPType) {
4231 T1 = T1OPType->getPointeeType();
4232 T2 = T2OPType->getPointeeType();
4237 // FIXME: Block pointers, too?
4243 ASTContext::getNameForTemplate(TemplateName Name,
4244 SourceLocation NameLoc) const {
4245 switch (Name.getKind()) {
4246 case TemplateName::QualifiedTemplate:
4247 case TemplateName::Template:
4248 // DNInfo work in progress: CHECKME: what about DNLoc?
4249 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4252 case TemplateName::OverloadedTemplate: {
4253 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4254 // DNInfo work in progress: CHECKME: what about DNLoc?
4255 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4258 case TemplateName::DependentTemplate: {
4259 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4260 DeclarationName DName;
4261 if (DTN->isIdentifier()) {
4262 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4263 return DeclarationNameInfo(DName, NameLoc);
4265 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4266 // DNInfo work in progress: FIXME: source locations?
4267 DeclarationNameLoc DNLoc;
4268 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4269 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4270 return DeclarationNameInfo(DName, NameLoc, DNLoc);
4274 case TemplateName::SubstTemplateTemplateParm: {
4275 SubstTemplateTemplateParmStorage *subst
4276 = Name.getAsSubstTemplateTemplateParm();
4277 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4281 case TemplateName::SubstTemplateTemplateParmPack: {
4282 SubstTemplateTemplateParmPackStorage *subst
4283 = Name.getAsSubstTemplateTemplateParmPack();
4284 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4289 llvm_unreachable("bad template name kind!");
4292 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4293 switch (Name.getKind()) {
4294 case TemplateName::QualifiedTemplate:
4295 case TemplateName::Template: {
4296 TemplateDecl *Template = Name.getAsTemplateDecl();
4297 if (TemplateTemplateParmDecl *TTP
4298 = dyn_cast<TemplateTemplateParmDecl>(Template))
4299 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4301 // The canonical template name is the canonical template declaration.
4302 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4305 case TemplateName::OverloadedTemplate:
4306 llvm_unreachable("cannot canonicalize overloaded template");
4308 case TemplateName::DependentTemplate: {
4309 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4310 assert(DTN && "Non-dependent template names must refer to template decls.");
4311 return DTN->CanonicalTemplateName;
4314 case TemplateName::SubstTemplateTemplateParm: {
4315 SubstTemplateTemplateParmStorage *subst
4316 = Name.getAsSubstTemplateTemplateParm();
4317 return getCanonicalTemplateName(subst->getReplacement());
4320 case TemplateName::SubstTemplateTemplateParmPack: {
4321 SubstTemplateTemplateParmPackStorage *subst
4322 = Name.getAsSubstTemplateTemplateParmPack();
4323 TemplateTemplateParmDecl *canonParameter
4324 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4325 TemplateArgument canonArgPack
4326 = getCanonicalTemplateArgument(subst->getArgumentPack());
4327 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4331 llvm_unreachable("bad template name!");
4334 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4335 X = getCanonicalTemplateName(X);
4336 Y = getCanonicalTemplateName(Y);
4337 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4341 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4342 switch (Arg.getKind()) {
4343 case TemplateArgument::Null:
4346 case TemplateArgument::Expression:
4349 case TemplateArgument::Declaration: {
4350 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4351 return TemplateArgument(D, Arg.getParamTypeForDecl());
4354 case TemplateArgument::NullPtr:
4355 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4358 case TemplateArgument::Template:
4359 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4361 case TemplateArgument::TemplateExpansion:
4362 return TemplateArgument(getCanonicalTemplateName(
4363 Arg.getAsTemplateOrTemplatePattern()),
4364 Arg.getNumTemplateExpansions());
4366 case TemplateArgument::Integral:
4367 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4369 case TemplateArgument::Type:
4370 return TemplateArgument(getCanonicalType(Arg.getAsType()));
4372 case TemplateArgument::Pack: {
4373 if (Arg.pack_size() == 0)
4376 TemplateArgument *CanonArgs
4377 = new (*this) TemplateArgument[Arg.pack_size()];
4379 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4380 AEnd = Arg.pack_end();
4381 A != AEnd; (void)++A, ++Idx)
4382 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4384 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
4388 // Silence GCC warning
4389 llvm_unreachable("Unhandled template argument kind");
4392 NestedNameSpecifier *
4393 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4397 switch (NNS->getKind()) {
4398 case NestedNameSpecifier::Identifier:
4399 // Canonicalize the prefix but keep the identifier the same.
4400 return NestedNameSpecifier::Create(*this,
4401 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4402 NNS->getAsIdentifier());
4404 case NestedNameSpecifier::Namespace:
4405 // A namespace is canonical; build a nested-name-specifier with
4406 // this namespace and no prefix.
4407 return NestedNameSpecifier::Create(*this, nullptr,
4408 NNS->getAsNamespace()->getOriginalNamespace());
4410 case NestedNameSpecifier::NamespaceAlias:
4411 // A namespace is canonical; build a nested-name-specifier with
4412 // this namespace and no prefix.
4413 return NestedNameSpecifier::Create(*this, nullptr,
4414 NNS->getAsNamespaceAlias()->getNamespace()
4415 ->getOriginalNamespace());
4417 case NestedNameSpecifier::TypeSpec:
4418 case NestedNameSpecifier::TypeSpecWithTemplate: {
4419 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4421 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4422 // break it apart into its prefix and identifier, then reconsititute those
4423 // as the canonical nested-name-specifier. This is required to canonicalize
4424 // a dependent nested-name-specifier involving typedefs of dependent-name
4426 // typedef typename T::type T1;
4427 // typedef typename T1::type T2;
4428 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4429 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4430 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4432 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4433 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4435 return NestedNameSpecifier::Create(*this, nullptr, false,
4436 const_cast<Type *>(T.getTypePtr()));
4439 case NestedNameSpecifier::Global:
4440 case NestedNameSpecifier::Super:
4441 // The global specifier and __super specifer are canonical and unique.
4445 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4448 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4449 // Handle the non-qualified case efficiently.
4450 if (!T.hasLocalQualifiers()) {
4451 // Handle the common positive case fast.
4452 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4456 // Handle the common negative case fast.
4457 if (!isa<ArrayType>(T.getCanonicalType()))
4460 // Apply any qualifiers from the array type to the element type. This
4461 // implements C99 6.7.3p8: "If the specification of an array type includes
4462 // any type qualifiers, the element type is so qualified, not the array type."
4464 // If we get here, we either have type qualifiers on the type, or we have
4465 // sugar such as a typedef in the way. If we have type qualifiers on the type
4466 // we must propagate them down into the element type.
4468 SplitQualType split = T.getSplitDesugaredType();
4469 Qualifiers qs = split.Quals;
4471 // If we have a simple case, just return now.
4472 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4473 if (!ATy || qs.empty())
4476 // Otherwise, we have an array and we have qualifiers on it. Push the
4477 // qualifiers into the array element type and return a new array type.
4478 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4480 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4481 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4482 CAT->getSizeModifier(),
4483 CAT->getIndexTypeCVRQualifiers()));
4484 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4485 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4486 IAT->getSizeModifier(),
4487 IAT->getIndexTypeCVRQualifiers()));
4489 if (const DependentSizedArrayType *DSAT
4490 = dyn_cast<DependentSizedArrayType>(ATy))
4491 return cast<ArrayType>(
4492 getDependentSizedArrayType(NewEltTy,
4493 DSAT->getSizeExpr(),
4494 DSAT->getSizeModifier(),
4495 DSAT->getIndexTypeCVRQualifiers(),
4496 DSAT->getBracketsRange()));
4498 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4499 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4501 VAT->getSizeModifier(),
4502 VAT->getIndexTypeCVRQualifiers(),
4503 VAT->getBracketsRange()));
4506 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4507 if (T->isArrayType() || T->isFunctionType())
4508 return getDecayedType(T);
4512 QualType ASTContext::getSignatureParameterType(QualType T) const {
4513 T = getVariableArrayDecayedType(T);
4514 T = getAdjustedParameterType(T);
4515 return T.getUnqualifiedType();
4518 QualType ASTContext::getExceptionObjectType(QualType T) const {
4519 // C++ [except.throw]p3:
4520 // A throw-expression initializes a temporary object, called the exception
4521 // object, the type of which is determined by removing any top-level
4522 // cv-qualifiers from the static type of the operand of throw and adjusting
4523 // the type from "array of T" or "function returning T" to "pointer to T"
4524 // or "pointer to function returning T", [...]
4525 T = getVariableArrayDecayedType(T);
4526 if (T->isArrayType() || T->isFunctionType())
4527 T = getDecayedType(T);
4528 return T.getUnqualifiedType();
4531 /// getArrayDecayedType - Return the properly qualified result of decaying the
4532 /// specified array type to a pointer. This operation is non-trivial when
4533 /// handling typedefs etc. The canonical type of "T" must be an array type,
4534 /// this returns a pointer to a properly qualified element of the array.
4536 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4537 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4538 // Get the element type with 'getAsArrayType' so that we don't lose any
4539 // typedefs in the element type of the array. This also handles propagation
4540 // of type qualifiers from the array type into the element type if present
4542 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4543 assert(PrettyArrayType && "Not an array type!");
4545 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4547 // int x[restrict 4] -> int *restrict
4548 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
4551 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4552 return getBaseElementType(array->getElementType());
4555 QualType ASTContext::getBaseElementType(QualType type) const {
4558 SplitQualType split = type.getSplitDesugaredType();
4559 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4562 type = array->getElementType();
4563 qs.addConsistentQualifiers(split.Quals);
4566 return getQualifiedType(type, qs);
4569 /// getConstantArrayElementCount - Returns number of constant array elements.
4571 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4572 uint64_t ElementCount = 1;
4574 ElementCount *= CA->getSize().getZExtValue();
4575 CA = dyn_cast_or_null<ConstantArrayType>(
4576 CA->getElementType()->getAsArrayTypeUnsafe());
4578 return ElementCount;
4581 /// getFloatingRank - Return a relative rank for floating point types.
4582 /// This routine will assert if passed a built-in type that isn't a float.
4583 static FloatingRank getFloatingRank(QualType T) {
4584 if (const ComplexType *CT = T->getAs<ComplexType>())
4585 return getFloatingRank(CT->getElementType());
4587 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4588 switch (T->getAs<BuiltinType>()->getKind()) {
4589 default: llvm_unreachable("getFloatingRank(): not a floating type");
4590 case BuiltinType::Half: return HalfRank;
4591 case BuiltinType::Float: return FloatRank;
4592 case BuiltinType::Double: return DoubleRank;
4593 case BuiltinType::LongDouble: return LongDoubleRank;
4597 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4598 /// point or a complex type (based on typeDomain/typeSize).
4599 /// 'typeDomain' is a real floating point or complex type.
4600 /// 'typeSize' is a real floating point or complex type.
4601 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4602 QualType Domain) const {
4603 FloatingRank EltRank = getFloatingRank(Size);
4604 if (Domain->isComplexType()) {
4606 case HalfRank: llvm_unreachable("Complex half is not supported");
4607 case FloatRank: return FloatComplexTy;
4608 case DoubleRank: return DoubleComplexTy;
4609 case LongDoubleRank: return LongDoubleComplexTy;
4613 assert(Domain->isRealFloatingType() && "Unknown domain!");
4615 case HalfRank: return HalfTy;
4616 case FloatRank: return FloatTy;
4617 case DoubleRank: return DoubleTy;
4618 case LongDoubleRank: return LongDoubleTy;
4620 llvm_unreachable("getFloatingRank(): illegal value for rank");
4623 /// getFloatingTypeOrder - Compare the rank of the two specified floating
4624 /// point types, ignoring the domain of the type (i.e. 'double' ==
4625 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
4626 /// LHS < RHS, return -1.
4627 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
4628 FloatingRank LHSR = getFloatingRank(LHS);
4629 FloatingRank RHSR = getFloatingRank(RHS);
4638 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4639 /// routine will assert if passed a built-in type that isn't an integer or enum,
4640 /// or if it is not canonicalized.
4641 unsigned ASTContext::getIntegerRank(const Type *T) const {
4642 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
4644 switch (cast<BuiltinType>(T)->getKind()) {
4645 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
4646 case BuiltinType::Bool:
4647 return 1 + (getIntWidth(BoolTy) << 3);
4648 case BuiltinType::Char_S:
4649 case BuiltinType::Char_U:
4650 case BuiltinType::SChar:
4651 case BuiltinType::UChar:
4652 return 2 + (getIntWidth(CharTy) << 3);
4653 case BuiltinType::Short:
4654 case BuiltinType::UShort:
4655 return 3 + (getIntWidth(ShortTy) << 3);
4656 case BuiltinType::Int:
4657 case BuiltinType::UInt:
4658 return 4 + (getIntWidth(IntTy) << 3);
4659 case BuiltinType::Long:
4660 case BuiltinType::ULong:
4661 return 5 + (getIntWidth(LongTy) << 3);
4662 case BuiltinType::LongLong:
4663 case BuiltinType::ULongLong:
4664 return 6 + (getIntWidth(LongLongTy) << 3);
4665 case BuiltinType::Int128:
4666 case BuiltinType::UInt128:
4667 return 7 + (getIntWidth(Int128Ty) << 3);
4671 /// \brief Whether this is a promotable bitfield reference according
4672 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4674 /// \returns the type this bit-field will promote to, or NULL if no
4675 /// promotion occurs.
4676 QualType ASTContext::isPromotableBitField(Expr *E) const {
4677 if (E->isTypeDependent() || E->isValueDependent())
4680 // FIXME: We should not do this unless E->refersToBitField() is true. This
4681 // matters in C where getSourceBitField() will find bit-fields for various
4682 // cases where the source expression is not a bit-field designator.
4684 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
4688 QualType FT = Field->getType();
4690 uint64_t BitWidth = Field->getBitWidthValue(*this);
4691 uint64_t IntSize = getTypeSize(IntTy);
4692 // C++ [conv.prom]p5:
4693 // A prvalue for an integral bit-field can be converted to a prvalue of type
4694 // int if int can represent all the values of the bit-field; otherwise, it
4695 // can be converted to unsigned int if unsigned int can represent all the
4696 // values of the bit-field. If the bit-field is larger yet, no integral
4697 // promotion applies to it.
4699 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4700 // If an int can represent all values of the original type (as restricted by
4701 // the width, for a bit-field), the value is converted to an int; otherwise,
4702 // it is converted to an unsigned int.
4704 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4705 // We perform that promotion here to match GCC and C++.
4706 if (BitWidth < IntSize)
4709 if (BitWidth == IntSize)
4710 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4712 // Types bigger than int are not subject to promotions, and therefore act
4713 // like the base type. GCC has some weird bugs in this area that we
4714 // deliberately do not follow (GCC follows a pre-standard resolution to
4715 // C's DR315 which treats bit-width as being part of the type, and this leaks
4716 // into their semantics in some cases).
4720 /// getPromotedIntegerType - Returns the type that Promotable will
4721 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4723 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
4724 assert(!Promotable.isNull());
4725 assert(Promotable->isPromotableIntegerType());
4726 if (const EnumType *ET = Promotable->getAs<EnumType>())
4727 return ET->getDecl()->getPromotionType();
4729 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4730 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4731 // (3.9.1) can be converted to a prvalue of the first of the following
4732 // types that can represent all the values of its underlying type:
4733 // int, unsigned int, long int, unsigned long int, long long int, or
4734 // unsigned long long int [...]
4735 // FIXME: Is there some better way to compute this?
4736 if (BT->getKind() == BuiltinType::WChar_S ||
4737 BT->getKind() == BuiltinType::WChar_U ||
4738 BT->getKind() == BuiltinType::Char16 ||
4739 BT->getKind() == BuiltinType::Char32) {
4740 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4741 uint64_t FromSize = getTypeSize(BT);
4742 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4743 LongLongTy, UnsignedLongLongTy };
4744 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4745 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4746 if (FromSize < ToSize ||
4747 (FromSize == ToSize &&
4748 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4749 return PromoteTypes[Idx];
4751 llvm_unreachable("char type should fit into long long");
4755 // At this point, we should have a signed or unsigned integer type.
4756 if (Promotable->isSignedIntegerType())
4758 uint64_t PromotableSize = getIntWidth(Promotable);
4759 uint64_t IntSize = getIntWidth(IntTy);
4760 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4761 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4764 /// \brief Recurses in pointer/array types until it finds an objc retainable
4765 /// type and returns its ownership.
4766 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4767 while (!T.isNull()) {
4768 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4769 return T.getObjCLifetime();
4770 if (T->isArrayType())
4771 T = getBaseElementType(T);
4772 else if (const PointerType *PT = T->getAs<PointerType>())
4773 T = PT->getPointeeType();
4774 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4775 T = RT->getPointeeType();
4780 return Qualifiers::OCL_None;
4783 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4784 // Incomplete enum types are not treated as integer types.
4785 // FIXME: In C++, enum types are never integer types.
4786 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4787 return ET->getDecl()->getIntegerType().getTypePtr();
4791 /// getIntegerTypeOrder - Returns the highest ranked integer type:
4792 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
4793 /// LHS < RHS, return -1.
4794 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
4795 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4796 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
4798 // Unwrap enums to their underlying type.
4799 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4800 LHSC = getIntegerTypeForEnum(ET);
4801 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4802 RHSC = getIntegerTypeForEnum(ET);
4804 if (LHSC == RHSC) return 0;
4806 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4807 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
4809 unsigned LHSRank = getIntegerRank(LHSC);
4810 unsigned RHSRank = getIntegerRank(RHSC);
4812 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4813 if (LHSRank == RHSRank) return 0;
4814 return LHSRank > RHSRank ? 1 : -1;
4817 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4819 // If the unsigned [LHS] type is larger, return it.
4820 if (LHSRank >= RHSRank)
4823 // If the signed type can represent all values of the unsigned type, it
4824 // wins. Because we are dealing with 2's complement and types that are
4825 // powers of two larger than each other, this is always safe.
4829 // If the unsigned [RHS] type is larger, return it.
4830 if (RHSRank >= LHSRank)
4833 // If the signed type can represent all values of the unsigned type, it
4834 // wins. Because we are dealing with 2's complement and types that are
4835 // powers of two larger than each other, this is always safe.
4839 // getCFConstantStringType - Return the type used for constant CFStrings.
4840 QualType ASTContext::getCFConstantStringType() const {
4841 if (!CFConstantStringTypeDecl) {
4842 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
4843 CFConstantStringTypeDecl->startDefinition();
4845 QualType FieldTypes[4];
4848 FieldTypes[0] = getPointerType(IntTy.withConst());
4850 FieldTypes[1] = IntTy;
4852 FieldTypes[2] = getPointerType(CharTy.withConst());
4854 FieldTypes[3] = LongTy;
4857 for (unsigned i = 0; i < 4; ++i) {
4858 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
4860 SourceLocation(), nullptr,
4861 FieldTypes[i], /*TInfo=*/nullptr,
4862 /*BitWidth=*/nullptr,
4865 Field->setAccess(AS_public);
4866 CFConstantStringTypeDecl->addDecl(Field);
4869 CFConstantStringTypeDecl->completeDefinition();
4872 return getTagDeclType(CFConstantStringTypeDecl);
4875 QualType ASTContext::getObjCSuperType() const {
4876 if (ObjCSuperType.isNull()) {
4877 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
4878 TUDecl->addDecl(ObjCSuperTypeDecl);
4879 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4881 return ObjCSuperType;
4884 void ASTContext::setCFConstantStringType(QualType T) {
4885 const RecordType *Rec = T->getAs<RecordType>();
4886 assert(Rec && "Invalid CFConstantStringType");
4887 CFConstantStringTypeDecl = Rec->getDecl();
4890 QualType ASTContext::getBlockDescriptorType() const {
4891 if (BlockDescriptorType)
4892 return getTagDeclType(BlockDescriptorType);
4895 // FIXME: Needs the FlagAppleBlock bit.
4896 RD = buildImplicitRecord("__block_descriptor");
4897 RD->startDefinition();
4899 QualType FieldTypes[] = {
4904 static const char *const FieldNames[] = {
4909 for (size_t i = 0; i < 2; ++i) {
4910 FieldDecl *Field = FieldDecl::Create(
4911 *this, RD, SourceLocation(), SourceLocation(),
4912 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4913 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
4914 Field->setAccess(AS_public);
4918 RD->completeDefinition();
4920 BlockDescriptorType = RD;
4922 return getTagDeclType(BlockDescriptorType);
4925 QualType ASTContext::getBlockDescriptorExtendedType() const {
4926 if (BlockDescriptorExtendedType)
4927 return getTagDeclType(BlockDescriptorExtendedType);
4930 // FIXME: Needs the FlagAppleBlock bit.
4931 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4932 RD->startDefinition();
4934 QualType FieldTypes[] = {
4937 getPointerType(VoidPtrTy),
4938 getPointerType(VoidPtrTy)
4941 static const char *const FieldNames[] = {
4948 for (size_t i = 0; i < 4; ++i) {
4949 FieldDecl *Field = FieldDecl::Create(
4950 *this, RD, SourceLocation(), SourceLocation(),
4951 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4952 /*BitWidth=*/nullptr,
4953 /*Mutable=*/false, ICIS_NoInit);
4954 Field->setAccess(AS_public);
4958 RD->completeDefinition();
4960 BlockDescriptorExtendedType = RD;
4961 return getTagDeclType(BlockDescriptorExtendedType);
4964 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4965 /// requires copy/dispose. Note that this must match the logic
4966 /// in buildByrefHelpers.
4967 bool ASTContext::BlockRequiresCopying(QualType Ty,
4969 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4970 const Expr *copyExpr = getBlockVarCopyInits(D);
4971 if (!copyExpr && record->hasTrivialDestructor()) return false;
4976 if (!Ty->isObjCRetainableType()) return false;
4978 Qualifiers qs = Ty.getQualifiers();
4980 // If we have lifetime, that dominates.
4981 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4983 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4985 // These are just bits as far as the runtime is concerned.
4986 case Qualifiers::OCL_ExplicitNone:
4987 case Qualifiers::OCL_Autoreleasing:
4990 // Tell the runtime that this is ARC __weak, called by the
4992 case Qualifiers::OCL_Weak:
4993 // ARC __strong __block variables need to be retained.
4994 case Qualifiers::OCL_Strong:
4997 llvm_unreachable("fell out of lifetime switch!");
4999 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5000 Ty->isObjCObjectPointerType());
5003 bool ASTContext::getByrefLifetime(QualType Ty,
5004 Qualifiers::ObjCLifetime &LifeTime,
5005 bool &HasByrefExtendedLayout) const {
5007 if (!getLangOpts().ObjC1 ||
5008 getLangOpts().getGC() != LangOptions::NonGC)
5011 HasByrefExtendedLayout = false;
5012 if (Ty->isRecordType()) {
5013 HasByrefExtendedLayout = true;
5014 LifeTime = Qualifiers::OCL_None;
5015 } else if ((LifeTime = Ty.getObjCLifetime())) {
5016 // Honor the ARC qualifiers.
5017 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5019 LifeTime = Qualifiers::OCL_ExplicitNone;
5021 LifeTime = Qualifiers::OCL_None;
5026 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5027 if (!ObjCInstanceTypeDecl)
5028 ObjCInstanceTypeDecl =
5029 buildImplicitTypedef(getObjCIdType(), "instancetype");
5030 return ObjCInstanceTypeDecl;
5033 // This returns true if a type has been typedefed to BOOL:
5034 // typedef <type> BOOL;
5035 static bool isTypeTypedefedAsBOOL(QualType T) {
5036 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
5037 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5038 return II->isStr("BOOL");
5043 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
5045 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
5046 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5047 return CharUnits::Zero();
5049 CharUnits sz = getTypeSizeInChars(type);
5051 // Make all integer and enum types at least as large as an int
5052 if (sz.isPositive() && type->isIntegralOrEnumerationType())
5053 sz = std::max(sz, getTypeSizeInChars(IntTy));
5054 // Treat arrays as pointers, since that's how they're passed in.
5055 else if (type->isArrayType())
5056 sz = getTypeSizeInChars(VoidPtrTy);
5060 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
5061 return getTargetInfo().getCXXABI().isMicrosoft() &&
5062 VD->isStaticDataMember() &&
5063 VD->getType()->isIntegralOrEnumerationType() &&
5064 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
5068 std::string charUnitsToString(const CharUnits &CU) {
5069 return llvm::itostr(CU.getQuantity());
5072 /// getObjCEncodingForBlock - Return the encoded type for this block
5074 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5077 const BlockDecl *Decl = Expr->getBlockDecl();
5079 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5080 // Encode result type.
5081 if (getLangOpts().EncodeExtendedBlockSig)
5082 getObjCEncodingForMethodParameter(
5083 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5086 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
5087 // Compute size of all parameters.
5088 // Start with computing size of a pointer in number of bytes.
5089 // FIXME: There might(should) be a better way of doing this computation!
5091 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5092 CharUnits ParmOffset = PtrSize;
5093 for (auto PI : Decl->params()) {
5094 QualType PType = PI->getType();
5095 CharUnits sz = getObjCEncodingTypeSize(PType);
5098 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
5101 // Size of the argument frame
5102 S += charUnitsToString(ParmOffset);
5103 // Block pointer and offset.
5107 ParmOffset = PtrSize;
5108 for (auto PVDecl : Decl->params()) {
5109 QualType PType = PVDecl->getOriginalType();
5110 if (const ArrayType *AT =
5111 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5112 // Use array's original type only if it has known number of
5114 if (!isa<ConstantArrayType>(AT))
5115 PType = PVDecl->getType();
5116 } else if (PType->isFunctionType())
5117 PType = PVDecl->getType();
5118 if (getLangOpts().EncodeExtendedBlockSig)
5119 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5120 S, true /*Extended*/);
5122 getObjCEncodingForType(PType, S);
5123 S += charUnitsToString(ParmOffset);
5124 ParmOffset += getObjCEncodingTypeSize(PType);
5130 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
5132 // Encode result type.
5133 getObjCEncodingForType(Decl->getReturnType(), S);
5134 CharUnits ParmOffset;
5135 // Compute size of all parameters.
5136 for (auto PI : Decl->params()) {
5137 QualType PType = PI->getType();
5138 CharUnits sz = getObjCEncodingTypeSize(PType);
5142 assert (sz.isPositive() &&
5143 "getObjCEncodingForFunctionDecl - Incomplete param type");
5146 S += charUnitsToString(ParmOffset);
5147 ParmOffset = CharUnits::Zero();
5150 for (auto PVDecl : Decl->params()) {
5151 QualType PType = PVDecl->getOriginalType();
5152 if (const ArrayType *AT =
5153 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5154 // Use array's original type only if it has known number of
5156 if (!isa<ConstantArrayType>(AT))
5157 PType = PVDecl->getType();
5158 } else if (PType->isFunctionType())
5159 PType = PVDecl->getType();
5160 getObjCEncodingForType(PType, S);
5161 S += charUnitsToString(ParmOffset);
5162 ParmOffset += getObjCEncodingTypeSize(PType);
5168 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
5169 /// method parameter or return type. If Extended, include class names and
5170 /// block object types.
5171 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5172 QualType T, std::string& S,
5173 bool Extended) const {
5174 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5175 getObjCEncodingForTypeQualifier(QT, S);
5176 // Encode parameter type.
5177 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5178 true /*OutermostType*/,
5179 false /*EncodingProperty*/,
5180 false /*StructField*/,
5181 Extended /*EncodeBlockParameters*/,
5182 Extended /*EncodeClassNames*/);
5185 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
5187 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5189 bool Extended) const {
5190 // FIXME: This is not very efficient.
5191 // Encode return type.
5192 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5193 Decl->getReturnType(), S, Extended);
5194 // Compute size of all parameters.
5195 // Start with computing size of a pointer in number of bytes.
5196 // FIXME: There might(should) be a better way of doing this computation!
5198 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5199 // The first two arguments (self and _cmd) are pointers; account for
5201 CharUnits ParmOffset = 2 * PtrSize;
5202 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5203 E = Decl->sel_param_end(); PI != E; ++PI) {
5204 QualType PType = (*PI)->getType();
5205 CharUnits sz = getObjCEncodingTypeSize(PType);
5209 assert (sz.isPositive() &&
5210 "getObjCEncodingForMethodDecl - Incomplete param type");
5213 S += charUnitsToString(ParmOffset);
5215 S += charUnitsToString(PtrSize);
5218 ParmOffset = 2 * PtrSize;
5219 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5220 E = Decl->sel_param_end(); PI != E; ++PI) {
5221 const ParmVarDecl *PVDecl = *PI;
5222 QualType PType = PVDecl->getOriginalType();
5223 if (const ArrayType *AT =
5224 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5225 // Use array's original type only if it has known number of
5227 if (!isa<ConstantArrayType>(AT))
5228 PType = PVDecl->getType();
5229 } else if (PType->isFunctionType())
5230 PType = PVDecl->getType();
5231 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5232 PType, S, Extended);
5233 S += charUnitsToString(ParmOffset);
5234 ParmOffset += getObjCEncodingTypeSize(PType);
5240 ObjCPropertyImplDecl *
5241 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5242 const ObjCPropertyDecl *PD,
5243 const Decl *Container) const {
5246 if (const ObjCCategoryImplDecl *CID =
5247 dyn_cast<ObjCCategoryImplDecl>(Container)) {
5248 for (auto *PID : CID->property_impls())
5249 if (PID->getPropertyDecl() == PD)
5252 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5253 for (auto *PID : OID->property_impls())
5254 if (PID->getPropertyDecl() == PD)
5260 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
5261 /// property declaration. If non-NULL, Container must be either an
5262 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5263 /// NULL when getting encodings for protocol properties.
5264 /// Property attributes are stored as a comma-delimited C string. The simple
5265 /// attributes readonly and bycopy are encoded as single characters. The
5266 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
5267 /// encoded as single characters, followed by an identifier. Property types
5268 /// are also encoded as a parametrized attribute. The characters used to encode
5269 /// these attributes are defined by the following enumeration:
5271 /// enum PropertyAttributes {
5272 /// kPropertyReadOnly = 'R', // property is read-only.
5273 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5274 /// kPropertyByref = '&', // property is a reference to the value last assigned
5275 /// kPropertyDynamic = 'D', // property is dynamic
5276 /// kPropertyGetter = 'G', // followed by getter selector name
5277 /// kPropertySetter = 'S', // followed by setter selector name
5278 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
5279 /// kPropertyType = 'T' // followed by old-style type encoding.
5280 /// kPropertyWeak = 'W' // 'weak' property
5281 /// kPropertyStrong = 'P' // property GC'able
5282 /// kPropertyNonAtomic = 'N' // property non-atomic
5285 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5286 const Decl *Container,
5287 std::string& S) const {
5288 // Collect information from the property implementation decl(s).
5289 bool Dynamic = false;
5290 ObjCPropertyImplDecl *SynthesizePID = nullptr;
5292 if (ObjCPropertyImplDecl *PropertyImpDecl =
5293 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5294 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5297 SynthesizePID = PropertyImpDecl;
5300 // FIXME: This is not very efficient.
5303 // Encode result type.
5304 // GCC has some special rules regarding encoding of properties which
5305 // closely resembles encoding of ivars.
5306 getObjCEncodingForPropertyType(PD->getType(), S);
5308 if (PD->isReadOnly()) {
5310 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5312 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5314 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5317 switch (PD->getSetterKind()) {
5318 case ObjCPropertyDecl::Assign: break;
5319 case ObjCPropertyDecl::Copy: S += ",C"; break;
5320 case ObjCPropertyDecl::Retain: S += ",&"; break;
5321 case ObjCPropertyDecl::Weak: S += ",W"; break;
5325 // It really isn't clear at all what this means, since properties
5326 // are "dynamic by default".
5330 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5333 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5335 S += PD->getGetterName().getAsString();
5338 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5340 S += PD->getSetterName().getAsString();
5343 if (SynthesizePID) {
5344 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5346 S += OID->getNameAsString();
5349 // FIXME: OBJCGC: weak & strong
5352 /// getLegacyIntegralTypeEncoding -
5353 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5354 /// 'l' or 'L' , but not always. For typedefs, we need to use
5355 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5357 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5358 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5359 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5360 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5361 PointeeTy = UnsignedIntTy;
5363 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5369 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5370 const FieldDecl *Field,
5371 QualType *NotEncodedT) const {
5372 // We follow the behavior of gcc, expanding structures which are
5373 // directly pointed to, and expanding embedded structures. Note that
5374 // these rules are sufficient to prevent recursive encoding of the
5376 getObjCEncodingForTypeImpl(T, S, true, true, Field,
5377 true /* outermost type */, false, false,
5378 false, false, false, NotEncodedT);
5381 void ASTContext::getObjCEncodingForPropertyType(QualType T,
5382 std::string& S) const {
5383 // Encode result type.
5384 // GCC has some special rules regarding encoding of properties which
5385 // closely resembles encoding of ivars.
5386 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5387 true /* outermost type */,
5388 true /* encoding property */);
5391 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5392 BuiltinType::Kind kind) {
5394 case BuiltinType::Void: return 'v';
5395 case BuiltinType::Bool: return 'B';
5396 case BuiltinType::Char_U:
5397 case BuiltinType::UChar: return 'C';
5398 case BuiltinType::Char16:
5399 case BuiltinType::UShort: return 'S';
5400 case BuiltinType::Char32:
5401 case BuiltinType::UInt: return 'I';
5402 case BuiltinType::ULong:
5403 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5404 case BuiltinType::UInt128: return 'T';
5405 case BuiltinType::ULongLong: return 'Q';
5406 case BuiltinType::Char_S:
5407 case BuiltinType::SChar: return 'c';
5408 case BuiltinType::Short: return 's';
5409 case BuiltinType::WChar_S:
5410 case BuiltinType::WChar_U:
5411 case BuiltinType::Int: return 'i';
5412 case BuiltinType::Long:
5413 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5414 case BuiltinType::LongLong: return 'q';
5415 case BuiltinType::Int128: return 't';
5416 case BuiltinType::Float: return 'f';
5417 case BuiltinType::Double: return 'd';
5418 case BuiltinType::LongDouble: return 'D';
5419 case BuiltinType::NullPtr: return '*'; // like char*
5421 case BuiltinType::Half:
5422 // FIXME: potentially need @encodes for these!
5425 case BuiltinType::ObjCId:
5426 case BuiltinType::ObjCClass:
5427 case BuiltinType::ObjCSel:
5428 llvm_unreachable("@encoding ObjC primitive type");
5430 // OpenCL and placeholder types don't need @encodings.
5431 case BuiltinType::OCLImage1d:
5432 case BuiltinType::OCLImage1dArray:
5433 case BuiltinType::OCLImage1dBuffer:
5434 case BuiltinType::OCLImage2d:
5435 case BuiltinType::OCLImage2dArray:
5436 case BuiltinType::OCLImage2dDepth:
5437 case BuiltinType::OCLImage2dArrayDepth:
5438 case BuiltinType::OCLImage2dMSAA:
5439 case BuiltinType::OCLImage2dArrayMSAA:
5440 case BuiltinType::OCLImage2dMSAADepth:
5441 case BuiltinType::OCLImage2dArrayMSAADepth:
5442 case BuiltinType::OCLImage3d:
5443 case BuiltinType::OCLEvent:
5444 case BuiltinType::OCLClkEvent:
5445 case BuiltinType::OCLQueue:
5446 case BuiltinType::OCLNDRange:
5447 case BuiltinType::OCLReserveID:
5448 case BuiltinType::OCLSampler:
5449 case BuiltinType::Dependent:
5450 #define BUILTIN_TYPE(KIND, ID)
5451 #define PLACEHOLDER_TYPE(KIND, ID) \
5452 case BuiltinType::KIND:
5453 #include "clang/AST/BuiltinTypes.def"
5454 llvm_unreachable("invalid builtin type for @encode");
5456 llvm_unreachable("invalid BuiltinType::Kind value");
5459 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5460 EnumDecl *Enum = ET->getDecl();
5462 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5463 if (!Enum->isFixed())
5466 // The encoding of a fixed enum type matches its fixed underlying type.
5467 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5468 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5471 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5472 QualType T, const FieldDecl *FD) {
5473 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5475 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5476 // The GNU runtime requires more information; bitfields are encoded as b,
5477 // then the offset (in bits) of the first element, then the type of the
5478 // bitfield, then the size in bits. For example, in this structure:
5485 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5486 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5487 // information is not especially sensible, but we're stuck with it for
5488 // compatibility with GCC, although providing it breaks anything that
5489 // actually uses runtime introspection and wants to work on both runtimes...
5490 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5491 const RecordDecl *RD = FD->getParent();
5492 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5493 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5494 if (const EnumType *ET = T->getAs<EnumType>())
5495 S += ObjCEncodingForEnumType(Ctx, ET);
5497 const BuiltinType *BT = T->castAs<BuiltinType>();
5498 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5501 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5504 // FIXME: Use SmallString for accumulating string.
5505 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5506 bool ExpandPointedToStructures,
5507 bool ExpandStructures,
5508 const FieldDecl *FD,
5510 bool EncodingProperty,
5512 bool EncodeBlockParameters,
5513 bool EncodeClassNames,
5514 bool EncodePointerToObjCTypedef,
5515 QualType *NotEncodedT) const {
5516 CanQualType CT = getCanonicalType(T);
5517 switch (CT->getTypeClass()) {
5520 if (FD && FD->isBitField())
5521 return EncodeBitField(this, S, T, FD);
5522 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5523 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5525 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5528 case Type::Complex: {
5529 const ComplexType *CT = T->castAs<ComplexType>();
5531 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
5535 case Type::Atomic: {
5536 const AtomicType *AT = T->castAs<AtomicType>();
5538 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
5542 // encoding for pointer or reference types.
5544 case Type::LValueReference:
5545 case Type::RValueReference: {
5547 if (isa<PointerType>(CT)) {
5548 const PointerType *PT = T->castAs<PointerType>();
5549 if (PT->isObjCSelType()) {
5553 PointeeTy = PT->getPointeeType();
5555 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5558 bool isReadOnly = false;
5559 // For historical/compatibility reasons, the read-only qualifier of the
5560 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5561 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5562 // Also, do not emit the 'r' for anything but the outermost type!
5563 if (isa<TypedefType>(T.getTypePtr())) {
5564 if (OutermostType && T.isConstQualified()) {
5568 } else if (OutermostType) {
5569 QualType P = PointeeTy;
5570 while (P->getAs<PointerType>())
5571 P = P->getAs<PointerType>()->getPointeeType();
5572 if (P.isConstQualified()) {
5578 // Another legacy compatibility encoding. Some ObjC qualifier and type
5579 // combinations need to be rearranged.
5580 // Rewrite "in const" from "nr" to "rn"
5581 if (StringRef(S).endswith("nr"))
5582 S.replace(S.end()-2, S.end(), "rn");
5585 if (PointeeTy->isCharType()) {
5586 // char pointer types should be encoded as '*' unless it is a
5587 // type that has been typedef'd to 'BOOL'.
5588 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5592 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5593 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5594 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5598 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5599 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5606 getLegacyIntegralTypeEncoding(PointeeTy);
5608 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5609 nullptr, false, false, false, false, false, false,
5614 case Type::ConstantArray:
5615 case Type::IncompleteArray:
5616 case Type::VariableArray: {
5617 const ArrayType *AT = cast<ArrayType>(CT);
5619 if (isa<IncompleteArrayType>(AT) && !StructField) {
5620 // Incomplete arrays are encoded as a pointer to the array element.
5623 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5624 false, ExpandStructures, FD);
5628 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5629 S += llvm::utostr(CAT->getSize().getZExtValue());
5631 //Variable length arrays are encoded as a regular array with 0 elements.
5632 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5633 "Unknown array type!");
5637 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5638 false, ExpandStructures, FD,
5639 false, false, false, false, false, false,
5646 case Type::FunctionNoProto:
5647 case Type::FunctionProto:
5651 case Type::Record: {
5652 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5653 S += RDecl->isUnion() ? '(' : '{';
5654 // Anonymous structures print as '?'
5655 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5657 if (ClassTemplateSpecializationDecl *Spec
5658 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5659 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5660 llvm::raw_string_ostream OS(S);
5661 TemplateSpecializationType::PrintTemplateArgumentList(OS,
5662 TemplateArgs.data(),
5663 TemplateArgs.size(),
5664 (*this).getPrintingPolicy());
5669 if (ExpandStructures) {
5671 if (!RDecl->isUnion()) {
5672 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
5674 for (const auto *Field : RDecl->fields()) {
5677 S += Field->getNameAsString();
5681 // Special case bit-fields.
5682 if (Field->isBitField()) {
5683 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5686 QualType qt = Field->getType();
5687 getLegacyIntegralTypeEncoding(qt);
5688 getObjCEncodingForTypeImpl(qt, S, false, true,
5689 FD, /*OutermostType*/false,
5690 /*EncodingProperty*/false,
5691 /*StructField*/true,
5692 false, false, false, NotEncodedT);
5697 S += RDecl->isUnion() ? ')' : '}';
5701 case Type::BlockPointer: {
5702 const BlockPointerType *BT = T->castAs<BlockPointerType>();
5703 S += "@?"; // Unlike a pointer-to-function, which is "^?".
5704 if (EncodeBlockParameters) {
5705 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5708 // Block return type
5709 getObjCEncodingForTypeImpl(
5710 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5711 FD, false /* OutermostType */, EncodingProperty,
5712 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5717 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5718 for (const auto &I : FPT->param_types())
5719 getObjCEncodingForTypeImpl(
5720 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5721 false /* OutermostType */, EncodingProperty,
5722 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5723 false, NotEncodedT);
5730 case Type::ObjCObject: {
5731 // hack to match legacy encoding of *id and *Class
5732 QualType Ty = getObjCObjectPointerType(CT);
5733 if (Ty->isObjCIdType()) {
5734 S += "{objc_object=}";
5737 else if (Ty->isObjCClassType()) {
5738 S += "{objc_class=}";
5743 case Type::ObjCInterface: {
5744 // Ignore protocol qualifiers when mangling at this level.
5745 // @encode(class_name)
5746 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
5748 S += OI->getObjCRuntimeNameAsString();
5750 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5751 DeepCollectObjCIvars(OI, true, Ivars);
5752 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5753 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5754 if (Field->isBitField())
5755 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5757 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5758 false, false, false, false, false,
5759 EncodePointerToObjCTypedef,
5766 case Type::ObjCObjectPointer: {
5767 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5768 if (OPT->isObjCIdType()) {
5773 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5774 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5775 // Since this is a binary compatibility issue, need to consult with runtime
5776 // folks. Fortunately, this is a *very* obsure construct.
5781 if (OPT->isObjCQualifiedIdType()) {
5782 getObjCEncodingForTypeImpl(getObjCIdType(), S,
5783 ExpandPointedToStructures,
5784 ExpandStructures, FD);
5785 if (FD || EncodingProperty || EncodeClassNames) {
5786 // Note that we do extended encoding of protocol qualifer list
5787 // Only when doing ivar or property encoding.
5789 for (const auto *I : OPT->quals()) {
5791 S += I->getObjCRuntimeNameAsString();
5799 QualType PointeeTy = OPT->getPointeeType();
5800 if (!EncodingProperty &&
5801 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5802 !EncodePointerToObjCTypedef) {
5803 // Another historical/compatibility reason.
5804 // We encode the underlying type which comes out as
5807 if (FD && OPT->getInterfaceDecl()) {
5808 // Prevent recursive encoding of fields in some rare cases.
5809 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5810 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5811 DeepCollectObjCIvars(OI, true, Ivars);
5812 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5813 if (cast<FieldDecl>(Ivars[i]) == FD) {
5815 S += OI->getObjCRuntimeNameAsString();
5821 getObjCEncodingForTypeImpl(PointeeTy, S,
5822 false, ExpandPointedToStructures,
5824 false, false, false, false, false,
5825 /*EncodePointerToObjCTypedef*/true);
5830 if (OPT->getInterfaceDecl() &&
5831 (FD || EncodingProperty || EncodeClassNames)) {
5833 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
5834 for (const auto *I : OPT->quals()) {
5836 S += I->getObjCRuntimeNameAsString();
5844 // gcc just blithely ignores member pointers.
5845 // FIXME: we shoul do better than that. 'M' is available.
5846 case Type::MemberPointer:
5847 // This matches gcc's encoding, even though technically it is insufficient.
5848 //FIXME. We should do a better job than gcc.
5850 case Type::ExtVector:
5851 // Until we have a coherent encoding of these three types, issue warning.
5857 // We could see an undeduced auto type here during error recovery.
5862 #define ABSTRACT_TYPE(KIND, BASE)
5863 #define TYPE(KIND, BASE)
5864 #define DEPENDENT_TYPE(KIND, BASE) \
5866 #define NON_CANONICAL_TYPE(KIND, BASE) \
5868 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5870 #include "clang/AST/TypeNodes.def"
5871 llvm_unreachable("@encode for dependent type!");
5873 llvm_unreachable("bad type kind!");
5876 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5878 const FieldDecl *FD,
5880 QualType *NotEncodedT) const {
5881 assert(RDecl && "Expected non-null RecordDecl");
5882 assert(!RDecl->isUnion() && "Should not be called for unions");
5883 if (!RDecl->getDefinition())
5886 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5887 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5888 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5891 for (const auto &BI : CXXRec->bases()) {
5892 if (!BI.isVirtual()) {
5893 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5894 if (base->isEmpty())
5896 uint64_t offs = toBits(layout.getBaseClassOffset(base));
5897 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5898 std::make_pair(offs, base));
5904 for (auto *Field : RDecl->fields()) {
5905 uint64_t offs = layout.getFieldOffset(i);
5906 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5907 std::make_pair(offs, Field));
5911 if (CXXRec && includeVBases) {
5912 for (const auto &BI : CXXRec->vbases()) {
5913 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5914 if (base->isEmpty())
5916 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
5917 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5918 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5919 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5920 std::make_pair(offs, base));
5926 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5928 size = layout.getSize();
5932 uint64_t CurOffs = 0;
5934 std::multimap<uint64_t, NamedDecl *>::iterator
5935 CurLayObj = FieldOrBaseOffsets.begin();
5937 if (CXXRec && CXXRec->isDynamicClass() &&
5938 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
5941 std::string recname = CXXRec->getNameAsString();
5942 if (recname.empty()) recname = "?";
5948 CurOffs += getTypeSize(VoidPtrTy);
5952 if (!RDecl->hasFlexibleArrayMember()) {
5953 // Mark the end of the structure.
5954 uint64_t offs = toBits(size);
5955 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5956 std::make_pair(offs, nullptr));
5959 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5961 assert(CurOffs <= CurLayObj->first);
5962 if (CurOffs < CurLayObj->first) {
5963 uint64_t padding = CurLayObj->first - CurOffs;
5964 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5965 // packing/alignment of members is different that normal, in which case
5966 // the encoding will be out-of-sync with the real layout.
5967 // If the runtime switches to just consider the size of types without
5968 // taking into account alignment, we could make padding explicit in the
5969 // encoding (e.g. using arrays of chars). The encoding strings would be
5970 // longer then though.
5975 NamedDecl *dcl = CurLayObj->second;
5977 break; // reached end of structure.
5979 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5980 // We expand the bases without their virtual bases since those are going
5981 // in the initial structure. Note that this differs from gcc which
5982 // expands virtual bases each time one is encountered in the hierarchy,
5983 // making the encoding type bigger than it really is.
5984 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5986 assert(!base->isEmpty());
5988 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
5991 FieldDecl *field = cast<FieldDecl>(dcl);
5994 S += field->getNameAsString();
5998 if (field->isBitField()) {
5999 EncodeBitField(this, S, field->getType(), field);
6001 CurOffs += field->getBitWidthValue(*this);
6004 QualType qt = field->getType();
6005 getLegacyIntegralTypeEncoding(qt);
6006 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6007 /*OutermostType*/false,
6008 /*EncodingProperty*/false,
6009 /*StructField*/true,
6010 false, false, false, NotEncodedT);
6012 CurOffs += getTypeSize(field->getType());
6019 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
6020 std::string& S) const {
6021 if (QT & Decl::OBJC_TQ_In)
6023 if (QT & Decl::OBJC_TQ_Inout)
6025 if (QT & Decl::OBJC_TQ_Out)
6027 if (QT & Decl::OBJC_TQ_Bycopy)
6029 if (QT & Decl::OBJC_TQ_Byref)
6031 if (QT & Decl::OBJC_TQ_Oneway)
6035 TypedefDecl *ASTContext::getObjCIdDecl() const {
6037 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
6038 T = getObjCObjectPointerType(T);
6039 ObjCIdDecl = buildImplicitTypedef(T, "id");
6044 TypedefDecl *ASTContext::getObjCSelDecl() const {
6046 QualType T = getPointerType(ObjCBuiltinSelTy);
6047 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
6052 TypedefDecl *ASTContext::getObjCClassDecl() const {
6053 if (!ObjCClassDecl) {
6054 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
6055 T = getObjCObjectPointerType(T);
6056 ObjCClassDecl = buildImplicitTypedef(T, "Class");
6058 return ObjCClassDecl;
6061 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6062 if (!ObjCProtocolClassDecl) {
6063 ObjCProtocolClassDecl
6064 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6066 &Idents.get("Protocol"),
6067 /*typeParamList=*/nullptr,
6068 /*PrevDecl=*/nullptr,
6069 SourceLocation(), true);
6072 return ObjCProtocolClassDecl;
6075 //===----------------------------------------------------------------------===//
6076 // __builtin_va_list Construction Functions
6077 //===----------------------------------------------------------------------===//
6079 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6081 // typedef char* __builtin[_ms]_va_list;
6082 QualType T = Context->getPointerType(Context->CharTy);
6083 return Context->buildImplicitTypedef(T, Name);
6086 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6087 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6090 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6091 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
6094 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6095 // typedef void* __builtin_va_list;
6096 QualType T = Context->getPointerType(Context->VoidTy);
6097 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6100 static TypedefDecl *
6101 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
6103 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
6104 if (Context->getLangOpts().CPlusPlus) {
6105 // namespace std { struct __va_list {
6107 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6108 Context->getTranslationUnitDecl(),
6109 /*Inline*/ false, SourceLocation(),
6110 SourceLocation(), &Context->Idents.get("std"),
6111 /*PrevDecl*/ nullptr);
6113 VaListTagDecl->setDeclContext(NS);
6116 VaListTagDecl->startDefinition();
6118 const size_t NumFields = 5;
6119 QualType FieldTypes[NumFields];
6120 const char *FieldNames[NumFields];
6123 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6124 FieldNames[0] = "__stack";
6127 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6128 FieldNames[1] = "__gr_top";
6131 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6132 FieldNames[2] = "__vr_top";
6135 FieldTypes[3] = Context->IntTy;
6136 FieldNames[3] = "__gr_offs";
6139 FieldTypes[4] = Context->IntTy;
6140 FieldNames[4] = "__vr_offs";
6143 for (unsigned i = 0; i < NumFields; ++i) {
6144 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6148 &Context->Idents.get(FieldNames[i]),
6149 FieldTypes[i], /*TInfo=*/nullptr,
6150 /*BitWidth=*/nullptr,
6153 Field->setAccess(AS_public);
6154 VaListTagDecl->addDecl(Field);
6156 VaListTagDecl->completeDefinition();
6157 Context->VaListTagDecl = VaListTagDecl;
6158 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6160 // } __builtin_va_list;
6161 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
6164 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6165 // typedef struct __va_list_tag {
6166 RecordDecl *VaListTagDecl;
6168 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6169 VaListTagDecl->startDefinition();
6171 const size_t NumFields = 5;
6172 QualType FieldTypes[NumFields];
6173 const char *FieldNames[NumFields];
6175 // unsigned char gpr;
6176 FieldTypes[0] = Context->UnsignedCharTy;
6177 FieldNames[0] = "gpr";
6179 // unsigned char fpr;
6180 FieldTypes[1] = Context->UnsignedCharTy;
6181 FieldNames[1] = "fpr";
6183 // unsigned short reserved;
6184 FieldTypes[2] = Context->UnsignedShortTy;
6185 FieldNames[2] = "reserved";
6187 // void* overflow_arg_area;
6188 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6189 FieldNames[3] = "overflow_arg_area";
6191 // void* reg_save_area;
6192 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6193 FieldNames[4] = "reg_save_area";
6196 for (unsigned i = 0; i < NumFields; ++i) {
6197 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6200 &Context->Idents.get(FieldNames[i]),
6201 FieldTypes[i], /*TInfo=*/nullptr,
6202 /*BitWidth=*/nullptr,
6205 Field->setAccess(AS_public);
6206 VaListTagDecl->addDecl(Field);
6208 VaListTagDecl->completeDefinition();
6209 Context->VaListTagDecl = VaListTagDecl;
6210 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6213 TypedefDecl *VaListTagTypedefDecl =
6214 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6216 QualType VaListTagTypedefType =
6217 Context->getTypedefType(VaListTagTypedefDecl);
6219 // typedef __va_list_tag __builtin_va_list[1];
6220 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6221 QualType VaListTagArrayType
6222 = Context->getConstantArrayType(VaListTagTypedefType,
6223 Size, ArrayType::Normal, 0);
6224 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6227 static TypedefDecl *
6228 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6229 // struct __va_list_tag {
6230 RecordDecl *VaListTagDecl;
6231 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6232 VaListTagDecl->startDefinition();
6234 const size_t NumFields = 4;
6235 QualType FieldTypes[NumFields];
6236 const char *FieldNames[NumFields];
6238 // unsigned gp_offset;
6239 FieldTypes[0] = Context->UnsignedIntTy;
6240 FieldNames[0] = "gp_offset";
6242 // unsigned fp_offset;
6243 FieldTypes[1] = Context->UnsignedIntTy;
6244 FieldNames[1] = "fp_offset";
6246 // void* overflow_arg_area;
6247 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6248 FieldNames[2] = "overflow_arg_area";
6250 // void* reg_save_area;
6251 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6252 FieldNames[3] = "reg_save_area";
6255 for (unsigned i = 0; i < NumFields; ++i) {
6256 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6260 &Context->Idents.get(FieldNames[i]),
6261 FieldTypes[i], /*TInfo=*/nullptr,
6262 /*BitWidth=*/nullptr,
6265 Field->setAccess(AS_public);
6266 VaListTagDecl->addDecl(Field);
6268 VaListTagDecl->completeDefinition();
6269 Context->VaListTagDecl = VaListTagDecl;
6270 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6274 // typedef struct __va_list_tag __builtin_va_list[1];
6275 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6276 QualType VaListTagArrayType =
6277 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6278 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6281 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6282 // typedef int __builtin_va_list[4];
6283 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6284 QualType IntArrayType
6285 = Context->getConstantArrayType(Context->IntTy,
6286 Size, ArrayType::Normal, 0);
6287 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6290 static TypedefDecl *
6291 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6293 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6294 if (Context->getLangOpts().CPlusPlus) {
6295 // namespace std { struct __va_list {
6297 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6298 Context->getTranslationUnitDecl(),
6299 /*Inline*/false, SourceLocation(),
6300 SourceLocation(), &Context->Idents.get("std"),
6301 /*PrevDecl*/ nullptr);
6303 VaListDecl->setDeclContext(NS);
6306 VaListDecl->startDefinition();
6309 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6313 &Context->Idents.get("__ap"),
6314 Context->getPointerType(Context->VoidTy),
6316 /*BitWidth=*/nullptr,
6319 Field->setAccess(AS_public);
6320 VaListDecl->addDecl(Field);
6323 VaListDecl->completeDefinition();
6325 // typedef struct __va_list __builtin_va_list;
6326 QualType T = Context->getRecordType(VaListDecl);
6327 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6330 static TypedefDecl *
6331 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6332 // struct __va_list_tag {
6333 RecordDecl *VaListTagDecl;
6334 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6335 VaListTagDecl->startDefinition();
6337 const size_t NumFields = 4;
6338 QualType FieldTypes[NumFields];
6339 const char *FieldNames[NumFields];
6342 FieldTypes[0] = Context->LongTy;
6343 FieldNames[0] = "__gpr";
6346 FieldTypes[1] = Context->LongTy;
6347 FieldNames[1] = "__fpr";
6349 // void *__overflow_arg_area;
6350 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6351 FieldNames[2] = "__overflow_arg_area";
6353 // void *__reg_save_area;
6354 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6355 FieldNames[3] = "__reg_save_area";
6358 for (unsigned i = 0; i < NumFields; ++i) {
6359 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6363 &Context->Idents.get(FieldNames[i]),
6364 FieldTypes[i], /*TInfo=*/nullptr,
6365 /*BitWidth=*/nullptr,
6368 Field->setAccess(AS_public);
6369 VaListTagDecl->addDecl(Field);
6371 VaListTagDecl->completeDefinition();
6372 Context->VaListTagDecl = VaListTagDecl;
6373 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6377 // typedef __va_list_tag __builtin_va_list[1];
6378 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6379 QualType VaListTagArrayType =
6380 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6382 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6385 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6386 TargetInfo::BuiltinVaListKind Kind) {
6388 case TargetInfo::CharPtrBuiltinVaList:
6389 return CreateCharPtrBuiltinVaListDecl(Context);
6390 case TargetInfo::VoidPtrBuiltinVaList:
6391 return CreateVoidPtrBuiltinVaListDecl(Context);
6392 case TargetInfo::AArch64ABIBuiltinVaList:
6393 return CreateAArch64ABIBuiltinVaListDecl(Context);
6394 case TargetInfo::PowerABIBuiltinVaList:
6395 return CreatePowerABIBuiltinVaListDecl(Context);
6396 case TargetInfo::X86_64ABIBuiltinVaList:
6397 return CreateX86_64ABIBuiltinVaListDecl(Context);
6398 case TargetInfo::PNaClABIBuiltinVaList:
6399 return CreatePNaClABIBuiltinVaListDecl(Context);
6400 case TargetInfo::AAPCSABIBuiltinVaList:
6401 return CreateAAPCSABIBuiltinVaListDecl(Context);
6402 case TargetInfo::SystemZBuiltinVaList:
6403 return CreateSystemZBuiltinVaListDecl(Context);
6406 llvm_unreachable("Unhandled __builtin_va_list type kind");
6409 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6410 if (!BuiltinVaListDecl) {
6411 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6412 assert(BuiltinVaListDecl->isImplicit());
6415 return BuiltinVaListDecl;
6418 Decl *ASTContext::getVaListTagDecl() const {
6419 // Force the creation of VaListTagDecl by building the __builtin_va_list
6422 (void)getBuiltinVaListDecl();
6424 return VaListTagDecl;
6427 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6428 if (!BuiltinMSVaListDecl)
6429 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6431 return BuiltinMSVaListDecl;
6434 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6435 assert(ObjCConstantStringType.isNull() &&
6436 "'NSConstantString' type already set!");
6438 ObjCConstantStringType = getObjCInterfaceType(Decl);
6441 /// \brief Retrieve the template name that corresponds to a non-empty
6444 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6445 UnresolvedSetIterator End) const {
6446 unsigned size = End - Begin;
6447 assert(size > 1 && "set is not overloaded!");
6449 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6450 size * sizeof(FunctionTemplateDecl*));
6451 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6453 NamedDecl **Storage = OT->getStorage();
6454 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6456 assert(isa<FunctionTemplateDecl>(D) ||
6457 (isa<UsingShadowDecl>(D) &&
6458 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6462 return TemplateName(OT);
6465 /// \brief Retrieve the template name that represents a qualified
6466 /// template name such as \c std::vector.
6468 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6469 bool TemplateKeyword,
6470 TemplateDecl *Template) const {
6471 assert(NNS && "Missing nested-name-specifier in qualified template name");
6473 // FIXME: Canonicalization?
6474 llvm::FoldingSetNodeID ID;
6475 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6477 void *InsertPos = nullptr;
6478 QualifiedTemplateName *QTN =
6479 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6481 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6482 QualifiedTemplateName(NNS, TemplateKeyword, Template);
6483 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6486 return TemplateName(QTN);
6489 /// \brief Retrieve the template name that represents a dependent
6490 /// template name such as \c MetaFun::template apply.
6492 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6493 const IdentifierInfo *Name) const {
6494 assert((!NNS || NNS->isDependent()) &&
6495 "Nested name specifier must be dependent");
6497 llvm::FoldingSetNodeID ID;
6498 DependentTemplateName::Profile(ID, NNS, Name);
6500 void *InsertPos = nullptr;
6501 DependentTemplateName *QTN =
6502 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6505 return TemplateName(QTN);
6507 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6508 if (CanonNNS == NNS) {
6509 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6510 DependentTemplateName(NNS, Name);
6512 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6513 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6514 DependentTemplateName(NNS, Name, Canon);
6515 DependentTemplateName *CheckQTN =
6516 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6517 assert(!CheckQTN && "Dependent type name canonicalization broken");
6521 DependentTemplateNames.InsertNode(QTN, InsertPos);
6522 return TemplateName(QTN);
6525 /// \brief Retrieve the template name that represents a dependent
6526 /// template name such as \c MetaFun::template operator+.
6528 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6529 OverloadedOperatorKind Operator) const {
6530 assert((!NNS || NNS->isDependent()) &&
6531 "Nested name specifier must be dependent");
6533 llvm::FoldingSetNodeID ID;
6534 DependentTemplateName::Profile(ID, NNS, Operator);
6536 void *InsertPos = nullptr;
6537 DependentTemplateName *QTN
6538 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6541 return TemplateName(QTN);
6543 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6544 if (CanonNNS == NNS) {
6545 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6546 DependentTemplateName(NNS, Operator);
6548 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6549 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6550 DependentTemplateName(NNS, Operator, Canon);
6552 DependentTemplateName *CheckQTN
6553 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6554 assert(!CheckQTN && "Dependent template name canonicalization broken");
6558 DependentTemplateNames.InsertNode(QTN, InsertPos);
6559 return TemplateName(QTN);
6563 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6564 TemplateName replacement) const {
6565 llvm::FoldingSetNodeID ID;
6566 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6568 void *insertPos = nullptr;
6569 SubstTemplateTemplateParmStorage *subst
6570 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6573 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6574 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6577 return TemplateName(subst);
6581 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6582 const TemplateArgument &ArgPack) const {
6583 ASTContext &Self = const_cast<ASTContext &>(*this);
6584 llvm::FoldingSetNodeID ID;
6585 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6587 void *InsertPos = nullptr;
6588 SubstTemplateTemplateParmPackStorage *Subst
6589 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6592 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6593 ArgPack.pack_size(),
6594 ArgPack.pack_begin());
6595 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6598 return TemplateName(Subst);
6601 /// getFromTargetType - Given one of the integer types provided by
6602 /// TargetInfo, produce the corresponding type. The unsigned @p Type
6603 /// is actually a value of type @c TargetInfo::IntType.
6604 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6606 case TargetInfo::NoInt: return CanQualType();
6607 case TargetInfo::SignedChar: return SignedCharTy;
6608 case TargetInfo::UnsignedChar: return UnsignedCharTy;
6609 case TargetInfo::SignedShort: return ShortTy;
6610 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6611 case TargetInfo::SignedInt: return IntTy;
6612 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6613 case TargetInfo::SignedLong: return LongTy;
6614 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6615 case TargetInfo::SignedLongLong: return LongLongTy;
6616 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6619 llvm_unreachable("Unhandled TargetInfo::IntType value");
6622 //===----------------------------------------------------------------------===//
6624 //===----------------------------------------------------------------------===//
6626 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6627 /// garbage collection attribute.
6629 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6630 if (getLangOpts().getGC() == LangOptions::NonGC)
6631 return Qualifiers::GCNone;
6633 assert(getLangOpts().ObjC1);
6634 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6636 // Default behaviour under objective-C's gc is for ObjC pointers
6637 // (or pointers to them) be treated as though they were declared
6639 if (GCAttrs == Qualifiers::GCNone) {
6640 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6641 return Qualifiers::Strong;
6642 else if (Ty->isPointerType())
6643 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6645 // It's not valid to set GC attributes on anything that isn't a
6648 QualType CT = Ty->getCanonicalTypeInternal();
6649 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6650 CT = AT->getElementType();
6651 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6657 //===----------------------------------------------------------------------===//
6658 // Type Compatibility Testing
6659 //===----------------------------------------------------------------------===//
6661 /// areCompatVectorTypes - Return true if the two specified vector types are
6663 static bool areCompatVectorTypes(const VectorType *LHS,
6664 const VectorType *RHS) {
6665 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6666 return LHS->getElementType() == RHS->getElementType() &&
6667 LHS->getNumElements() == RHS->getNumElements();
6670 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6671 QualType SecondVec) {
6672 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6673 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6675 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6678 // Treat Neon vector types and most AltiVec vector types as if they are the
6679 // equivalent GCC vector types.
6680 const VectorType *First = FirstVec->getAs<VectorType>();
6681 const VectorType *Second = SecondVec->getAs<VectorType>();
6682 if (First->getNumElements() == Second->getNumElements() &&
6683 hasSameType(First->getElementType(), Second->getElementType()) &&
6684 First->getVectorKind() != VectorType::AltiVecPixel &&
6685 First->getVectorKind() != VectorType::AltiVecBool &&
6686 Second->getVectorKind() != VectorType::AltiVecPixel &&
6687 Second->getVectorKind() != VectorType::AltiVecBool)
6693 //===----------------------------------------------------------------------===//
6694 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6695 //===----------------------------------------------------------------------===//
6697 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6698 /// inheritance hierarchy of 'rProto'.
6700 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6701 ObjCProtocolDecl *rProto) const {
6702 if (declaresSameEntity(lProto, rProto))
6704 for (auto *PI : rProto->protocols())
6705 if (ProtocolCompatibleWithProtocol(lProto, PI))
6710 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6711 /// Class<pr1, ...>.
6712 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6714 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6715 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6716 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6718 for (auto *lhsProto : lhsQID->quals()) {
6720 for (auto *rhsProto : rhsOPT->quals()) {
6721 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6732 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6733 /// ObjCQualifiedIDType.
6734 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6736 // Allow id<P..> and an 'id' or void* type in all cases.
6737 if (lhs->isVoidPointerType() ||
6738 lhs->isObjCIdType() || lhs->isObjCClassType())
6740 else if (rhs->isVoidPointerType() ||
6741 rhs->isObjCIdType() || rhs->isObjCClassType())
6744 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6745 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6747 if (!rhsOPT) return false;
6749 if (rhsOPT->qual_empty()) {
6750 // If the RHS is a unqualified interface pointer "NSString*",
6751 // make sure we check the class hierarchy.
6752 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6753 for (auto *I : lhsQID->quals()) {
6754 // when comparing an id<P> on lhs with a static type on rhs,
6755 // see if static class implements all of id's protocols, directly or
6756 // through its super class and categories.
6757 if (!rhsID->ClassImplementsProtocol(I, true))
6761 // If there are no qualifiers and no interface, we have an 'id'.
6764 // Both the right and left sides have qualifiers.
6765 for (auto *lhsProto : lhsQID->quals()) {
6768 // when comparing an id<P> on lhs with a static type on rhs,
6769 // see if static class implements all of id's protocols, directly or
6770 // through its super class and categories.
6771 for (auto *rhsProto : rhsOPT->quals()) {
6772 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6773 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6778 // If the RHS is a qualified interface pointer "NSString<P>*",
6779 // make sure we check the class hierarchy.
6780 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6781 for (auto *I : lhsQID->quals()) {
6782 // when comparing an id<P> on lhs with a static type on rhs,
6783 // see if static class implements all of id's protocols, directly or
6784 // through its super class and categories.
6785 if (rhsID->ClassImplementsProtocol(I, true)) {
6798 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6799 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6801 if (const ObjCObjectPointerType *lhsOPT =
6802 lhs->getAsObjCInterfacePointerType()) {
6803 // If both the right and left sides have qualifiers.
6804 for (auto *lhsProto : lhsOPT->quals()) {
6807 // when comparing an id<P> on rhs with a static type on lhs,
6808 // see if static class implements all of id's protocols, directly or
6809 // through its super class and categories.
6810 // First, lhs protocols in the qualifier list must be found, direct
6811 // or indirect in rhs's qualifier list or it is a mismatch.
6812 for (auto *rhsProto : rhsQID->quals()) {
6813 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6814 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6823 // Static class's protocols, or its super class or category protocols
6824 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6825 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6826 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6827 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6828 // This is rather dubious but matches gcc's behavior. If lhs has
6829 // no type qualifier and its class has no static protocol(s)
6830 // assume that it is mismatch.
6831 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6833 for (auto *lhsProto : LHSInheritedProtocols) {
6835 for (auto *rhsProto : rhsQID->quals()) {
6836 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6837 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6851 /// canAssignObjCInterfaces - Return true if the two interface types are
6852 /// compatible for assignment from RHS to LHS. This handles validation of any
6853 /// protocol qualifiers on the LHS or RHS.
6855 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6856 const ObjCObjectPointerType *RHSOPT) {
6857 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6858 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6860 // If either type represents the built-in 'id' or 'Class' types, return true.
6861 if (LHS->isObjCUnqualifiedIdOrClass() ||
6862 RHS->isObjCUnqualifiedIdOrClass())
6865 // Function object that propagates a successful result or handles
6867 auto finish = [&](bool succeeded) -> bool {
6871 if (!RHS->isKindOfType())
6874 // Strip off __kindof and protocol qualifiers, then check whether
6875 // we can assign the other way.
6876 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6877 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6880 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6881 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6886 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6887 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6888 QualType(RHSOPT,0)));
6891 // If we have 2 user-defined types, fall into that path.
6892 if (LHS->getInterface() && RHS->getInterface()) {
6893 return finish(canAssignObjCInterfaces(LHS, RHS));
6899 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6900 /// for providing type-safety for objective-c pointers used to pass/return
6901 /// arguments in block literals. When passed as arguments, passing 'A*' where
6902 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6903 /// not OK. For the return type, the opposite is not OK.
6904 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6905 const ObjCObjectPointerType *LHSOPT,
6906 const ObjCObjectPointerType *RHSOPT,
6907 bool BlockReturnType) {
6909 // Function object that propagates a successful result or handles
6911 auto finish = [&](bool succeeded) -> bool {
6915 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6916 if (!Expected->isKindOfType())
6919 // Strip off __kindof and protocol qualifiers, then check whether
6920 // we can assign the other way.
6921 return canAssignObjCInterfacesInBlockPointer(
6922 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6923 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6927 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
6930 if (LHSOPT->isObjCBuiltinType()) {
6931 return finish(RHSOPT->isObjCBuiltinType() ||
6932 RHSOPT->isObjCQualifiedIdType());
6935 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
6936 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6940 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6941 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6942 if (LHS && RHS) { // We have 2 user-defined types.
6944 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
6945 return finish(BlockReturnType);
6946 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
6947 return finish(!BlockReturnType);
6955 /// Comparison routine for Objective-C protocols to be used with
6956 /// llvm::array_pod_sort.
6957 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6958 ObjCProtocolDecl * const *rhs) {
6959 return (*lhs)->getName().compare((*rhs)->getName());
6963 /// getIntersectionOfProtocols - This routine finds the intersection of set
6964 /// of protocols inherited from two distinct objective-c pointer objects with
6965 /// the given common base.
6966 /// It is used to build composite qualifier list of the composite type of
6967 /// the conditional expression involving two objective-c pointer objects.
6969 void getIntersectionOfProtocols(ASTContext &Context,
6970 const ObjCInterfaceDecl *CommonBase,
6971 const ObjCObjectPointerType *LHSOPT,
6972 const ObjCObjectPointerType *RHSOPT,
6973 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
6975 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6976 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6977 assert(LHS->getInterface() && "LHS must have an interface base");
6978 assert(RHS->getInterface() && "RHS must have an interface base");
6980 // Add all of the protocols for the LHS.
6981 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6983 // Start with the protocol qualifiers.
6984 for (auto proto : LHS->quals()) {
6985 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
6988 // Also add the protocols associated with the LHS interface.
6989 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6991 // Add all of the protocls for the RHS.
6992 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6994 // Start with the protocol qualifiers.
6995 for (auto proto : RHS->quals()) {
6996 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
6999 // Also add the protocols associated with the RHS interface.
7000 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7002 // Compute the intersection of the collected protocol sets.
7003 for (auto proto : LHSProtocolSet) {
7004 if (RHSProtocolSet.count(proto))
7005 IntersectionSet.push_back(proto);
7008 // Compute the set of protocols that is implied by either the common type or
7009 // the protocols within the intersection.
7010 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7011 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7013 // Remove any implied protocols from the list of inherited protocols.
7014 if (!ImpliedProtocols.empty()) {
7015 IntersectionSet.erase(
7016 std::remove_if(IntersectionSet.begin(),
7017 IntersectionSet.end(),
7018 [&](ObjCProtocolDecl *proto) -> bool {
7019 return ImpliedProtocols.count(proto) > 0;
7021 IntersectionSet.end());
7024 // Sort the remaining protocols by name.
7025 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7026 compareObjCProtocolsByName);
7029 /// Determine whether the first type is a subtype of the second.
7030 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7032 // Common case: two object pointers.
7033 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7034 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7035 if (lhsOPT && rhsOPT)
7036 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7038 // Two block pointers.
7039 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7040 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7041 if (lhsBlock && rhsBlock)
7042 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7044 // If either is an unqualified 'id' and the other is a block, it's
7046 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7047 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7053 // Check that the given Objective-C type argument lists are equivalent.
7054 static bool sameObjCTypeArgs(ASTContext &ctx,
7055 const ObjCInterfaceDecl *iface,
7056 ArrayRef<QualType> lhsArgs,
7057 ArrayRef<QualType> rhsArgs,
7059 if (lhsArgs.size() != rhsArgs.size())
7062 ObjCTypeParamList *typeParams = iface->getTypeParamList();
7063 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
7064 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7067 switch (typeParams->begin()[i]->getVariance()) {
7068 case ObjCTypeParamVariance::Invariant:
7070 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7071 rhsArgs[i].stripObjCKindOfType(ctx))) {
7076 case ObjCTypeParamVariance::Covariant:
7077 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7081 case ObjCTypeParamVariance::Contravariant:
7082 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7091 QualType ASTContext::areCommonBaseCompatible(
7092 const ObjCObjectPointerType *Lptr,
7093 const ObjCObjectPointerType *Rptr) {
7094 const ObjCObjectType *LHS = Lptr->getObjectType();
7095 const ObjCObjectType *RHS = Rptr->getObjectType();
7096 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7097 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
7099 if (!LDecl || !RDecl)
7102 // Follow the left-hand side up the class hierarchy until we either hit a
7103 // root or find the RHS. Record the ancestors in case we don't find it.
7104 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7107 // Record this ancestor. We'll need this if the common type isn't in the
7108 // path from the LHS to the root.
7109 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
7111 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7112 // Get the type arguments.
7113 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7114 bool anyChanges = false;
7115 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7116 // Both have type arguments, compare them.
7117 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7118 LHS->getTypeArgs(), RHS->getTypeArgs(),
7119 /*stripKindOf=*/true))
7121 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7122 // If only one has type arguments, the result will not have type
7128 // Compute the intersection of protocols.
7129 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7130 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7132 if (!Protocols.empty())
7135 // If anything in the LHS will have changed, build a new result type.
7137 QualType Result = getObjCInterfaceType(LHS->getInterface());
7138 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7139 LHS->isKindOfType());
7140 return getObjCObjectPointerType(Result);
7143 return getObjCObjectPointerType(QualType(LHS, 0));
7146 // Find the superclass.
7147 QualType LHSSuperType = LHS->getSuperClassType();
7148 if (LHSSuperType.isNull())
7151 LHS = LHSSuperType->castAs<ObjCObjectType>();
7154 // We didn't find anything by following the LHS to its root; now check
7155 // the RHS against the cached set of ancestors.
7157 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7158 if (KnownLHS != LHSAncestors.end()) {
7159 LHS = KnownLHS->second;
7161 // Get the type arguments.
7162 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7163 bool anyChanges = false;
7164 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7165 // Both have type arguments, compare them.
7166 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7167 LHS->getTypeArgs(), RHS->getTypeArgs(),
7168 /*stripKindOf=*/true))
7170 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7171 // If only one has type arguments, the result will not have type
7177 // Compute the intersection of protocols.
7178 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7179 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7181 if (!Protocols.empty())
7185 QualType Result = getObjCInterfaceType(RHS->getInterface());
7186 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7187 RHS->isKindOfType());
7188 return getObjCObjectPointerType(Result);
7191 return getObjCObjectPointerType(QualType(RHS, 0));
7194 // Find the superclass of the RHS.
7195 QualType RHSSuperType = RHS->getSuperClassType();
7196 if (RHSSuperType.isNull())
7199 RHS = RHSSuperType->castAs<ObjCObjectType>();
7205 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7206 const ObjCObjectType *RHS) {
7207 assert(LHS->getInterface() && "LHS is not an interface type");
7208 assert(RHS->getInterface() && "RHS is not an interface type");
7210 // Verify that the base decls are compatible: the RHS must be a subclass of
7212 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7213 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7217 // If the LHS has protocol qualifiers, determine whether all of them are
7218 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7220 if (LHS->getNumProtocols() > 0) {
7221 // OK if conversion of LHS to SuperClass results in narrowing of types
7222 // ; i.e., SuperClass may implement at least one of the protocols
7223 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7224 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7225 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7226 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7227 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7229 for (auto *RHSPI : RHS->quals())
7230 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
7231 // If there is no protocols associated with RHS, it is not a match.
7232 if (SuperClassInheritedProtocols.empty())
7235 for (const auto *LHSProto : LHS->quals()) {
7236 bool SuperImplementsProtocol = false;
7237 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7238 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7239 SuperImplementsProtocol = true;
7242 if (!SuperImplementsProtocol)
7247 // If the LHS is specialized, we may need to check type arguments.
7248 if (LHS->isSpecialized()) {
7249 // Follow the superclass chain until we've matched the LHS class in the
7250 // hierarchy. This substitutes type arguments through.
7251 const ObjCObjectType *RHSSuper = RHS;
7252 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7253 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7255 // If the RHS is specializd, compare type arguments.
7256 if (RHSSuper->isSpecialized() &&
7257 !sameObjCTypeArgs(*this, LHS->getInterface(),
7258 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
7259 /*stripKindOf=*/true)) {
7267 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7268 // get the "pointed to" types
7269 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7270 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
7272 if (!LHSOPT || !RHSOPT)
7275 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7276 canAssignObjCInterfaces(RHSOPT, LHSOPT);
7279 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7280 return canAssignObjCInterfaces(
7281 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7282 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7285 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
7286 /// both shall have the identically qualified version of a compatible type.
7287 /// C99 6.2.7p1: Two types have compatible types if their types are the
7288 /// same. See 6.7.[2,3,5] for additional rules.
7289 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7290 bool CompareUnqualified) {
7291 if (getLangOpts().CPlusPlus)
7292 return hasSameType(LHS, RHS);
7294 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
7297 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
7298 return typesAreCompatible(LHS, RHS);
7301 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7302 return !mergeTypes(LHS, RHS, true).isNull();
7305 /// mergeTransparentUnionType - if T is a transparent union type and a member
7306 /// of T is compatible with SubType, return the merged type, else return
7308 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7309 bool OfBlockPointer,
7311 if (const RecordType *UT = T->getAsUnionType()) {
7312 RecordDecl *UD = UT->getDecl();
7313 if (UD->hasAttr<TransparentUnionAttr>()) {
7314 for (const auto *I : UD->fields()) {
7315 QualType ET = I->getType().getUnqualifiedType();
7316 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7326 /// mergeFunctionParameterTypes - merge two types which appear as function
7328 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7329 bool OfBlockPointer,
7331 // GNU extension: two types are compatible if they appear as a function
7332 // argument, one of the types is a transparent union type and the other
7333 // type is compatible with a union member
7334 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7336 if (!lmerge.isNull())
7339 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7341 if (!rmerge.isNull())
7344 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7347 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
7348 bool OfBlockPointer,
7350 const FunctionType *lbase = lhs->getAs<FunctionType>();
7351 const FunctionType *rbase = rhs->getAs<FunctionType>();
7352 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7353 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
7354 bool allLTypes = true;
7355 bool allRTypes = true;
7357 // Check return type
7359 if (OfBlockPointer) {
7360 QualType RHS = rbase->getReturnType();
7361 QualType LHS = lbase->getReturnType();
7362 bool UnqualifiedResult = Unqualified;
7363 if (!UnqualifiedResult)
7364 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
7365 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
7368 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
7370 if (retType.isNull()) return QualType();
7373 retType = retType.getUnqualifiedType();
7375 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7376 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
7378 LRetType = LRetType.getUnqualifiedType();
7379 RRetType = RRetType.getUnqualifiedType();
7382 if (getCanonicalType(retType) != LRetType)
7384 if (getCanonicalType(retType) != RRetType)
7387 // FIXME: double check this
7388 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7389 // rbase->getRegParmAttr() != 0 &&
7390 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
7391 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7392 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
7394 // Compatible functions must have compatible calling conventions
7395 if (lbaseInfo.getCC() != rbaseInfo.getCC())
7398 // Regparm is part of the calling convention.
7399 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7401 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7404 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7407 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7408 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
7410 if (lbaseInfo.getNoReturn() != NoReturn)
7412 if (rbaseInfo.getNoReturn() != NoReturn)
7415 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
7417 if (lproto && rproto) { // two C99 style function prototypes
7418 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7419 "C++ shouldn't be here");
7420 // Compatible functions must have the same number of parameters
7421 if (lproto->getNumParams() != rproto->getNumParams())
7424 // Variadic and non-variadic functions aren't compatible
7425 if (lproto->isVariadic() != rproto->isVariadic())
7428 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7431 if (LangOpts.ObjCAutoRefCount &&
7432 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7435 // Check parameter type compatibility
7436 SmallVector<QualType, 10> types;
7437 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7438 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7439 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7440 QualType paramType = mergeFunctionParameterTypes(
7441 lParamType, rParamType, OfBlockPointer, Unqualified);
7442 if (paramType.isNull())
7446 paramType = paramType.getUnqualifiedType();
7448 types.push_back(paramType);
7450 lParamType = lParamType.getUnqualifiedType();
7451 rParamType = rParamType.getUnqualifiedType();
7454 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
7456 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
7460 if (allLTypes) return lhs;
7461 if (allRTypes) return rhs;
7463 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7464 EPI.ExtInfo = einfo;
7465 return getFunctionType(retType, types, EPI);
7468 if (lproto) allRTypes = false;
7469 if (rproto) allLTypes = false;
7471 const FunctionProtoType *proto = lproto ? lproto : rproto;
7473 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7474 if (proto->isVariadic()) return QualType();
7475 // Check that the types are compatible with the types that
7476 // would result from default argument promotions (C99 6.7.5.3p15).
7477 // The only types actually affected are promotable integer
7478 // types and floats, which would be passed as a different
7479 // type depending on whether the prototype is visible.
7480 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7481 QualType paramTy = proto->getParamType(i);
7483 // Look at the converted type of enum types, since that is the type used
7484 // to pass enum values.
7485 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7486 paramTy = Enum->getDecl()->getIntegerType();
7487 if (paramTy.isNull())
7491 if (paramTy->isPromotableIntegerType() ||
7492 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
7496 if (allLTypes) return lhs;
7497 if (allRTypes) return rhs;
7499 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7500 EPI.ExtInfo = einfo;
7501 return getFunctionType(retType, proto->getParamTypes(), EPI);
7504 if (allLTypes) return lhs;
7505 if (allRTypes) return rhs;
7506 return getFunctionNoProtoType(retType, einfo);
7509 /// Given that we have an enum type and a non-enum type, try to merge them.
7510 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7511 QualType other, bool isBlockReturnType) {
7512 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7513 // a signed integer type, or an unsigned integer type.
7514 // Compatibility is based on the underlying type, not the promotion
7516 QualType underlyingType = ET->getDecl()->getIntegerType();
7517 if (underlyingType.isNull()) return QualType();
7518 if (Context.hasSameType(underlyingType, other))
7521 // In block return types, we're more permissive and accept any
7522 // integral type of the same size.
7523 if (isBlockReturnType && other->isIntegerType() &&
7524 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7530 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
7531 bool OfBlockPointer,
7532 bool Unqualified, bool BlockReturnType) {
7533 // C++ [expr]: If an expression initially has the type "reference to T", the
7534 // type is adjusted to "T" prior to any further analysis, the expression
7535 // designates the object or function denoted by the reference, and the
7536 // expression is an lvalue unless the reference is an rvalue reference and
7537 // the expression is a function call (possibly inside parentheses).
7538 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7539 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
7542 LHS = LHS.getUnqualifiedType();
7543 RHS = RHS.getUnqualifiedType();
7546 QualType LHSCan = getCanonicalType(LHS),
7547 RHSCan = getCanonicalType(RHS);
7549 // If two types are identical, they are compatible.
7550 if (LHSCan == RHSCan)
7553 // If the qualifiers are different, the types aren't compatible... mostly.
7554 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7555 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7556 if (LQuals != RQuals) {
7557 // If any of these qualifiers are different, we have a type
7559 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7560 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7561 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
7564 // Exactly one GC qualifier difference is allowed: __strong is
7565 // okay if the other type has no GC qualifier but is an Objective
7566 // C object pointer (i.e. implicitly strong by default). We fix
7567 // this by pretending that the unqualified type was actually
7568 // qualified __strong.
7569 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7570 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7571 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7573 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7576 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7577 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7579 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7580 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7585 // Okay, qualifiers are equal.
7587 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7588 Type::TypeClass RHSClass = RHSCan->getTypeClass();
7590 // We want to consider the two function types to be the same for these
7591 // comparisons, just force one to the other.
7592 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7593 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
7595 // Same as above for arrays
7596 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7597 LHSClass = Type::ConstantArray;
7598 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7599 RHSClass = Type::ConstantArray;
7601 // ObjCInterfaces are just specialized ObjCObjects.
7602 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7603 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7605 // Canonicalize ExtVector -> Vector.
7606 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7607 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
7609 // If the canonical type classes don't match.
7610 if (LHSClass != RHSClass) {
7611 // Note that we only have special rules for turning block enum
7612 // returns into block int returns, not vice-versa.
7613 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
7614 return mergeEnumWithInteger(*this, ETy, RHS, false);
7616 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
7617 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
7619 // allow block pointer type to match an 'id' type.
7620 if (OfBlockPointer && !BlockReturnType) {
7621 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7623 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7630 // The canonical type classes match.
7632 #define TYPE(Class, Base)
7633 #define ABSTRACT_TYPE(Class, Base)
7634 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
7635 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7636 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
7637 #include "clang/AST/TypeNodes.def"
7638 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
7641 case Type::LValueReference:
7642 case Type::RValueReference:
7643 case Type::MemberPointer:
7644 llvm_unreachable("C++ should never be in mergeTypes");
7646 case Type::ObjCInterface:
7647 case Type::IncompleteArray:
7648 case Type::VariableArray:
7649 case Type::FunctionProto:
7650 case Type::ExtVector:
7651 llvm_unreachable("Types are eliminated above");
7655 // Merge two pointer types, while trying to preserve typedef info
7656 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7657 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
7659 LHSPointee = LHSPointee.getUnqualifiedType();
7660 RHSPointee = RHSPointee.getUnqualifiedType();
7662 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7664 if (ResultType.isNull()) return QualType();
7665 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7667 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7669 return getPointerType(ResultType);
7671 case Type::BlockPointer:
7673 // Merge two block pointer types, while trying to preserve typedef info
7674 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7675 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7677 LHSPointee = LHSPointee.getUnqualifiedType();
7678 RHSPointee = RHSPointee.getUnqualifiedType();
7680 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7682 if (ResultType.isNull()) return QualType();
7683 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7685 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7687 return getBlockPointerType(ResultType);
7691 // Merge two pointer types, while trying to preserve typedef info
7692 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7693 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7695 LHSValue = LHSValue.getUnqualifiedType();
7696 RHSValue = RHSValue.getUnqualifiedType();
7698 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7700 if (ResultType.isNull()) return QualType();
7701 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7703 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7705 return getAtomicType(ResultType);
7707 case Type::ConstantArray:
7709 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7710 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7711 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7714 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7715 QualType RHSElem = getAsArrayType(RHS)->getElementType();
7717 LHSElem = LHSElem.getUnqualifiedType();
7718 RHSElem = RHSElem.getUnqualifiedType();
7721 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7722 if (ResultType.isNull()) return QualType();
7723 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7725 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7727 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7728 ArrayType::ArraySizeModifier(), 0);
7729 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7730 ArrayType::ArraySizeModifier(), 0);
7731 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7732 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7733 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7735 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7738 // FIXME: This isn't correct! But tricky to implement because
7739 // the array's size has to be the size of LHS, but the type
7740 // has to be different.
7744 // FIXME: This isn't correct! But tricky to implement because
7745 // the array's size has to be the size of RHS, but the type
7746 // has to be different.
7749 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7750 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7751 return getIncompleteArrayType(ResultType,
7752 ArrayType::ArraySizeModifier(), 0);
7754 case Type::FunctionNoProto:
7755 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7760 // Only exactly equal builtin types are compatible, which is tested above.
7763 // Distinct complex types are incompatible.
7766 // FIXME: The merged type should be an ExtVector!
7767 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7768 RHSCan->getAs<VectorType>()))
7771 case Type::ObjCObject: {
7772 // Check if the types are assignment compatible.
7773 // FIXME: This should be type compatibility, e.g. whether
7774 // "LHS x; RHS x;" at global scope is legal.
7775 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7776 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7777 if (canAssignObjCInterfaces(LHSIface, RHSIface))
7782 case Type::ObjCObjectPointer: {
7783 if (OfBlockPointer) {
7784 if (canAssignObjCInterfacesInBlockPointer(
7785 LHS->getAs<ObjCObjectPointerType>(),
7786 RHS->getAs<ObjCObjectPointerType>(),
7791 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7792 RHS->getAs<ObjCObjectPointerType>()))
7799 llvm_unreachable("Invalid Type::Class!");
7802 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7803 const FunctionProtoType *FromFunctionType,
7804 const FunctionProtoType *ToFunctionType) {
7805 if (FromFunctionType->hasAnyConsumedParams() !=
7806 ToFunctionType->hasAnyConsumedParams())
7808 FunctionProtoType::ExtProtoInfo FromEPI =
7809 FromFunctionType->getExtProtoInfo();
7810 FunctionProtoType::ExtProtoInfo ToEPI =
7811 ToFunctionType->getExtProtoInfo();
7812 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
7813 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7814 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
7820 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
7821 ObjCLayouts[CD] = nullptr;
7824 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7825 /// 'RHS' attributes and returns the merged version; including for function
7827 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7828 QualType LHSCan = getCanonicalType(LHS),
7829 RHSCan = getCanonicalType(RHS);
7830 // If two types are identical, they are compatible.
7831 if (LHSCan == RHSCan)
7833 if (RHSCan->isFunctionType()) {
7834 if (!LHSCan->isFunctionType())
7836 QualType OldReturnType =
7837 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
7838 QualType NewReturnType =
7839 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
7840 QualType ResReturnType =
7841 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7842 if (ResReturnType.isNull())
7844 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7845 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7846 // In either case, use OldReturnType to build the new function type.
7847 const FunctionType *F = LHS->getAs<FunctionType>();
7848 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7849 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7850 EPI.ExtInfo = getFunctionExtInfo(LHS);
7851 QualType ResultType =
7852 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
7859 // If the qualifiers are different, the types can still be merged.
7860 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7861 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7862 if (LQuals != RQuals) {
7863 // If any of these qualifiers are different, we have a type mismatch.
7864 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7865 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7868 // Exactly one GC qualifier difference is allowed: __strong is
7869 // okay if the other type has no GC qualifier but is an Objective
7870 // C object pointer (i.e. implicitly strong by default). We fix
7871 // this by pretending that the unqualified type was actually
7872 // qualified __strong.
7873 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7874 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7875 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7877 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7880 if (GC_L == Qualifiers::Strong)
7882 if (GC_R == Qualifiers::Strong)
7887 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7888 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7889 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7890 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7891 if (ResQT == LHSBaseQT)
7893 if (ResQT == RHSBaseQT)
7899 //===----------------------------------------------------------------------===//
7900 // Integer Predicates
7901 //===----------------------------------------------------------------------===//
7903 unsigned ASTContext::getIntWidth(QualType T) const {
7904 if (const EnumType *ET = T->getAs<EnumType>())
7905 T = ET->getDecl()->getIntegerType();
7906 if (T->isBooleanType())
7908 // For builtin types, just use the standard type sizing method
7909 return (unsigned)getTypeSize(T);
7912 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
7913 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
7915 // Turn <4 x signed int> -> <4 x unsigned int>
7916 if (const VectorType *VTy = T->getAs<VectorType>())
7917 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
7918 VTy->getNumElements(), VTy->getVectorKind());
7920 // For enums, we return the unsigned version of the base type.
7921 if (const EnumType *ETy = T->getAs<EnumType>())
7922 T = ETy->getDecl()->getIntegerType();
7924 const BuiltinType *BTy = T->getAs<BuiltinType>();
7925 assert(BTy && "Unexpected signed integer type");
7926 switch (BTy->getKind()) {
7927 case BuiltinType::Char_S:
7928 case BuiltinType::SChar:
7929 return UnsignedCharTy;
7930 case BuiltinType::Short:
7931 return UnsignedShortTy;
7932 case BuiltinType::Int:
7933 return UnsignedIntTy;
7934 case BuiltinType::Long:
7935 return UnsignedLongTy;
7936 case BuiltinType::LongLong:
7937 return UnsignedLongLongTy;
7938 case BuiltinType::Int128:
7939 return UnsignedInt128Ty;
7941 llvm_unreachable("Unexpected signed integer type");
7945 ASTMutationListener::~ASTMutationListener() { }
7947 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7948 QualType ReturnType) {}
7950 //===----------------------------------------------------------------------===//
7951 // Builtin Type Computation
7952 //===----------------------------------------------------------------------===//
7954 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
7955 /// pointer over the consumed characters. This returns the resultant type. If
7956 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7957 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7958 /// a vector of "i*".
7960 /// RequiresICE is filled in on return to indicate whether the value is required
7961 /// to be an Integer Constant Expression.
7962 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
7963 ASTContext::GetBuiltinTypeError &Error,
7965 bool AllowTypeModifiers) {
7968 bool Signed = false, Unsigned = false;
7969 RequiresICE = false;
7971 // Read the prefixed modifiers first.
7975 default: Done = true; --Str; break;
7980 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7981 assert(!Signed && "Can't use 'S' modifier multiple times!");
7985 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7986 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
7990 assert(HowLong <= 2 && "Can't have LLLL modifier");
7994 // This modifier represents int64 type.
7995 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7996 switch (Context.getTargetInfo().getInt64Type()) {
7998 llvm_unreachable("Unexpected integer type");
7999 case TargetInfo::SignedLong:
8002 case TargetInfo::SignedLongLong:
8011 // Read the base type.
8013 default: llvm_unreachable("Unknown builtin type letter!");
8015 assert(HowLong == 0 && !Signed && !Unsigned &&
8016 "Bad modifiers used with 'v'!");
8017 Type = Context.VoidTy;
8020 assert(HowLong == 0 && !Signed && !Unsigned &&
8021 "Bad modifiers used with 'h'!");
8022 Type = Context.HalfTy;
8025 assert(HowLong == 0 && !Signed && !Unsigned &&
8026 "Bad modifiers used with 'f'!");
8027 Type = Context.FloatTy;
8030 assert(HowLong < 2 && !Signed && !Unsigned &&
8031 "Bad modifiers used with 'd'!");
8033 Type = Context.LongDoubleTy;
8035 Type = Context.DoubleTy;
8038 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8040 Type = Context.UnsignedShortTy;
8042 Type = Context.ShortTy;
8046 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8047 else if (HowLong == 2)
8048 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8049 else if (HowLong == 1)
8050 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8052 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8055 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8057 Type = Context.SignedCharTy;
8059 Type = Context.UnsignedCharTy;
8061 Type = Context.CharTy;
8063 case 'b': // boolean
8064 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8065 Type = Context.BoolTy;
8067 case 'z': // size_t.
8068 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8069 Type = Context.getSizeType();
8072 Type = Context.getCFConstantStringType();
8075 Type = Context.getObjCIdType();
8078 Type = Context.getObjCSelType();
8081 Type = Context.getObjCSuperType();
8084 Type = Context.getBuiltinVaListType();
8085 assert(!Type.isNull() && "builtin va list type not initialized!");
8088 // This is a "reference" to a va_list; however, what exactly
8089 // this means depends on how va_list is defined. There are two
8090 // different kinds of va_list: ones passed by value, and ones
8091 // passed by reference. An example of a by-value va_list is
8092 // x86, where va_list is a char*. An example of by-ref va_list
8093 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8094 // we want this argument to be a char*&; for x86-64, we want
8095 // it to be a __va_list_tag*.
8096 Type = Context.getBuiltinVaListType();
8097 assert(!Type.isNull() && "builtin va list type not initialized!");
8098 if (Type->isArrayType())
8099 Type = Context.getArrayDecayedType(Type);
8101 Type = Context.getLValueReferenceType(Type);
8105 unsigned NumElements = strtoul(Str, &End, 10);
8106 assert(End != Str && "Missing vector size");
8109 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8110 RequiresICE, false);
8111 assert(!RequiresICE && "Can't require vector ICE");
8113 // TODO: No way to make AltiVec vectors in builtins yet.
8114 Type = Context.getVectorType(ElementType, NumElements,
8115 VectorType::GenericVector);
8121 unsigned NumElements = strtoul(Str, &End, 10);
8122 assert(End != Str && "Missing vector size");
8126 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8128 Type = Context.getExtVectorType(ElementType, NumElements);
8132 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8134 assert(!RequiresICE && "Can't require complex ICE");
8135 Type = Context.getComplexType(ElementType);
8139 Type = Context.getPointerDiffType();
8143 Type = Context.getFILEType();
8144 if (Type.isNull()) {
8145 Error = ASTContext::GE_Missing_stdio;
8151 Type = Context.getsigjmp_bufType();
8153 Type = Context.getjmp_bufType();
8155 if (Type.isNull()) {
8156 Error = ASTContext::GE_Missing_setjmp;
8161 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8162 Type = Context.getucontext_tType();
8164 if (Type.isNull()) {
8165 Error = ASTContext::GE_Missing_ucontext;
8170 Type = Context.getProcessIDType();
8174 // If there are modifiers and if we're allowed to parse them, go for it.
8175 Done = !AllowTypeModifiers;
8177 switch (char c = *Str++) {
8178 default: Done = true; --Str; break;
8181 // Both pointers and references can have their pointee types
8182 // qualified with an address space.
8184 unsigned AddrSpace = strtoul(Str, &End, 10);
8185 if (End != Str && AddrSpace != 0) {
8186 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8190 Type = Context.getPointerType(Type);
8192 Type = Context.getLValueReferenceType(Type);
8195 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8197 Type = Type.withConst();
8200 Type = Context.getVolatileType(Type);
8203 Type = Type.withRestrict();
8208 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
8209 "Integer constant 'I' type must be an integer");
8214 /// GetBuiltinType - Return the type for the specified builtin.
8215 QualType ASTContext::GetBuiltinType(unsigned Id,
8216 GetBuiltinTypeError &Error,
8217 unsigned *IntegerConstantArgs) const {
8218 const char *TypeStr = BuiltinInfo.getTypeString(Id);
8220 SmallVector<QualType, 8> ArgTypes;
8222 bool RequiresICE = false;
8224 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8226 if (Error != GE_None)
8229 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8231 while (TypeStr[0] && TypeStr[0] != '.') {
8232 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
8233 if (Error != GE_None)
8236 // If this argument is required to be an IntegerConstantExpression and the
8237 // caller cares, fill in the bitmask we return.
8238 if (RequiresICE && IntegerConstantArgs)
8239 *IntegerConstantArgs |= 1 << ArgTypes.size();
8241 // Do array -> pointer decay. The builtin should use the decayed type.
8242 if (Ty->isArrayType())
8243 Ty = getArrayDecayedType(Ty);
8245 ArgTypes.push_back(Ty);
8248 if (Id == Builtin::BI__GetExceptionInfo)
8251 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8252 "'.' should only occur at end of builtin type list!");
8254 FunctionType::ExtInfo EI(CC_C);
8255 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8257 bool Variadic = (TypeStr[0] == '.');
8259 // We really shouldn't be making a no-proto type here, especially in C++.
8260 if (ArgTypes.empty() && Variadic)
8261 return getFunctionNoProtoType(ResType, EI);
8263 FunctionProtoType::ExtProtoInfo EPI;
8265 EPI.Variadic = Variadic;
8267 return getFunctionType(ResType, ArgTypes, EPI);
8270 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8271 const FunctionDecl *FD) {
8272 if (!FD->isExternallyVisible())
8273 return GVA_Internal;
8275 GVALinkage External = GVA_StrongExternal;
8276 switch (FD->getTemplateSpecializationKind()) {
8277 case TSK_Undeclared:
8278 case TSK_ExplicitSpecialization:
8279 External = GVA_StrongExternal;
8282 case TSK_ExplicitInstantiationDefinition:
8283 return GVA_StrongODR;
8285 // C++11 [temp.explicit]p10:
8286 // [ Note: The intent is that an inline function that is the subject of
8287 // an explicit instantiation declaration will still be implicitly
8288 // instantiated when used so that the body can be considered for
8289 // inlining, but that no out-of-line copy of the inline function would be
8290 // generated in the translation unit. -- end note ]
8291 case TSK_ExplicitInstantiationDeclaration:
8292 return GVA_AvailableExternally;
8294 case TSK_ImplicitInstantiation:
8295 External = GVA_DiscardableODR;
8299 if (!FD->isInlined())
8302 if ((!Context.getLangOpts().CPlusPlus &&
8303 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8304 !FD->hasAttr<DLLExportAttr>()) ||
8305 FD->hasAttr<GNUInlineAttr>()) {
8306 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8308 // GNU or C99 inline semantics. Determine whether this symbol should be
8309 // externally visible.
8310 if (FD->isInlineDefinitionExternallyVisible())
8313 // C99 inline semantics, where the symbol is not externally visible.
8314 return GVA_AvailableExternally;
8317 // Functions specified with extern and inline in -fms-compatibility mode
8318 // forcibly get emitted. While the body of the function cannot be later
8319 // replaced, the function definition cannot be discarded.
8320 if (FD->isMSExternInline())
8321 return GVA_StrongODR;
8323 return GVA_DiscardableODR;
8326 static GVALinkage adjustGVALinkageForAttributes(GVALinkage L, const Decl *D) {
8327 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8328 // dllexport/dllimport on inline functions.
8329 if (D->hasAttr<DLLImportAttr>()) {
8330 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8331 return GVA_AvailableExternally;
8332 } else if (D->hasAttr<DLLExportAttr>() || D->hasAttr<CUDAGlobalAttr>()) {
8333 if (L == GVA_DiscardableODR)
8334 return GVA_StrongODR;
8339 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8340 return adjustGVALinkageForAttributes(basicGVALinkageForFunction(*this, FD),
8344 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8345 const VarDecl *VD) {
8346 if (!VD->isExternallyVisible())
8347 return GVA_Internal;
8349 if (VD->isStaticLocal()) {
8350 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8351 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8352 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8353 LexicalContext = LexicalContext->getLexicalParent();
8355 // Let the static local variable inherit its linkage from the nearest
8356 // enclosing function.
8358 StaticLocalLinkage =
8359 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8361 // GVA_StrongODR function linkage is stronger than what we need,
8362 // downgrade to GVA_DiscardableODR.
8363 // This allows us to discard the variable if we never end up needing it.
8364 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8365 : StaticLocalLinkage;
8368 // MSVC treats in-class initialized static data members as definitions.
8369 // By giving them non-strong linkage, out-of-line definitions won't
8370 // cause link errors.
8371 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8372 return GVA_DiscardableODR;
8374 switch (VD->getTemplateSpecializationKind()) {
8375 case TSK_Undeclared:
8376 return GVA_StrongExternal;
8378 case TSK_ExplicitSpecialization:
8379 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8380 VD->isStaticDataMember()
8382 : GVA_StrongExternal;
8384 case TSK_ExplicitInstantiationDefinition:
8385 return GVA_StrongODR;
8387 case TSK_ExplicitInstantiationDeclaration:
8388 return GVA_AvailableExternally;
8390 case TSK_ImplicitInstantiation:
8391 return GVA_DiscardableODR;
8394 llvm_unreachable("Invalid Linkage!");
8397 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8398 return adjustGVALinkageForAttributes(basicGVALinkageForVariable(*this, VD),
8402 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
8403 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8404 if (!VD->isFileVarDecl())
8406 // Global named register variables (GNU extension) are never emitted.
8407 if (VD->getStorageClass() == SC_Register)
8409 if (VD->getDescribedVarTemplate() ||
8410 isa<VarTemplatePartialSpecializationDecl>(VD))
8412 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8413 // We never need to emit an uninstantiated function template.
8414 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8416 } else if (isa<OMPThreadPrivateDecl>(D))
8421 // If this is a member of a class template, we do not need to emit it.
8422 if (D->getDeclContext()->isDependentContext())
8425 // Weak references don't produce any output by themselves.
8426 if (D->hasAttr<WeakRefAttr>())
8429 // Aliases and used decls are required.
8430 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8433 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8434 // Forward declarations aren't required.
8435 if (!FD->doesThisDeclarationHaveABody())
8436 return FD->doesDeclarationForceExternallyVisibleDefinition();
8438 // Constructors and destructors are required.
8439 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8442 // The key function for a class is required. This rule only comes
8443 // into play when inline functions can be key functions, though.
8444 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8445 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8446 const CXXRecordDecl *RD = MD->getParent();
8447 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8448 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8449 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8455 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8457 // static, static inline, always_inline, and extern inline functions can
8458 // always be deferred. Normal inline functions can be deferred in C99/C++.
8459 // Implicit template instantiations can also be deferred in C++.
8460 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8461 Linkage == GVA_DiscardableODR)
8466 const VarDecl *VD = cast<VarDecl>(D);
8467 assert(VD->isFileVarDecl() && "Expected file scoped var");
8469 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8470 !isMSStaticDataMemberInlineDefinition(VD))
8473 // Variables that can be needed in other TUs are required.
8474 GVALinkage L = GetGVALinkageForVariable(VD);
8475 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8476 L != GVA_DiscardableODR)
8479 // Variables that have destruction with side-effects are required.
8480 if (VD->getType().isDestructedType())
8483 // Variables that have initialization with side-effects are required.
8484 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8485 !VD->evaluateValue())
8491 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8492 bool IsCXXMethod) const {
8493 // Pass through to the C++ ABI object
8495 return ABI->getDefaultMethodCallConv(IsVariadic);
8497 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8499 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
8502 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
8503 // Pass through to the C++ ABI object
8504 return ABI->isNearlyEmpty(RD);
8507 VTableContextBase *ASTContext::getVTableContext() {
8508 if (!VTContext.get()) {
8509 if (Target->getCXXABI().isMicrosoft())
8510 VTContext.reset(new MicrosoftVTableContext(*this));
8512 VTContext.reset(new ItaniumVTableContext(*this));
8514 return VTContext.get();
8517 MangleContext *ASTContext::createMangleContext() {
8518 switch (Target->getCXXABI().getKind()) {
8519 case TargetCXXABI::GenericAArch64:
8520 case TargetCXXABI::GenericItanium:
8521 case TargetCXXABI::GenericARM:
8522 case TargetCXXABI::GenericMIPS:
8523 case TargetCXXABI::iOS:
8524 case TargetCXXABI::iOS64:
8525 case TargetCXXABI::WebAssembly:
8526 case TargetCXXABI::WatchOS:
8527 return ItaniumMangleContext::create(*this, getDiagnostics());
8528 case TargetCXXABI::Microsoft:
8529 return MicrosoftMangleContext::create(*this, getDiagnostics());
8531 llvm_unreachable("Unsupported ABI");
8534 CXXABI::~CXXABI() {}
8536 size_t ASTContext::getSideTableAllocatedMemory() const {
8537 return ASTRecordLayouts.getMemorySize() +
8538 llvm::capacity_in_bytes(ObjCLayouts) +
8539 llvm::capacity_in_bytes(KeyFunctions) +
8540 llvm::capacity_in_bytes(ObjCImpls) +
8541 llvm::capacity_in_bytes(BlockVarCopyInits) +
8542 llvm::capacity_in_bytes(DeclAttrs) +
8543 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8544 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8545 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8546 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8547 llvm::capacity_in_bytes(OverriddenMethods) +
8548 llvm::capacity_in_bytes(Types) +
8549 llvm::capacity_in_bytes(VariableArrayTypes) +
8550 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
8553 /// getIntTypeForBitwidth -
8554 /// sets integer QualTy according to specified details:
8555 /// bitwidth, signed/unsigned.
8556 /// Returns empty type if there is no appropriate target types.
8557 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8558 unsigned Signed) const {
8559 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8560 CanQualType QualTy = getFromTargetType(Ty);
8561 if (!QualTy && DestWidth == 128)
8562 return Signed ? Int128Ty : UnsignedInt128Ty;
8566 /// getRealTypeForBitwidth -
8567 /// sets floating point QualTy according to specified bitwidth.
8568 /// Returns empty type if there is no appropriate target types.
8569 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8570 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8572 case TargetInfo::Float:
8574 case TargetInfo::Double:
8576 case TargetInfo::LongDouble:
8577 return LongDoubleTy;
8578 case TargetInfo::NoFloat:
8582 llvm_unreachable("Unhandled TargetInfo::RealType value");
8585 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8587 MangleNumbers[ND] = Number;
8590 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8591 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8592 MangleNumbers.find(ND);
8593 return I != MangleNumbers.end() ? I->second : 1;
8596 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8598 StaticLocalNumbers[VD] = Number;
8601 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8602 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8603 StaticLocalNumbers.find(VD);
8604 return I != StaticLocalNumbers.end() ? I->second : 1;
8607 MangleNumberingContext &
8608 ASTContext::getManglingNumberContext(const DeclContext *DC) {
8609 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8610 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8612 MCtx = createMangleNumberingContext();
8616 MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8617 return ABI->createMangleNumberingContext();
8620 const CXXConstructorDecl *
8621 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8622 return ABI->getCopyConstructorForExceptionObject(
8623 cast<CXXRecordDecl>(RD->getFirstDecl()));
8626 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8627 CXXConstructorDecl *CD) {
8628 return ABI->addCopyConstructorForExceptionObject(
8629 cast<CXXRecordDecl>(RD->getFirstDecl()),
8630 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8633 void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8634 unsigned ParmIdx, Expr *DAE) {
8635 ABI->addDefaultArgExprForConstructor(
8636 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8639 Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8641 return ABI->getDefaultArgExprForConstructor(
8642 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8645 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8646 TypedefNameDecl *DD) {
8647 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8651 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8652 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8655 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8656 DeclaratorDecl *DD) {
8657 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8660 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8661 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8664 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8665 ParamIndices[D] = index;
8668 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8669 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8670 assert(I != ParamIndices.end() &&
8671 "ParmIndices lacks entry set by ParmVarDecl");
8676 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8678 assert(E && E->getStorageDuration() == SD_Static &&
8679 "don't need to cache the computed value for this temporary");
8681 APValue *&MTVI = MaterializedTemporaryValues[E];
8683 MTVI = new (*this) APValue;
8687 return MaterializedTemporaryValues.lookup(E);
8690 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8691 const llvm::Triple &T = getTargetInfo().getTriple();
8692 if (!T.isOSDarwin())
8695 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8696 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8699 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8700 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8701 uint64_t Size = sizeChars.getQuantity();
8702 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8703 unsigned Align = alignChars.getQuantity();
8704 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8705 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8710 ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8711 ASTContext::ParentMapPointers::mapped_type U) {
8712 if (const auto *D = U.dyn_cast<const Decl *>())
8713 return ast_type_traits::DynTypedNode::create(*D);
8714 if (const auto *S = U.dyn_cast<const Stmt *>())
8715 return ast_type_traits::DynTypedNode::create(*S);
8716 return *U.get<ast_type_traits::DynTypedNode *>();
8719 /// Template specializations to abstract away from pointers and TypeLocs.
8721 template <typename T>
8722 ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8723 return ast_type_traits::DynTypedNode::create(*Node);
8726 ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8727 return ast_type_traits::DynTypedNode::create(Node);
8730 ast_type_traits::DynTypedNode
8731 createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8732 return ast_type_traits::DynTypedNode::create(Node);
8736 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8737 /// parents as defined by the \c RecursiveASTVisitor.
8739 /// Note that the relationship described here is purely in terms of AST
8740 /// traversal - there are other relationships (for example declaration context)
8741 /// in the AST that are better modeled by special matchers.
8743 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8744 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8746 /// \brief Builds and returns the translation unit's parent map.
8748 /// The caller takes ownership of the returned \c ParentMap.
8749 static std::pair<ASTContext::ParentMapPointers *,
8750 ASTContext::ParentMapOtherNodes *>
8751 buildMap(TranslationUnitDecl &TU) {
8752 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8753 new ASTContext::ParentMapOtherNodes);
8754 Visitor.TraverseDecl(&TU);
8755 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
8759 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8761 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
8762 ASTContext::ParentMapOtherNodes *OtherParents)
8763 : Parents(Parents), OtherParents(OtherParents) {}
8765 bool shouldVisitTemplateInstantiations() const {
8768 bool shouldVisitImplicitCode() const {
8772 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
8774 bool TraverseNode(T Node, MapNodeTy MapNode,
8775 BaseTraverseFn BaseTraverse, MapTy *Parents) {
8778 if (ParentStack.size() > 0) {
8779 // FIXME: Currently we add the same parent multiple times, but only
8780 // when no memoization data is available for the type.
8781 // For example when we visit all subexpressions of template
8782 // instantiations; this is suboptimal, but benign: the only way to
8783 // visit those is with hasAncestor / hasParent, and those do not create
8785 // The plan is to enable DynTypedNode to be storable in a map or hash
8786 // map. The main problem there is to implement hash functions /
8787 // comparison operators for all types that DynTypedNode supports that
8788 // do not have pointer identity.
8789 auto &NodeOrVector = (*Parents)[MapNode];
8790 if (NodeOrVector.isNull()) {
8791 if (const auto *D = ParentStack.back().get<Decl>())
8793 else if (const auto *S = ParentStack.back().get<Stmt>())
8797 new ast_type_traits::DynTypedNode(ParentStack.back());
8799 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
8800 auto *Vector = new ASTContext::ParentVector(
8801 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
8804 .template dyn_cast<ast_type_traits::DynTypedNode *>())
8806 NodeOrVector = Vector;
8810 NodeOrVector.template get<ASTContext::ParentVector *>();
8811 // Skip duplicates for types that have memoization data.
8812 // We must check that the type has memoization data before calling
8813 // std::find() because DynTypedNode::operator== can't compare all
8815 bool Found = ParentStack.back().getMemoizationData() &&
8816 std::find(Vector->begin(), Vector->end(),
8817 ParentStack.back()) != Vector->end();
8819 Vector->push_back(ParentStack.back());
8822 ParentStack.push_back(createDynTypedNode(Node));
8823 bool Result = BaseTraverse();
8824 ParentStack.pop_back();
8828 bool TraverseDecl(Decl *DeclNode) {
8829 return TraverseNode(DeclNode, DeclNode,
8830 [&] { return VisitorBase::TraverseDecl(DeclNode); },
8834 bool TraverseStmt(Stmt *StmtNode) {
8835 return TraverseNode(StmtNode, StmtNode,
8836 [&] { return VisitorBase::TraverseStmt(StmtNode); },
8840 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
8841 return TraverseNode(
8842 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
8843 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
8847 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
8848 return TraverseNode(
8849 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
8851 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
8856 ASTContext::ParentMapPointers *Parents;
8857 ASTContext::ParentMapOtherNodes *OtherParents;
8858 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8860 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8863 } // anonymous namespace
8865 template <typename NodeTy, typename MapTy>
8866 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
8868 auto I = Map.find(Node);
8869 if (I == Map.end()) {
8870 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
8872 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
8873 return llvm::makeArrayRef(*V);
8875 return getSingleDynTypedNodeFromParentMap(I->second);
8878 ASTContext::DynTypedNodeList
8879 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8880 if (!PointerParents) {
8881 // We always need to run over the whole translation unit, as
8882 // hasAncestor can escape any subtree.
8883 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
8884 PointerParents.reset(Maps.first);
8885 OtherParents.reset(Maps.second);
8887 if (Node.getNodeKind().hasPointerIdentity())
8888 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
8889 return getDynNodeFromMap(Node, *OtherParents);
8893 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8894 const ObjCMethodDecl *MethodImpl) {
8895 // No point trying to match an unavailable/deprecated mothod.
8896 if (MethodDecl->hasAttr<UnavailableAttr>()
8897 || MethodDecl->hasAttr<DeprecatedAttr>())
8899 if (MethodDecl->getObjCDeclQualifier() !=
8900 MethodImpl->getObjCDeclQualifier())
8902 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
8905 if (MethodDecl->param_size() != MethodImpl->param_size())
8908 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8909 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8910 EF = MethodDecl->param_end();
8911 IM != EM && IF != EF; ++IM, ++IF) {
8912 const ParmVarDecl *DeclVar = (*IF);
8913 const ParmVarDecl *ImplVar = (*IM);
8914 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8916 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8919 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8923 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8924 // doesn't include ASTContext.h
8926 clang::LazyGenerationalUpdatePtr<
8927 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8928 clang::LazyGenerationalUpdatePtr<
8929 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8930 const clang::ASTContext &Ctx, Decl *Value);