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 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1849 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1850 return TypeInfo(Width, Align, AlignIsRequired);
1853 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1854 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1855 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1856 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1857 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1858 getTargetInfo().getABI() == "elfv1-qpx" &&
1859 T->isSpecificBuiltinType(BuiltinType::Double))
1864 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1865 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1866 return CharUnits::fromQuantity(BitSize / getCharWidth());
1869 /// toBits - Convert a size in characters to a size in characters.
1870 int64_t ASTContext::toBits(CharUnits CharSize) const {
1871 return CharSize.getQuantity() * getCharWidth();
1874 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1875 /// This method does not work on incomplete types.
1876 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1877 return getTypeInfoInChars(T).first;
1879 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1880 return getTypeInfoInChars(T).first;
1883 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1884 /// characters. This method does not work on incomplete types.
1885 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1886 return toCharUnitsFromBits(getTypeAlign(T));
1888 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1889 return toCharUnitsFromBits(getTypeAlign(T));
1892 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1893 /// type for the current target in bits. This can be different than the ABI
1894 /// alignment in cases where it is beneficial for performance to overalign
1896 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1897 TypeInfo TI = getTypeInfo(T);
1898 unsigned ABIAlign = TI.Align;
1900 T = T->getBaseElementTypeUnsafe();
1902 // The preferred alignment of member pointers is that of a pointer.
1903 if (T->isMemberPointerType())
1904 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1906 if (Target->getTriple().getArch() == llvm::Triple::xcore)
1907 return ABIAlign; // Never overalign on XCore.
1909 // Double and long long should be naturally aligned if possible.
1910 if (const ComplexType *CT = T->getAs<ComplexType>())
1911 T = CT->getElementType().getTypePtr();
1912 if (const EnumType *ET = T->getAs<EnumType>())
1913 T = ET->getDecl()->getIntegerType().getTypePtr();
1914 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1915 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1916 T->isSpecificBuiltinType(BuiltinType::ULongLong))
1917 // Don't increase the alignment if an alignment attribute was specified on a
1918 // typedef declaration.
1919 if (!TI.AlignIsRequired)
1920 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1925 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1926 /// for __attribute__((aligned)) on this target, to be used if no alignment
1927 /// value is specified.
1928 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
1929 return getTargetInfo().getDefaultAlignForAttributeAligned();
1932 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
1933 /// to a global variable of the specified type.
1934 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1935 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1938 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
1939 /// should be given to a global variable of the specified type.
1940 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1941 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1944 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1945 CharUnits Offset = CharUnits::Zero();
1946 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1947 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1948 Offset += Layout->getBaseClassOffset(Base);
1949 Layout = &getASTRecordLayout(Base);
1954 /// DeepCollectObjCIvars -
1955 /// This routine first collects all declared, but not synthesized, ivars in
1956 /// super class and then collects all ivars, including those synthesized for
1957 /// current class. This routine is used for implementation of current class
1958 /// when all ivars, declared and synthesized are known.
1960 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1962 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1963 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1964 DeepCollectObjCIvars(SuperClass, false, Ivars);
1966 for (const auto *I : OI->ivars())
1969 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1970 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1971 Iv= Iv->getNextIvar())
1972 Ivars.push_back(Iv);
1976 /// CollectInheritedProtocols - Collect all protocols in current class and
1977 /// those inherited by it.
1978 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1979 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1980 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1981 // We can use protocol_iterator here instead of
1982 // all_referenced_protocol_iterator since we are walking all categories.
1983 for (auto *Proto : OI->all_referenced_protocols()) {
1984 CollectInheritedProtocols(Proto, Protocols);
1987 // Categories of this Interface.
1988 for (const auto *Cat : OI->visible_categories())
1989 CollectInheritedProtocols(Cat, Protocols);
1991 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1993 CollectInheritedProtocols(SD, Protocols);
1994 SD = SD->getSuperClass();
1996 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1997 for (auto *Proto : OC->protocols()) {
1998 CollectInheritedProtocols(Proto, Protocols);
2000 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2001 // Insert the protocol.
2002 if (!Protocols.insert(
2003 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2006 for (auto *Proto : OP->protocols())
2007 CollectInheritedProtocols(Proto, Protocols);
2011 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2013 // Count ivars declared in class extension.
2014 for (const auto *Ext : OI->known_extensions())
2015 count += Ext->ivar_size();
2017 // Count ivar defined in this class's implementation. This
2018 // includes synthesized ivars.
2019 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2020 count += ImplDecl->ivar_size();
2025 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2029 // nullptr_t is always treated as null.
2030 if (E->getType()->isNullPtrType()) return true;
2032 if (E->getType()->isAnyPointerType() &&
2033 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2034 Expr::NPC_ValueDependentIsNull))
2037 // Unfortunately, __null has type 'int'.
2038 if (isa<GNUNullExpr>(E)) return true;
2043 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2044 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2045 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2046 I = ObjCImpls.find(D);
2047 if (I != ObjCImpls.end())
2048 return cast<ObjCImplementationDecl>(I->second);
2051 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2052 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2053 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2054 I = ObjCImpls.find(D);
2055 if (I != ObjCImpls.end())
2056 return cast<ObjCCategoryImplDecl>(I->second);
2060 /// \brief Set the implementation of ObjCInterfaceDecl.
2061 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2062 ObjCImplementationDecl *ImplD) {
2063 assert(IFaceD && ImplD && "Passed null params");
2064 ObjCImpls[IFaceD] = ImplD;
2066 /// \brief Set the implementation of ObjCCategoryDecl.
2067 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2068 ObjCCategoryImplDecl *ImplD) {
2069 assert(CatD && ImplD && "Passed null params");
2070 ObjCImpls[CatD] = ImplD;
2073 const ObjCMethodDecl *
2074 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2075 return ObjCMethodRedecls.lookup(MD);
2078 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2079 const ObjCMethodDecl *Redecl) {
2080 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2081 ObjCMethodRedecls[MD] = Redecl;
2084 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2085 const NamedDecl *ND) const {
2086 if (const ObjCInterfaceDecl *ID =
2087 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2089 if (const ObjCCategoryDecl *CD =
2090 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2091 return CD->getClassInterface();
2092 if (const ObjCImplDecl *IMD =
2093 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2094 return IMD->getClassInterface();
2099 /// \brief Get the copy initialization expression of VarDecl,or NULL if
2101 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
2102 assert(VD && "Passed null params");
2103 assert(VD->hasAttr<BlocksAttr>() &&
2104 "getBlockVarCopyInits - not __block var");
2105 llvm::DenseMap<const VarDecl*, Expr*>::iterator
2106 I = BlockVarCopyInits.find(VD);
2107 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
2110 /// \brief Set the copy inialization expression of a block var decl.
2111 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2112 assert(VD && Init && "Passed null params");
2113 assert(VD->hasAttr<BlocksAttr>() &&
2114 "setBlockVarCopyInits - not __block var");
2115 BlockVarCopyInits[VD] = Init;
2118 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2119 unsigned DataSize) const {
2121 DataSize = TypeLoc::getFullDataSizeForType(T);
2123 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2124 "incorrect data size provided to CreateTypeSourceInfo!");
2126 TypeSourceInfo *TInfo =
2127 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2128 new (TInfo) TypeSourceInfo(T);
2132 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2133 SourceLocation L) const {
2134 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2135 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2139 const ASTRecordLayout &
2140 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2141 return getObjCLayout(D, nullptr);
2144 const ASTRecordLayout &
2145 ASTContext::getASTObjCImplementationLayout(
2146 const ObjCImplementationDecl *D) const {
2147 return getObjCLayout(D->getClassInterface(), D);
2150 //===----------------------------------------------------------------------===//
2151 // Type creation/memoization methods
2152 //===----------------------------------------------------------------------===//
2155 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2156 unsigned fastQuals = quals.getFastQualifiers();
2157 quals.removeFastQualifiers();
2159 // Check if we've already instantiated this type.
2160 llvm::FoldingSetNodeID ID;
2161 ExtQuals::Profile(ID, baseType, quals);
2162 void *insertPos = nullptr;
2163 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2164 assert(eq->getQualifiers() == quals);
2165 return QualType(eq, fastQuals);
2168 // If the base type is not canonical, make the appropriate canonical type.
2170 if (!baseType->isCanonicalUnqualified()) {
2171 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2172 canonSplit.Quals.addConsistentQualifiers(quals);
2173 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2175 // Re-find the insert position.
2176 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2179 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2180 ExtQualNodes.InsertNode(eq, insertPos);
2181 return QualType(eq, fastQuals);
2185 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2186 QualType CanT = getCanonicalType(T);
2187 if (CanT.getAddressSpace() == AddressSpace)
2190 // If we are composing extended qualifiers together, merge together
2191 // into one ExtQuals node.
2192 QualifierCollector Quals;
2193 const Type *TypeNode = Quals.strip(T);
2195 // If this type already has an address space specified, it cannot get
2197 assert(!Quals.hasAddressSpace() &&
2198 "Type cannot be in multiple addr spaces!");
2199 Quals.addAddressSpace(AddressSpace);
2201 return getExtQualType(TypeNode, Quals);
2204 QualType ASTContext::getObjCGCQualType(QualType T,
2205 Qualifiers::GC GCAttr) const {
2206 QualType CanT = getCanonicalType(T);
2207 if (CanT.getObjCGCAttr() == GCAttr)
2210 if (const PointerType *ptr = T->getAs<PointerType>()) {
2211 QualType Pointee = ptr->getPointeeType();
2212 if (Pointee->isAnyPointerType()) {
2213 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2214 return getPointerType(ResultType);
2218 // If we are composing extended qualifiers together, merge together
2219 // into one ExtQuals node.
2220 QualifierCollector Quals;
2221 const Type *TypeNode = Quals.strip(T);
2223 // If this type already has an ObjCGC specified, it cannot get
2225 assert(!Quals.hasObjCGCAttr() &&
2226 "Type cannot have multiple ObjCGCs!");
2227 Quals.addObjCGCAttr(GCAttr);
2229 return getExtQualType(TypeNode, Quals);
2232 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2233 FunctionType::ExtInfo Info) {
2234 if (T->getExtInfo() == Info)
2238 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2239 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2241 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2242 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2244 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2247 return cast<FunctionType>(Result.getTypePtr());
2250 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2251 QualType ResultType) {
2252 FD = FD->getMostRecentDecl();
2254 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2255 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2256 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2257 if (FunctionDecl *Next = FD->getPreviousDecl())
2262 if (ASTMutationListener *L = getASTMutationListener())
2263 L->DeducedReturnType(FD, ResultType);
2266 /// Get a function type and produce the equivalent function type with the
2267 /// specified exception specification. Type sugar that can be present on a
2268 /// declaration of a function with an exception specification is permitted
2269 /// and preserved. Other type sugar (for instance, typedefs) is not.
2270 static QualType getFunctionTypeWithExceptionSpec(
2271 ASTContext &Context, QualType Orig,
2272 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2273 // Might have some parens.
2274 if (auto *PT = dyn_cast<ParenType>(Orig))
2275 return Context.getParenType(
2276 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2278 // Might have a calling-convention attribute.
2279 if (auto *AT = dyn_cast<AttributedType>(Orig))
2280 return Context.getAttributedType(
2282 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2283 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2286 // Anything else must be a function type. Rebuild it with the new exception
2288 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2289 return Context.getFunctionType(
2290 Proto->getReturnType(), Proto->getParamTypes(),
2291 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2294 void ASTContext::adjustExceptionSpec(
2295 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2299 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2300 FD->setType(Updated);
2305 // Update the type in the type source information too.
2306 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2307 // If the type and the type-as-written differ, we may need to update
2308 // the type-as-written too.
2309 if (TSInfo->getType() != FD->getType())
2310 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2312 // FIXME: When we get proper type location information for exceptions,
2313 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2314 // up the TypeSourceInfo;
2315 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2316 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2317 "TypeLoc size mismatch from updating exception specification");
2318 TSInfo->overrideType(Updated);
2322 /// getComplexType - Return the uniqued reference to the type for a complex
2323 /// number with the specified element type.
2324 QualType ASTContext::getComplexType(QualType T) const {
2325 // Unique pointers, to guarantee there is only one pointer of a particular
2327 llvm::FoldingSetNodeID ID;
2328 ComplexType::Profile(ID, T);
2330 void *InsertPos = nullptr;
2331 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2332 return QualType(CT, 0);
2334 // If the pointee type isn't canonical, this won't be a canonical type either,
2335 // so fill in the canonical type field.
2337 if (!T.isCanonical()) {
2338 Canonical = getComplexType(getCanonicalType(T));
2340 // Get the new insert position for the node we care about.
2341 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2342 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2344 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2345 Types.push_back(New);
2346 ComplexTypes.InsertNode(New, InsertPos);
2347 return QualType(New, 0);
2350 /// getPointerType - Return the uniqued reference to the type for a pointer to
2351 /// the specified type.
2352 QualType ASTContext::getPointerType(QualType T) const {
2353 // Unique pointers, to guarantee there is only one pointer of a particular
2355 llvm::FoldingSetNodeID ID;
2356 PointerType::Profile(ID, T);
2358 void *InsertPos = nullptr;
2359 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2360 return QualType(PT, 0);
2362 // If the pointee type isn't canonical, this won't be a canonical type either,
2363 // so fill in the canonical type field.
2365 if (!T.isCanonical()) {
2366 Canonical = getPointerType(getCanonicalType(T));
2368 // Get the new insert position for the node we care about.
2369 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2370 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2372 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2373 Types.push_back(New);
2374 PointerTypes.InsertNode(New, InsertPos);
2375 return QualType(New, 0);
2378 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2379 llvm::FoldingSetNodeID ID;
2380 AdjustedType::Profile(ID, Orig, New);
2381 void *InsertPos = nullptr;
2382 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2384 return QualType(AT, 0);
2386 QualType Canonical = getCanonicalType(New);
2388 // Get the new insert position for the node we care about.
2389 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2390 assert(!AT && "Shouldn't be in the map!");
2392 AT = new (*this, TypeAlignment)
2393 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2394 Types.push_back(AT);
2395 AdjustedTypes.InsertNode(AT, InsertPos);
2396 return QualType(AT, 0);
2399 QualType ASTContext::getDecayedType(QualType T) const {
2400 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2405 // A declaration of a parameter as "array of type" shall be
2406 // adjusted to "qualified pointer to type", where the type
2407 // qualifiers (if any) are those specified within the [ and ] of
2408 // the array type derivation.
2409 if (T->isArrayType())
2410 Decayed = getArrayDecayedType(T);
2413 // A declaration of a parameter as "function returning type"
2414 // shall be adjusted to "pointer to function returning type", as
2416 if (T->isFunctionType())
2417 Decayed = getPointerType(T);
2419 llvm::FoldingSetNodeID ID;
2420 AdjustedType::Profile(ID, T, Decayed);
2421 void *InsertPos = nullptr;
2422 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2424 return QualType(AT, 0);
2426 QualType Canonical = getCanonicalType(Decayed);
2428 // Get the new insert position for the node we care about.
2429 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2430 assert(!AT && "Shouldn't be in the map!");
2432 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2433 Types.push_back(AT);
2434 AdjustedTypes.InsertNode(AT, InsertPos);
2435 return QualType(AT, 0);
2438 /// getBlockPointerType - Return the uniqued reference to the type for
2439 /// a pointer to the specified block.
2440 QualType ASTContext::getBlockPointerType(QualType T) const {
2441 assert(T->isFunctionType() && "block of function types only");
2442 // Unique pointers, to guarantee there is only one block of a particular
2444 llvm::FoldingSetNodeID ID;
2445 BlockPointerType::Profile(ID, T);
2447 void *InsertPos = nullptr;
2448 if (BlockPointerType *PT =
2449 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2450 return QualType(PT, 0);
2452 // If the block pointee type isn't canonical, this won't be a canonical
2453 // type either so fill in the canonical type field.
2455 if (!T.isCanonical()) {
2456 Canonical = getBlockPointerType(getCanonicalType(T));
2458 // Get the new insert position for the node we care about.
2459 BlockPointerType *NewIP =
2460 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2461 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2463 BlockPointerType *New
2464 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2465 Types.push_back(New);
2466 BlockPointerTypes.InsertNode(New, InsertPos);
2467 return QualType(New, 0);
2470 /// getLValueReferenceType - Return the uniqued reference to the type for an
2471 /// lvalue reference to the specified type.
2473 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2474 assert(getCanonicalType(T) != OverloadTy &&
2475 "Unresolved overloaded function type");
2477 // Unique pointers, to guarantee there is only one pointer of a particular
2479 llvm::FoldingSetNodeID ID;
2480 ReferenceType::Profile(ID, T, SpelledAsLValue);
2482 void *InsertPos = nullptr;
2483 if (LValueReferenceType *RT =
2484 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2485 return QualType(RT, 0);
2487 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2489 // If the referencee type isn't canonical, this won't be a canonical type
2490 // either, so fill in the canonical type field.
2492 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2493 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2494 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2496 // Get the new insert position for the node we care about.
2497 LValueReferenceType *NewIP =
2498 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2499 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2502 LValueReferenceType *New
2503 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2505 Types.push_back(New);
2506 LValueReferenceTypes.InsertNode(New, InsertPos);
2508 return QualType(New, 0);
2511 /// getRValueReferenceType - Return the uniqued reference to the type for an
2512 /// rvalue reference to the specified type.
2513 QualType ASTContext::getRValueReferenceType(QualType T) const {
2514 // Unique pointers, to guarantee there is only one pointer of a particular
2516 llvm::FoldingSetNodeID ID;
2517 ReferenceType::Profile(ID, T, false);
2519 void *InsertPos = nullptr;
2520 if (RValueReferenceType *RT =
2521 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2522 return QualType(RT, 0);
2524 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2526 // If the referencee type isn't canonical, this won't be a canonical type
2527 // either, so fill in the canonical type field.
2529 if (InnerRef || !T.isCanonical()) {
2530 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2531 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2533 // Get the new insert position for the node we care about.
2534 RValueReferenceType *NewIP =
2535 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2536 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2539 RValueReferenceType *New
2540 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2541 Types.push_back(New);
2542 RValueReferenceTypes.InsertNode(New, InsertPos);
2543 return QualType(New, 0);
2546 /// getMemberPointerType - Return the uniqued reference to the type for a
2547 /// member pointer to the specified type, in the specified class.
2548 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2549 // Unique pointers, to guarantee there is only one pointer of a particular
2551 llvm::FoldingSetNodeID ID;
2552 MemberPointerType::Profile(ID, T, Cls);
2554 void *InsertPos = nullptr;
2555 if (MemberPointerType *PT =
2556 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2557 return QualType(PT, 0);
2559 // If the pointee or class type isn't canonical, this won't be a canonical
2560 // type either, so fill in the canonical type field.
2562 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2563 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2565 // Get the new insert position for the node we care about.
2566 MemberPointerType *NewIP =
2567 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2568 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2570 MemberPointerType *New
2571 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2572 Types.push_back(New);
2573 MemberPointerTypes.InsertNode(New, InsertPos);
2574 return QualType(New, 0);
2577 /// getConstantArrayType - Return the unique reference to the type for an
2578 /// array of the specified element type.
2579 QualType ASTContext::getConstantArrayType(QualType EltTy,
2580 const llvm::APInt &ArySizeIn,
2581 ArrayType::ArraySizeModifier ASM,
2582 unsigned IndexTypeQuals) const {
2583 assert((EltTy->isDependentType() ||
2584 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2585 "Constant array of VLAs is illegal!");
2587 // Convert the array size into a canonical width matching the pointer size for
2589 llvm::APInt ArySize(ArySizeIn);
2591 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2593 llvm::FoldingSetNodeID ID;
2594 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2596 void *InsertPos = nullptr;
2597 if (ConstantArrayType *ATP =
2598 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2599 return QualType(ATP, 0);
2601 // If the element type isn't canonical or has qualifiers, this won't
2602 // be a canonical type either, so fill in the canonical type field.
2604 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2605 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2606 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2607 ASM, IndexTypeQuals);
2608 Canon = getQualifiedType(Canon, canonSplit.Quals);
2610 // Get the new insert position for the node we care about.
2611 ConstantArrayType *NewIP =
2612 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2613 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2616 ConstantArrayType *New = new(*this,TypeAlignment)
2617 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2618 ConstantArrayTypes.InsertNode(New, InsertPos);
2619 Types.push_back(New);
2620 return QualType(New, 0);
2623 /// getVariableArrayDecayedType - Turns the given type, which may be
2624 /// variably-modified, into the corresponding type with all the known
2625 /// sizes replaced with [*].
2626 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2627 // Vastly most common case.
2628 if (!type->isVariablyModifiedType()) return type;
2632 SplitQualType split = type.getSplitDesugaredType();
2633 const Type *ty = split.Ty;
2634 switch (ty->getTypeClass()) {
2635 #define TYPE(Class, Base)
2636 #define ABSTRACT_TYPE(Class, Base)
2637 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2638 #include "clang/AST/TypeNodes.def"
2639 llvm_unreachable("didn't desugar past all non-canonical types?");
2641 // These types should never be variably-modified.
2645 case Type::ExtVector:
2646 case Type::DependentSizedExtVector:
2647 case Type::ObjCObject:
2648 case Type::ObjCInterface:
2649 case Type::ObjCObjectPointer:
2652 case Type::UnresolvedUsing:
2653 case Type::TypeOfExpr:
2655 case Type::Decltype:
2656 case Type::UnaryTransform:
2657 case Type::DependentName:
2658 case Type::InjectedClassName:
2659 case Type::TemplateSpecialization:
2660 case Type::DependentTemplateSpecialization:
2661 case Type::TemplateTypeParm:
2662 case Type::SubstTemplateTypeParmPack:
2664 case Type::PackExpansion:
2665 llvm_unreachable("type should never be variably-modified");
2667 // These types can be variably-modified but should never need to
2669 case Type::FunctionNoProto:
2670 case Type::FunctionProto:
2671 case Type::BlockPointer:
2672 case Type::MemberPointer:
2676 // These types can be variably-modified. All these modifications
2677 // preserve structure except as noted by comments.
2678 // TODO: if we ever care about optimizing VLAs, there are no-op
2679 // optimizations available here.
2681 result = getPointerType(getVariableArrayDecayedType(
2682 cast<PointerType>(ty)->getPointeeType()));
2685 case Type::LValueReference: {
2686 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2687 result = getLValueReferenceType(
2688 getVariableArrayDecayedType(lv->getPointeeType()),
2689 lv->isSpelledAsLValue());
2693 case Type::RValueReference: {
2694 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2695 result = getRValueReferenceType(
2696 getVariableArrayDecayedType(lv->getPointeeType()));
2700 case Type::Atomic: {
2701 const AtomicType *at = cast<AtomicType>(ty);
2702 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2706 case Type::ConstantArray: {
2707 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2708 result = getConstantArrayType(
2709 getVariableArrayDecayedType(cat->getElementType()),
2711 cat->getSizeModifier(),
2712 cat->getIndexTypeCVRQualifiers());
2716 case Type::DependentSizedArray: {
2717 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2718 result = getDependentSizedArrayType(
2719 getVariableArrayDecayedType(dat->getElementType()),
2721 dat->getSizeModifier(),
2722 dat->getIndexTypeCVRQualifiers(),
2723 dat->getBracketsRange());
2727 // Turn incomplete types into [*] types.
2728 case Type::IncompleteArray: {
2729 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2730 result = getVariableArrayType(
2731 getVariableArrayDecayedType(iat->getElementType()),
2734 iat->getIndexTypeCVRQualifiers(),
2739 // Turn VLA types into [*] types.
2740 case Type::VariableArray: {
2741 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2742 result = getVariableArrayType(
2743 getVariableArrayDecayedType(vat->getElementType()),
2746 vat->getIndexTypeCVRQualifiers(),
2747 vat->getBracketsRange());
2752 // Apply the top-level qualifiers from the original.
2753 return getQualifiedType(result, split.Quals);
2756 /// getVariableArrayType - Returns a non-unique reference to the type for a
2757 /// variable array of the specified element type.
2758 QualType ASTContext::getVariableArrayType(QualType EltTy,
2760 ArrayType::ArraySizeModifier ASM,
2761 unsigned IndexTypeQuals,
2762 SourceRange Brackets) const {
2763 // Since we don't unique expressions, it isn't possible to unique VLA's
2764 // that have an expression provided for their size.
2767 // Be sure to pull qualifiers off the element type.
2768 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2769 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2770 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2771 IndexTypeQuals, Brackets);
2772 Canon = getQualifiedType(Canon, canonSplit.Quals);
2775 VariableArrayType *New = new(*this, TypeAlignment)
2776 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2778 VariableArrayTypes.push_back(New);
2779 Types.push_back(New);
2780 return QualType(New, 0);
2783 /// getDependentSizedArrayType - Returns a non-unique reference to
2784 /// the type for a dependently-sized array of the specified element
2786 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2788 ArrayType::ArraySizeModifier ASM,
2789 unsigned elementTypeQuals,
2790 SourceRange brackets) const {
2791 assert((!numElements || numElements->isTypeDependent() ||
2792 numElements->isValueDependent()) &&
2793 "Size must be type- or value-dependent!");
2795 // Dependently-sized array types that do not have a specified number
2796 // of elements will have their sizes deduced from a dependent
2797 // initializer. We do no canonicalization here at all, which is okay
2798 // because they can't be used in most locations.
2800 DependentSizedArrayType *newType
2801 = new (*this, TypeAlignment)
2802 DependentSizedArrayType(*this, elementType, QualType(),
2803 numElements, ASM, elementTypeQuals,
2805 Types.push_back(newType);
2806 return QualType(newType, 0);
2809 // Otherwise, we actually build a new type every time, but we
2810 // also build a canonical type.
2812 SplitQualType canonElementType = getCanonicalType(elementType).split();
2814 void *insertPos = nullptr;
2815 llvm::FoldingSetNodeID ID;
2816 DependentSizedArrayType::Profile(ID, *this,
2817 QualType(canonElementType.Ty, 0),
2818 ASM, elementTypeQuals, numElements);
2820 // Look for an existing type with these properties.
2821 DependentSizedArrayType *canonTy =
2822 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2824 // If we don't have one, build one.
2826 canonTy = new (*this, TypeAlignment)
2827 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2828 QualType(), numElements, ASM, elementTypeQuals,
2830 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2831 Types.push_back(canonTy);
2834 // Apply qualifiers from the element type to the array.
2835 QualType canon = getQualifiedType(QualType(canonTy,0),
2836 canonElementType.Quals);
2838 // If we didn't need extra canonicalization for the element type or the size
2839 // expression, then just use that as our result.
2840 if (QualType(canonElementType.Ty, 0) == elementType &&
2841 canonTy->getSizeExpr() == numElements)
2844 // Otherwise, we need to build a type which follows the spelling
2845 // of the element type.
2846 DependentSizedArrayType *sugaredType
2847 = new (*this, TypeAlignment)
2848 DependentSizedArrayType(*this, elementType, canon, numElements,
2849 ASM, elementTypeQuals, brackets);
2850 Types.push_back(sugaredType);
2851 return QualType(sugaredType, 0);
2854 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2855 ArrayType::ArraySizeModifier ASM,
2856 unsigned elementTypeQuals) const {
2857 llvm::FoldingSetNodeID ID;
2858 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2860 void *insertPos = nullptr;
2861 if (IncompleteArrayType *iat =
2862 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2863 return QualType(iat, 0);
2865 // If the element type isn't canonical, this won't be a canonical type
2866 // either, so fill in the canonical type field. We also have to pull
2867 // qualifiers off the element type.
2870 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2871 SplitQualType canonSplit = getCanonicalType(elementType).split();
2872 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2873 ASM, elementTypeQuals);
2874 canon = getQualifiedType(canon, canonSplit.Quals);
2876 // Get the new insert position for the node we care about.
2877 IncompleteArrayType *existing =
2878 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2879 assert(!existing && "Shouldn't be in the map!"); (void) existing;
2882 IncompleteArrayType *newType = new (*this, TypeAlignment)
2883 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2885 IncompleteArrayTypes.InsertNode(newType, insertPos);
2886 Types.push_back(newType);
2887 return QualType(newType, 0);
2890 /// getVectorType - Return the unique reference to a vector type of
2891 /// the specified element type and size. VectorType must be a built-in type.
2892 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2893 VectorType::VectorKind VecKind) const {
2894 assert(vecType->isBuiltinType());
2896 // Check if we've already instantiated a vector of this type.
2897 llvm::FoldingSetNodeID ID;
2898 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2900 void *InsertPos = nullptr;
2901 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2902 return QualType(VTP, 0);
2904 // If the element type isn't canonical, this won't be a canonical type either,
2905 // so fill in the canonical type field.
2907 if (!vecType.isCanonical()) {
2908 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2910 // Get the new insert position for the node we care about.
2911 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2912 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2914 VectorType *New = new (*this, TypeAlignment)
2915 VectorType(vecType, NumElts, Canonical, VecKind);
2916 VectorTypes.InsertNode(New, InsertPos);
2917 Types.push_back(New);
2918 return QualType(New, 0);
2921 /// getExtVectorType - Return the unique reference to an extended vector type of
2922 /// the specified element type and size. VectorType must be a built-in type.
2924 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2925 assert(vecType->isBuiltinType() || vecType->isDependentType());
2927 // Check if we've already instantiated a vector of this type.
2928 llvm::FoldingSetNodeID ID;
2929 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2930 VectorType::GenericVector);
2931 void *InsertPos = nullptr;
2932 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2933 return QualType(VTP, 0);
2935 // If the element type isn't canonical, this won't be a canonical type either,
2936 // so fill in the canonical type field.
2938 if (!vecType.isCanonical()) {
2939 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2941 // Get the new insert position for the node we care about.
2942 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2943 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2945 ExtVectorType *New = new (*this, TypeAlignment)
2946 ExtVectorType(vecType, NumElts, Canonical);
2947 VectorTypes.InsertNode(New, InsertPos);
2948 Types.push_back(New);
2949 return QualType(New, 0);
2953 ASTContext::getDependentSizedExtVectorType(QualType vecType,
2955 SourceLocation AttrLoc) const {
2956 llvm::FoldingSetNodeID ID;
2957 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2960 void *InsertPos = nullptr;
2961 DependentSizedExtVectorType *Canon
2962 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2963 DependentSizedExtVectorType *New;
2965 // We already have a canonical version of this array type; use it as
2966 // the canonical type for a newly-built type.
2967 New = new (*this, TypeAlignment)
2968 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2971 QualType CanonVecTy = getCanonicalType(vecType);
2972 if (CanonVecTy == vecType) {
2973 New = new (*this, TypeAlignment)
2974 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2977 DependentSizedExtVectorType *CanonCheck
2978 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2979 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2981 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2983 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2985 New = new (*this, TypeAlignment)
2986 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2990 Types.push_back(New);
2991 return QualType(New, 0);
2994 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2997 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2998 const FunctionType::ExtInfo &Info) const {
2999 const CallingConv CallConv = Info.getCC();
3001 // Unique functions, to guarantee there is only one function of a particular
3003 llvm::FoldingSetNodeID ID;
3004 FunctionNoProtoType::Profile(ID, ResultTy, Info);
3006 void *InsertPos = nullptr;
3007 if (FunctionNoProtoType *FT =
3008 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3009 return QualType(FT, 0);
3012 if (!ResultTy.isCanonical()) {
3013 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
3015 // Get the new insert position for the node we care about.
3016 FunctionNoProtoType *NewIP =
3017 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3018 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3021 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
3022 FunctionNoProtoType *New = new (*this, TypeAlignment)
3023 FunctionNoProtoType(ResultTy, Canonical, newInfo);
3024 Types.push_back(New);
3025 FunctionNoProtoTypes.InsertNode(New, InsertPos);
3026 return QualType(New, 0);
3029 /// \brief Determine whether \p T is canonical as the result type of a function.
3030 static bool isCanonicalResultType(QualType T) {
3031 return T.isCanonical() &&
3032 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3033 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3037 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3038 CanQualType CanResultType = getCanonicalType(ResultType);
3040 // Canonical result types do not have ARC lifetime qualifiers.
3041 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3042 Qualifiers Qs = CanResultType.getQualifiers();
3043 Qs.removeObjCLifetime();
3044 return CanQualType::CreateUnsafe(
3045 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3048 return CanResultType;
3052 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
3053 const FunctionProtoType::ExtProtoInfo &EPI) const {
3054 size_t NumArgs = ArgArray.size();
3056 // Unique functions, to guarantee there is only one function of a particular
3058 llvm::FoldingSetNodeID ID;
3059 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3062 void *InsertPos = nullptr;
3063 if (FunctionProtoType *FTP =
3064 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3065 return QualType(FTP, 0);
3067 // Determine whether the type being created is already canonical or not.
3069 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
3070 !EPI.HasTrailingReturn;
3071 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
3072 if (!ArgArray[i].isCanonicalAsParam())
3073 isCanonical = false;
3075 // If this type isn't canonical, get the canonical version of it.
3076 // The exception spec is not part of the canonical type.
3079 SmallVector<QualType, 16> CanonicalArgs;
3080 CanonicalArgs.reserve(NumArgs);
3081 for (unsigned i = 0; i != NumArgs; ++i)
3082 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
3084 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
3085 CanonicalEPI.HasTrailingReturn = false;
3086 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3088 // Adjust the canonical function result type.
3089 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
3090 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
3092 // Get the new insert position for the node we care about.
3093 FunctionProtoType *NewIP =
3094 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3095 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3098 // FunctionProtoType objects are allocated with extra bytes after
3099 // them for three variable size arrays at the end:
3100 // - parameter types
3101 // - exception types
3102 // - consumed-arguments flags
3103 // Instead of the exception types, there could be a noexcept
3104 // expression, or information used to resolve the exception
3106 size_t Size = sizeof(FunctionProtoType) +
3107 NumArgs * sizeof(QualType);
3108 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3109 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3110 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3111 Size += sizeof(Expr*);
3112 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3113 Size += 2 * sizeof(FunctionDecl*);
3114 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3115 Size += sizeof(FunctionDecl*);
3117 if (EPI.ConsumedParameters)
3118 Size += NumArgs * sizeof(bool);
3120 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
3121 FunctionProtoType::ExtProtoInfo newEPI = EPI;
3122 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3123 Types.push_back(FTP);
3124 FunctionProtoTypes.InsertNode(FTP, InsertPos);
3125 return QualType(FTP, 0);
3128 /// Return pipe type for the specified type.
3129 QualType ASTContext::getPipeType(QualType T) const {
3130 llvm::FoldingSetNodeID ID;
3131 PipeType::Profile(ID, T);
3133 void *InsertPos = 0;
3134 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3135 return QualType(PT, 0);
3137 // If the pipe element type isn't canonical, this won't be a canonical type
3138 // either, so fill in the canonical type field.
3140 if (!T.isCanonical()) {
3141 Canonical = getPipeType(getCanonicalType(T));
3143 // Get the new insert position for the node we care about.
3144 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3145 assert(!NewIP && "Shouldn't be in the map!");
3148 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical);
3149 Types.push_back(New);
3150 PipeTypes.InsertNode(New, InsertPos);
3151 return QualType(New, 0);
3155 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3156 if (!isa<CXXRecordDecl>(D)) return false;
3157 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3158 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3160 if (RD->getDescribedClassTemplate() &&
3161 !isa<ClassTemplateSpecializationDecl>(RD))
3167 /// getInjectedClassNameType - Return the unique reference to the
3168 /// injected class name type for the specified templated declaration.
3169 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
3170 QualType TST) const {
3171 assert(NeedsInjectedClassNameType(Decl));
3172 if (Decl->TypeForDecl) {
3173 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3174 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
3175 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3176 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3177 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3180 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
3181 Decl->TypeForDecl = newType;
3182 Types.push_back(newType);
3184 return QualType(Decl->TypeForDecl, 0);
3187 /// getTypeDeclType - Return the unique reference to the type for the
3188 /// specified type declaration.
3189 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3190 assert(Decl && "Passed null for Decl param");
3191 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3193 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3194 return getTypedefType(Typedef);
3196 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3197 "Template type parameter types are always available.");
3199 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
3200 assert(Record->isFirstDecl() && "struct/union has previous declaration");
3201 assert(!NeedsInjectedClassNameType(Record));
3202 return getRecordType(Record);
3203 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
3204 assert(Enum->isFirstDecl() && "enum has previous declaration");
3205 return getEnumType(Enum);
3206 } else if (const UnresolvedUsingTypenameDecl *Using =
3207 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3208 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3209 Decl->TypeForDecl = newType;
3210 Types.push_back(newType);
3212 llvm_unreachable("TypeDecl without a type?");
3214 return QualType(Decl->TypeForDecl, 0);
3217 /// getTypedefType - Return the unique reference to the type for the
3218 /// specified typedef name decl.
3220 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3221 QualType Canonical) const {
3222 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3224 if (Canonical.isNull())
3225 Canonical = getCanonicalType(Decl->getUnderlyingType());
3226 TypedefType *newType = new(*this, TypeAlignment)
3227 TypedefType(Type::Typedef, Decl, Canonical);
3228 Decl->TypeForDecl = newType;
3229 Types.push_back(newType);
3230 return QualType(newType, 0);
3233 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
3234 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3236 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3237 if (PrevDecl->TypeForDecl)
3238 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3240 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3241 Decl->TypeForDecl = newType;
3242 Types.push_back(newType);
3243 return QualType(newType, 0);
3246 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3247 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3249 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3250 if (PrevDecl->TypeForDecl)
3251 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3253 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3254 Decl->TypeForDecl = newType;
3255 Types.push_back(newType);
3256 return QualType(newType, 0);
3259 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3260 QualType modifiedType,
3261 QualType equivalentType) {
3262 llvm::FoldingSetNodeID id;
3263 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3265 void *insertPos = nullptr;
3266 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3267 if (type) return QualType(type, 0);
3269 QualType canon = getCanonicalType(equivalentType);
3270 type = new (*this, TypeAlignment)
3271 AttributedType(canon, attrKind, modifiedType, equivalentType);
3273 Types.push_back(type);
3274 AttributedTypes.InsertNode(type, insertPos);
3276 return QualType(type, 0);
3279 /// \brief Retrieve a substitution-result type.
3281 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3282 QualType Replacement) const {
3283 assert(Replacement.isCanonical()
3284 && "replacement types must always be canonical");
3286 llvm::FoldingSetNodeID ID;
3287 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3288 void *InsertPos = nullptr;
3289 SubstTemplateTypeParmType *SubstParm
3290 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3293 SubstParm = new (*this, TypeAlignment)
3294 SubstTemplateTypeParmType(Parm, Replacement);
3295 Types.push_back(SubstParm);
3296 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3299 return QualType(SubstParm, 0);
3302 /// \brief Retrieve a
3303 QualType ASTContext::getSubstTemplateTypeParmPackType(
3304 const TemplateTypeParmType *Parm,
3305 const TemplateArgument &ArgPack) {
3307 for (const auto &P : ArgPack.pack_elements()) {
3308 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3309 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
3313 llvm::FoldingSetNodeID ID;
3314 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3315 void *InsertPos = nullptr;
3316 if (SubstTemplateTypeParmPackType *SubstParm
3317 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3318 return QualType(SubstParm, 0);
3321 if (!Parm->isCanonicalUnqualified()) {
3322 Canon = getCanonicalType(QualType(Parm, 0));
3323 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3325 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3328 SubstTemplateTypeParmPackType *SubstParm
3329 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3331 Types.push_back(SubstParm);
3332 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3333 return QualType(SubstParm, 0);
3336 /// \brief Retrieve the template type parameter type for a template
3337 /// parameter or parameter pack with the given depth, index, and (optionally)
3339 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3341 TemplateTypeParmDecl *TTPDecl) const {
3342 llvm::FoldingSetNodeID ID;
3343 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3344 void *InsertPos = nullptr;
3345 TemplateTypeParmType *TypeParm
3346 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3349 return QualType(TypeParm, 0);
3352 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3353 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3355 TemplateTypeParmType *TypeCheck
3356 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3357 assert(!TypeCheck && "Template type parameter canonical type broken");
3360 TypeParm = new (*this, TypeAlignment)
3361 TemplateTypeParmType(Depth, Index, ParameterPack);
3363 Types.push_back(TypeParm);
3364 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3366 return QualType(TypeParm, 0);
3370 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3371 SourceLocation NameLoc,
3372 const TemplateArgumentListInfo &Args,
3373 QualType Underlying) const {
3374 assert(!Name.getAsDependentTemplateName() &&
3375 "No dependent template names here!");
3376 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3378 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3379 TemplateSpecializationTypeLoc TL =
3380 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3381 TL.setTemplateKeywordLoc(SourceLocation());
3382 TL.setTemplateNameLoc(NameLoc);
3383 TL.setLAngleLoc(Args.getLAngleLoc());
3384 TL.setRAngleLoc(Args.getRAngleLoc());
3385 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3386 TL.setArgLocInfo(i, Args[i].getLocInfo());
3391 ASTContext::getTemplateSpecializationType(TemplateName Template,
3392 const TemplateArgumentListInfo &Args,
3393 QualType Underlying) const {
3394 assert(!Template.getAsDependentTemplateName() &&
3395 "No dependent template names here!");
3397 unsigned NumArgs = Args.size();
3399 SmallVector<TemplateArgument, 4> ArgVec;
3400 ArgVec.reserve(NumArgs);
3401 for (unsigned i = 0; i != NumArgs; ++i)
3402 ArgVec.push_back(Args[i].getArgument());
3404 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
3409 static bool hasAnyPackExpansions(const TemplateArgument *Args,
3411 for (unsigned I = 0; I != NumArgs; ++I)
3412 if (Args[I].isPackExpansion())
3420 ASTContext::getTemplateSpecializationType(TemplateName Template,
3421 const TemplateArgument *Args,
3423 QualType Underlying) const {
3424 assert(!Template.getAsDependentTemplateName() &&
3425 "No dependent template names here!");
3426 // Look through qualified template names.
3427 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3428 Template = TemplateName(QTN->getTemplateDecl());
3431 Template.getAsTemplateDecl() &&
3432 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3434 if (!Underlying.isNull())
3435 CanonType = getCanonicalType(Underlying);
3437 // We can get here with an alias template when the specialization contains
3438 // a pack expansion that does not match up with a parameter pack.
3439 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3440 "Caller must compute aliased type");
3441 IsTypeAlias = false;
3442 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3446 // Allocate the (non-canonical) template specialization type, but don't
3447 // try to unique it: these types typically have location information that
3448 // we don't unique and don't want to lose.
3449 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3450 sizeof(TemplateArgument) * NumArgs +
3451 (IsTypeAlias? sizeof(QualType) : 0),
3453 TemplateSpecializationType *Spec
3454 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3455 IsTypeAlias ? Underlying : QualType());
3457 Types.push_back(Spec);
3458 return QualType(Spec, 0);
3462 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3463 const TemplateArgument *Args,
3464 unsigned NumArgs) const {
3465 assert(!Template.getAsDependentTemplateName() &&
3466 "No dependent template names here!");
3468 // Look through qualified template names.
3469 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3470 Template = TemplateName(QTN->getTemplateDecl());
3472 // Build the canonical template specialization type.
3473 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3474 SmallVector<TemplateArgument, 4> CanonArgs;
3475 CanonArgs.reserve(NumArgs);
3476 for (unsigned I = 0; I != NumArgs; ++I)
3477 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3479 // Determine whether this canonical template specialization type already
3481 llvm::FoldingSetNodeID ID;
3482 TemplateSpecializationType::Profile(ID, CanonTemplate,
3483 CanonArgs.data(), NumArgs, *this);
3485 void *InsertPos = nullptr;
3486 TemplateSpecializationType *Spec
3487 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3490 // Allocate a new canonical template specialization type.
3491 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3492 sizeof(TemplateArgument) * NumArgs),
3494 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3495 CanonArgs.data(), NumArgs,
3496 QualType(), QualType());
3497 Types.push_back(Spec);
3498 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3501 assert(Spec->isDependentType() &&
3502 "Non-dependent template-id type must have a canonical type");
3503 return QualType(Spec, 0);
3507 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3508 NestedNameSpecifier *NNS,
3509 QualType NamedType) const {
3510 llvm::FoldingSetNodeID ID;
3511 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3513 void *InsertPos = nullptr;
3514 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3516 return QualType(T, 0);
3518 QualType Canon = NamedType;
3519 if (!Canon.isCanonical()) {
3520 Canon = getCanonicalType(NamedType);
3521 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3522 assert(!CheckT && "Elaborated canonical type broken");
3526 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
3528 ElaboratedTypes.InsertNode(T, InsertPos);
3529 return QualType(T, 0);
3533 ASTContext::getParenType(QualType InnerType) const {
3534 llvm::FoldingSetNodeID ID;
3535 ParenType::Profile(ID, InnerType);
3537 void *InsertPos = nullptr;
3538 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3540 return QualType(T, 0);
3542 QualType Canon = InnerType;
3543 if (!Canon.isCanonical()) {
3544 Canon = getCanonicalType(InnerType);
3545 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3546 assert(!CheckT && "Paren canonical type broken");
3550 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
3552 ParenTypes.InsertNode(T, InsertPos);
3553 return QualType(T, 0);
3556 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3557 NestedNameSpecifier *NNS,
3558 const IdentifierInfo *Name,
3559 QualType Canon) const {
3560 if (Canon.isNull()) {
3561 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3562 ElaboratedTypeKeyword CanonKeyword = Keyword;
3563 if (Keyword == ETK_None)
3564 CanonKeyword = ETK_Typename;
3566 if (CanonNNS != NNS || CanonKeyword != Keyword)
3567 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3570 llvm::FoldingSetNodeID ID;
3571 DependentNameType::Profile(ID, Keyword, NNS, Name);
3573 void *InsertPos = nullptr;
3574 DependentNameType *T
3575 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3577 return QualType(T, 0);
3579 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
3581 DependentNameTypes.InsertNode(T, InsertPos);
3582 return QualType(T, 0);
3586 ASTContext::getDependentTemplateSpecializationType(
3587 ElaboratedTypeKeyword Keyword,
3588 NestedNameSpecifier *NNS,
3589 const IdentifierInfo *Name,
3590 const TemplateArgumentListInfo &Args) const {
3591 // TODO: avoid this copy
3592 SmallVector<TemplateArgument, 16> ArgCopy;
3593 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3594 ArgCopy.push_back(Args[I].getArgument());
3595 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3601 ASTContext::getDependentTemplateSpecializationType(
3602 ElaboratedTypeKeyword Keyword,
3603 NestedNameSpecifier *NNS,
3604 const IdentifierInfo *Name,
3606 const TemplateArgument *Args) const {
3607 assert((!NNS || NNS->isDependent()) &&
3608 "nested-name-specifier must be dependent");
3610 llvm::FoldingSetNodeID ID;
3611 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3612 Name, NumArgs, Args);
3614 void *InsertPos = nullptr;
3615 DependentTemplateSpecializationType *T
3616 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3618 return QualType(T, 0);
3620 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3622 ElaboratedTypeKeyword CanonKeyword = Keyword;
3623 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3625 bool AnyNonCanonArgs = false;
3626 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3627 for (unsigned I = 0; I != NumArgs; ++I) {
3628 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3629 if (!CanonArgs[I].structurallyEquals(Args[I]))
3630 AnyNonCanonArgs = true;
3634 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3635 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3639 // Find the insert position again.
3640 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3643 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3644 sizeof(TemplateArgument) * NumArgs),
3646 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3647 Name, NumArgs, Args, Canon);
3649 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3650 return QualType(T, 0);
3653 QualType ASTContext::getPackExpansionType(QualType Pattern,
3654 Optional<unsigned> NumExpansions) {
3655 llvm::FoldingSetNodeID ID;
3656 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3658 assert(Pattern->containsUnexpandedParameterPack() &&
3659 "Pack expansions must expand one or more parameter packs");
3660 void *InsertPos = nullptr;
3661 PackExpansionType *T
3662 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3664 return QualType(T, 0);
3667 if (!Pattern.isCanonical()) {
3668 Canon = getCanonicalType(Pattern);
3669 // The canonical type might not contain an unexpanded parameter pack, if it
3670 // contains an alias template specialization which ignores one of its
3672 if (Canon->containsUnexpandedParameterPack()) {
3673 Canon = getPackExpansionType(Canon, NumExpansions);
3675 // Find the insert position again, in case we inserted an element into
3676 // PackExpansionTypes and invalidated our insert position.
3677 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3681 T = new (*this, TypeAlignment)
3682 PackExpansionType(Pattern, Canon, NumExpansions);
3684 PackExpansionTypes.InsertNode(T, InsertPos);
3685 return QualType(T, 0);
3688 /// CmpProtocolNames - Comparison predicate for sorting protocols
3690 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3691 ObjCProtocolDecl *const *RHS) {
3692 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
3695 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3696 if (Protocols.empty()) return true;
3698 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3701 for (unsigned i = 1; i != Protocols.size(); ++i)
3702 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
3703 Protocols[i]->getCanonicalDecl() != Protocols[i])
3709 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
3710 // Sort protocols, keyed by name.
3711 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
3714 for (ObjCProtocolDecl *&P : Protocols)
3715 P = P->getCanonicalDecl();
3717 // Remove duplicates.
3718 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3719 Protocols.erase(ProtocolsEnd, Protocols.end());
3722 QualType ASTContext::getObjCObjectType(QualType BaseType,
3723 ObjCProtocolDecl * const *Protocols,
3724 unsigned NumProtocols) const {
3725 return getObjCObjectType(BaseType, { },
3726 llvm::makeArrayRef(Protocols, NumProtocols),
3727 /*isKindOf=*/false);
3730 QualType ASTContext::getObjCObjectType(
3732 ArrayRef<QualType> typeArgs,
3733 ArrayRef<ObjCProtocolDecl *> protocols,
3734 bool isKindOf) const {
3735 // If the base type is an interface and there aren't any protocols or
3736 // type arguments to add, then the interface type will do just fine.
3737 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3738 isa<ObjCInterfaceType>(baseType))
3741 // Look in the folding set for an existing type.
3742 llvm::FoldingSetNodeID ID;
3743 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
3744 void *InsertPos = nullptr;
3745 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3746 return QualType(QT, 0);
3748 // Determine the type arguments to be used for canonicalization,
3749 // which may be explicitly specified here or written on the base
3751 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3752 if (effectiveTypeArgs.empty()) {
3753 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3754 effectiveTypeArgs = baseObject->getTypeArgs();
3757 // Build the canonical type, which has the canonical base type and a
3758 // sorted-and-uniqued list of protocols and the type arguments
3761 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3762 effectiveTypeArgs.end(),
3763 [&](QualType type) {
3764 return type.isCanonical();
3766 bool protocolsSorted = areSortedAndUniqued(protocols);
3767 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3768 // Determine the canonical type arguments.
3769 ArrayRef<QualType> canonTypeArgs;
3770 SmallVector<QualType, 4> canonTypeArgsVec;
3771 if (!typeArgsAreCanonical) {
3772 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3773 for (auto typeArg : effectiveTypeArgs)
3774 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3775 canonTypeArgs = canonTypeArgsVec;
3777 canonTypeArgs = effectiveTypeArgs;
3780 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3781 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3782 if (!protocolsSorted) {
3783 canonProtocolsVec.append(protocols.begin(), protocols.end());
3784 SortAndUniqueProtocols(canonProtocolsVec);
3785 canonProtocols = canonProtocolsVec;
3787 canonProtocols = protocols;
3790 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
3791 canonProtocols, isKindOf);
3793 // Regenerate InsertPos.
3794 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3797 unsigned size = sizeof(ObjCObjectTypeImpl);
3798 size += typeArgs.size() * sizeof(QualType);
3799 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3800 void *mem = Allocate(size, TypeAlignment);
3801 ObjCObjectTypeImpl *T =
3802 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3806 ObjCObjectTypes.InsertNode(T, InsertPos);
3807 return QualType(T, 0);
3810 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3811 /// protocol list adopt all protocols in QT's qualified-id protocol
3813 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3814 ObjCInterfaceDecl *IC) {
3815 if (!QT->isObjCQualifiedIdType())
3818 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3819 // If both the right and left sides have qualifiers.
3820 for (auto *Proto : OPT->quals()) {
3821 if (!IC->ClassImplementsProtocol(Proto, false))
3829 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3830 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
3832 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3833 ObjCInterfaceDecl *IDecl) {
3834 if (!QT->isObjCQualifiedIdType())
3836 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3839 if (!IDecl->hasDefinition())
3841 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3842 CollectInheritedProtocols(IDecl, InheritedProtocols);
3843 if (InheritedProtocols.empty())
3845 // Check that if every protocol in list of id<plist> conforms to a protcol
3846 // of IDecl's, then bridge casting is ok.
3847 bool Conforms = false;
3848 for (auto *Proto : OPT->quals()) {
3850 for (auto *PI : InheritedProtocols) {
3851 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3862 for (auto *PI : InheritedProtocols) {
3863 // If both the right and left sides have qualifiers.
3864 bool Adopts = false;
3865 for (auto *Proto : OPT->quals()) {
3866 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
3867 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
3876 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3877 /// the given object type.
3878 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
3879 llvm::FoldingSetNodeID ID;
3880 ObjCObjectPointerType::Profile(ID, ObjectT);
3882 void *InsertPos = nullptr;
3883 if (ObjCObjectPointerType *QT =
3884 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3885 return QualType(QT, 0);
3887 // Find the canonical object type.
3889 if (!ObjectT.isCanonical()) {
3890 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3892 // Regenerate InsertPos.
3893 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3897 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3898 ObjCObjectPointerType *QType =
3899 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
3901 Types.push_back(QType);
3902 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
3903 return QualType(QType, 0);
3906 /// getObjCInterfaceType - Return the unique reference to the type for the
3907 /// specified ObjC interface decl. The list of protocols is optional.
3908 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3909 ObjCInterfaceDecl *PrevDecl) const {
3910 if (Decl->TypeForDecl)
3911 return QualType(Decl->TypeForDecl, 0);
3914 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3915 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3916 return QualType(PrevDecl->TypeForDecl, 0);
3919 // Prefer the definition, if there is one.
3920 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3923 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3924 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3925 Decl->TypeForDecl = T;
3927 return QualType(T, 0);
3930 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3931 /// TypeOfExprType AST's (since expression's are never shared). For example,
3932 /// multiple declarations that refer to "typeof(x)" all contain different
3933 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
3934 /// on canonical type's (which are always unique).
3935 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
3936 TypeOfExprType *toe;
3937 if (tofExpr->isTypeDependent()) {
3938 llvm::FoldingSetNodeID ID;
3939 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3941 void *InsertPos = nullptr;
3942 DependentTypeOfExprType *Canon
3943 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3945 // We already have a "canonical" version of an identical, dependent
3946 // typeof(expr) type. Use that as our canonical type.
3947 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3948 QualType((TypeOfExprType*)Canon, 0));
3950 // Build a new, canonical typeof(expr) type.
3952 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3953 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3957 QualType Canonical = getCanonicalType(tofExpr->getType());
3958 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3960 Types.push_back(toe);
3961 return QualType(toe, 0);
3964 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3965 /// TypeOfType nodes. The only motivation to unique these nodes would be
3966 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3967 /// an issue. This doesn't affect the type checker, since it operates
3968 /// on canonical types (which are always unique).
3969 QualType ASTContext::getTypeOfType(QualType tofType) const {
3970 QualType Canonical = getCanonicalType(tofType);
3971 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3972 Types.push_back(tot);
3973 return QualType(tot, 0);
3976 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3977 /// nodes. This would never be helpful, since each such type has its own
3978 /// expression, and would not give a significant memory saving, since there
3979 /// is an Expr tree under each such type.
3980 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3983 // C++11 [temp.type]p2:
3984 // If an expression e involves a template parameter, decltype(e) denotes a
3985 // unique dependent type. Two such decltype-specifiers refer to the same
3986 // type only if their expressions are equivalent (14.5.6.1).
3987 if (e->isInstantiationDependent()) {
3988 llvm::FoldingSetNodeID ID;
3989 DependentDecltypeType::Profile(ID, *this, e);
3991 void *InsertPos = nullptr;
3992 DependentDecltypeType *Canon
3993 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3995 // Build a new, canonical typeof(expr) type.
3996 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3997 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3999 dt = new (*this, TypeAlignment)
4000 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
4002 dt = new (*this, TypeAlignment)
4003 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
4005 Types.push_back(dt);
4006 return QualType(dt, 0);
4009 /// getUnaryTransformationType - We don't unique these, since the memory
4010 /// savings are minimal and these are rare.
4011 QualType ASTContext::getUnaryTransformType(QualType BaseType,
4012 QualType UnderlyingType,
4013 UnaryTransformType::UTTKind Kind)
4015 UnaryTransformType *Ty =
4016 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
4018 UnderlyingType->isDependentType() ?
4019 QualType() : getCanonicalType(UnderlyingType));
4020 Types.push_back(Ty);
4021 return QualType(Ty, 0);
4024 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
4025 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4026 /// canonical deduced-but-dependent 'auto' type.
4027 QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
4028 bool IsDependent) const {
4029 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
4030 return getAutoDeductType();
4032 // Look in the folding set for an existing type.
4033 void *InsertPos = nullptr;
4034 llvm::FoldingSetNodeID ID;
4035 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
4036 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4037 return QualType(AT, 0);
4039 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
4042 Types.push_back(AT);
4044 AutoTypes.InsertNode(AT, InsertPos);
4045 return QualType(AT, 0);
4048 /// getAtomicType - Return the uniqued reference to the atomic type for
4049 /// the given value type.
4050 QualType ASTContext::getAtomicType(QualType T) const {
4051 // Unique pointers, to guarantee there is only one pointer of a particular
4053 llvm::FoldingSetNodeID ID;
4054 AtomicType::Profile(ID, T);
4056 void *InsertPos = nullptr;
4057 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4058 return QualType(AT, 0);
4060 // If the atomic value type isn't canonical, this won't be a canonical type
4061 // either, so fill in the canonical type field.
4063 if (!T.isCanonical()) {
4064 Canonical = getAtomicType(getCanonicalType(T));
4066 // Get the new insert position for the node we care about.
4067 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
4068 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4070 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4071 Types.push_back(New);
4072 AtomicTypes.InsertNode(New, InsertPos);
4073 return QualType(New, 0);
4076 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
4077 QualType ASTContext::getAutoDeductType() const {
4078 if (AutoDeductTy.isNull())
4079 AutoDeductTy = QualType(
4080 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
4081 /*dependent*/false),
4083 return AutoDeductTy;
4086 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4087 QualType ASTContext::getAutoRRefDeductType() const {
4088 if (AutoRRefDeductTy.isNull())
4089 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4090 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4091 return AutoRRefDeductTy;
4094 /// getTagDeclType - Return the unique reference to the type for the
4095 /// specified TagDecl (struct/union/class/enum) decl.
4096 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
4098 // FIXME: What is the design on getTagDeclType when it requires casting
4099 // away const? mutable?
4100 return getTypeDeclType(const_cast<TagDecl*>(Decl));
4103 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4104 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4105 /// needs to agree with the definition in <stddef.h>.
4106 CanQualType ASTContext::getSizeType() const {
4107 return getFromTargetType(Target->getSizeType());
4110 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4111 CanQualType ASTContext::getIntMaxType() const {
4112 return getFromTargetType(Target->getIntMaxType());
4115 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4116 CanQualType ASTContext::getUIntMaxType() const {
4117 return getFromTargetType(Target->getUIntMaxType());
4120 /// getSignedWCharType - Return the type of "signed wchar_t".
4121 /// Used when in C++, as a GCC extension.
4122 QualType ASTContext::getSignedWCharType() const {
4123 // FIXME: derive from "Target" ?
4127 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4128 /// Used when in C++, as a GCC extension.
4129 QualType ASTContext::getUnsignedWCharType() const {
4130 // FIXME: derive from "Target" ?
4131 return UnsignedIntTy;
4134 QualType ASTContext::getIntPtrType() const {
4135 return getFromTargetType(Target->getIntPtrType());
4138 QualType ASTContext::getUIntPtrType() const {
4139 return getCorrespondingUnsignedType(getIntPtrType());
4142 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
4143 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4144 QualType ASTContext::getPointerDiffType() const {
4145 return getFromTargetType(Target->getPtrDiffType(0));
4148 /// \brief Return the unique type for "pid_t" defined in
4149 /// <sys/types.h>. We need this to compute the correct type for vfork().
4150 QualType ASTContext::getProcessIDType() const {
4151 return getFromTargetType(Target->getProcessIDType());
4154 //===----------------------------------------------------------------------===//
4156 //===----------------------------------------------------------------------===//
4158 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
4159 // Push qualifiers into arrays, and then discard any remaining
4161 T = getCanonicalType(T);
4162 T = getVariableArrayDecayedType(T);
4163 const Type *Ty = T.getTypePtr();
4165 if (isa<ArrayType>(Ty)) {
4166 Result = getArrayDecayedType(QualType(Ty,0));
4167 } else if (isa<FunctionType>(Ty)) {
4168 Result = getPointerType(QualType(Ty, 0));
4170 Result = QualType(Ty, 0);
4173 return CanQualType::CreateUnsafe(Result);
4176 QualType ASTContext::getUnqualifiedArrayType(QualType type,
4177 Qualifiers &quals) {
4178 SplitQualType splitType = type.getSplitUnqualifiedType();
4180 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4181 // the unqualified desugared type and then drops it on the floor.
4182 // We then have to strip that sugar back off with
4183 // getUnqualifiedDesugaredType(), which is silly.
4184 const ArrayType *AT =
4185 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
4187 // If we don't have an array, just use the results in splitType.
4189 quals = splitType.Quals;
4190 return QualType(splitType.Ty, 0);
4193 // Otherwise, recurse on the array's element type.
4194 QualType elementType = AT->getElementType();
4195 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4197 // If that didn't change the element type, AT has no qualifiers, so we
4198 // can just use the results in splitType.
4199 if (elementType == unqualElementType) {
4200 assert(quals.empty()); // from the recursive call
4201 quals = splitType.Quals;
4202 return QualType(splitType.Ty, 0);
4205 // Otherwise, add in the qualifiers from the outermost type, then
4206 // build the type back up.
4207 quals.addConsistentQualifiers(splitType.Quals);
4209 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4210 return getConstantArrayType(unqualElementType, CAT->getSize(),
4211 CAT->getSizeModifier(), 0);
4214 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
4215 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
4218 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
4219 return getVariableArrayType(unqualElementType,
4221 VAT->getSizeModifier(),
4222 VAT->getIndexTypeCVRQualifiers(),
4223 VAT->getBracketsRange());
4226 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
4227 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
4228 DSAT->getSizeModifier(), 0,
4232 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4233 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4234 /// they point to and return true. If T1 and T2 aren't pointer types
4235 /// or pointer-to-member types, or if they are not similar at this
4236 /// level, returns false and leaves T1 and T2 unchanged. Top-level
4237 /// qualifiers on T1 and T2 are ignored. This function will typically
4238 /// be called in a loop that successively "unwraps" pointer and
4239 /// pointer-to-member types to compare them at each level.
4240 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4241 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4242 *T2PtrType = T2->getAs<PointerType>();
4243 if (T1PtrType && T2PtrType) {
4244 T1 = T1PtrType->getPointeeType();
4245 T2 = T2PtrType->getPointeeType();
4249 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4250 *T2MPType = T2->getAs<MemberPointerType>();
4251 if (T1MPType && T2MPType &&
4252 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4253 QualType(T2MPType->getClass(), 0))) {
4254 T1 = T1MPType->getPointeeType();
4255 T2 = T2MPType->getPointeeType();
4259 if (getLangOpts().ObjC1) {
4260 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4261 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4262 if (T1OPType && T2OPType) {
4263 T1 = T1OPType->getPointeeType();
4264 T2 = T2OPType->getPointeeType();
4269 // FIXME: Block pointers, too?
4275 ASTContext::getNameForTemplate(TemplateName Name,
4276 SourceLocation NameLoc) const {
4277 switch (Name.getKind()) {
4278 case TemplateName::QualifiedTemplate:
4279 case TemplateName::Template:
4280 // DNInfo work in progress: CHECKME: what about DNLoc?
4281 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4284 case TemplateName::OverloadedTemplate: {
4285 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4286 // DNInfo work in progress: CHECKME: what about DNLoc?
4287 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4290 case TemplateName::DependentTemplate: {
4291 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4292 DeclarationName DName;
4293 if (DTN->isIdentifier()) {
4294 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4295 return DeclarationNameInfo(DName, NameLoc);
4297 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4298 // DNInfo work in progress: FIXME: source locations?
4299 DeclarationNameLoc DNLoc;
4300 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4301 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4302 return DeclarationNameInfo(DName, NameLoc, DNLoc);
4306 case TemplateName::SubstTemplateTemplateParm: {
4307 SubstTemplateTemplateParmStorage *subst
4308 = Name.getAsSubstTemplateTemplateParm();
4309 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4313 case TemplateName::SubstTemplateTemplateParmPack: {
4314 SubstTemplateTemplateParmPackStorage *subst
4315 = Name.getAsSubstTemplateTemplateParmPack();
4316 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4321 llvm_unreachable("bad template name kind!");
4324 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4325 switch (Name.getKind()) {
4326 case TemplateName::QualifiedTemplate:
4327 case TemplateName::Template: {
4328 TemplateDecl *Template = Name.getAsTemplateDecl();
4329 if (TemplateTemplateParmDecl *TTP
4330 = dyn_cast<TemplateTemplateParmDecl>(Template))
4331 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4333 // The canonical template name is the canonical template declaration.
4334 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4337 case TemplateName::OverloadedTemplate:
4338 llvm_unreachable("cannot canonicalize overloaded template");
4340 case TemplateName::DependentTemplate: {
4341 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4342 assert(DTN && "Non-dependent template names must refer to template decls.");
4343 return DTN->CanonicalTemplateName;
4346 case TemplateName::SubstTemplateTemplateParm: {
4347 SubstTemplateTemplateParmStorage *subst
4348 = Name.getAsSubstTemplateTemplateParm();
4349 return getCanonicalTemplateName(subst->getReplacement());
4352 case TemplateName::SubstTemplateTemplateParmPack: {
4353 SubstTemplateTemplateParmPackStorage *subst
4354 = Name.getAsSubstTemplateTemplateParmPack();
4355 TemplateTemplateParmDecl *canonParameter
4356 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4357 TemplateArgument canonArgPack
4358 = getCanonicalTemplateArgument(subst->getArgumentPack());
4359 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4363 llvm_unreachable("bad template name!");
4366 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4367 X = getCanonicalTemplateName(X);
4368 Y = getCanonicalTemplateName(Y);
4369 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4373 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4374 switch (Arg.getKind()) {
4375 case TemplateArgument::Null:
4378 case TemplateArgument::Expression:
4381 case TemplateArgument::Declaration: {
4382 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4383 return TemplateArgument(D, Arg.getParamTypeForDecl());
4386 case TemplateArgument::NullPtr:
4387 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4390 case TemplateArgument::Template:
4391 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4393 case TemplateArgument::TemplateExpansion:
4394 return TemplateArgument(getCanonicalTemplateName(
4395 Arg.getAsTemplateOrTemplatePattern()),
4396 Arg.getNumTemplateExpansions());
4398 case TemplateArgument::Integral:
4399 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4401 case TemplateArgument::Type:
4402 return TemplateArgument(getCanonicalType(Arg.getAsType()));
4404 case TemplateArgument::Pack: {
4405 if (Arg.pack_size() == 0)
4408 TemplateArgument *CanonArgs
4409 = new (*this) TemplateArgument[Arg.pack_size()];
4411 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4412 AEnd = Arg.pack_end();
4413 A != AEnd; (void)++A, ++Idx)
4414 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4416 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
4420 // Silence GCC warning
4421 llvm_unreachable("Unhandled template argument kind");
4424 NestedNameSpecifier *
4425 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4429 switch (NNS->getKind()) {
4430 case NestedNameSpecifier::Identifier:
4431 // Canonicalize the prefix but keep the identifier the same.
4432 return NestedNameSpecifier::Create(*this,
4433 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4434 NNS->getAsIdentifier());
4436 case NestedNameSpecifier::Namespace:
4437 // A namespace is canonical; build a nested-name-specifier with
4438 // this namespace and no prefix.
4439 return NestedNameSpecifier::Create(*this, nullptr,
4440 NNS->getAsNamespace()->getOriginalNamespace());
4442 case NestedNameSpecifier::NamespaceAlias:
4443 // A namespace is canonical; build a nested-name-specifier with
4444 // this namespace and no prefix.
4445 return NestedNameSpecifier::Create(*this, nullptr,
4446 NNS->getAsNamespaceAlias()->getNamespace()
4447 ->getOriginalNamespace());
4449 case NestedNameSpecifier::TypeSpec:
4450 case NestedNameSpecifier::TypeSpecWithTemplate: {
4451 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4453 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4454 // break it apart into its prefix and identifier, then reconsititute those
4455 // as the canonical nested-name-specifier. This is required to canonicalize
4456 // a dependent nested-name-specifier involving typedefs of dependent-name
4458 // typedef typename T::type T1;
4459 // typedef typename T1::type T2;
4460 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4461 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4462 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4464 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4465 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4467 return NestedNameSpecifier::Create(*this, nullptr, false,
4468 const_cast<Type *>(T.getTypePtr()));
4471 case NestedNameSpecifier::Global:
4472 case NestedNameSpecifier::Super:
4473 // The global specifier and __super specifer are canonical and unique.
4477 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4480 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4481 // Handle the non-qualified case efficiently.
4482 if (!T.hasLocalQualifiers()) {
4483 // Handle the common positive case fast.
4484 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4488 // Handle the common negative case fast.
4489 if (!isa<ArrayType>(T.getCanonicalType()))
4492 // Apply any qualifiers from the array type to the element type. This
4493 // implements C99 6.7.3p8: "If the specification of an array type includes
4494 // any type qualifiers, the element type is so qualified, not the array type."
4496 // If we get here, we either have type qualifiers on the type, or we have
4497 // sugar such as a typedef in the way. If we have type qualifiers on the type
4498 // we must propagate them down into the element type.
4500 SplitQualType split = T.getSplitDesugaredType();
4501 Qualifiers qs = split.Quals;
4503 // If we have a simple case, just return now.
4504 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4505 if (!ATy || qs.empty())
4508 // Otherwise, we have an array and we have qualifiers on it. Push the
4509 // qualifiers into the array element type and return a new array type.
4510 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4512 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4513 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4514 CAT->getSizeModifier(),
4515 CAT->getIndexTypeCVRQualifiers()));
4516 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4517 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4518 IAT->getSizeModifier(),
4519 IAT->getIndexTypeCVRQualifiers()));
4521 if (const DependentSizedArrayType *DSAT
4522 = dyn_cast<DependentSizedArrayType>(ATy))
4523 return cast<ArrayType>(
4524 getDependentSizedArrayType(NewEltTy,
4525 DSAT->getSizeExpr(),
4526 DSAT->getSizeModifier(),
4527 DSAT->getIndexTypeCVRQualifiers(),
4528 DSAT->getBracketsRange()));
4530 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4531 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4533 VAT->getSizeModifier(),
4534 VAT->getIndexTypeCVRQualifiers(),
4535 VAT->getBracketsRange()));
4538 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4539 if (T->isArrayType() || T->isFunctionType())
4540 return getDecayedType(T);
4544 QualType ASTContext::getSignatureParameterType(QualType T) const {
4545 T = getVariableArrayDecayedType(T);
4546 T = getAdjustedParameterType(T);
4547 return T.getUnqualifiedType();
4550 QualType ASTContext::getExceptionObjectType(QualType T) const {
4551 // C++ [except.throw]p3:
4552 // A throw-expression initializes a temporary object, called the exception
4553 // object, the type of which is determined by removing any top-level
4554 // cv-qualifiers from the static type of the operand of throw and adjusting
4555 // the type from "array of T" or "function returning T" to "pointer to T"
4556 // or "pointer to function returning T", [...]
4557 T = getVariableArrayDecayedType(T);
4558 if (T->isArrayType() || T->isFunctionType())
4559 T = getDecayedType(T);
4560 return T.getUnqualifiedType();
4563 /// getArrayDecayedType - Return the properly qualified result of decaying the
4564 /// specified array type to a pointer. This operation is non-trivial when
4565 /// handling typedefs etc. The canonical type of "T" must be an array type,
4566 /// this returns a pointer to a properly qualified element of the array.
4568 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4569 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4570 // Get the element type with 'getAsArrayType' so that we don't lose any
4571 // typedefs in the element type of the array. This also handles propagation
4572 // of type qualifiers from the array type into the element type if present
4574 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4575 assert(PrettyArrayType && "Not an array type!");
4577 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4579 // int x[restrict 4] -> int *restrict
4580 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
4583 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4584 return getBaseElementType(array->getElementType());
4587 QualType ASTContext::getBaseElementType(QualType type) const {
4590 SplitQualType split = type.getSplitDesugaredType();
4591 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4594 type = array->getElementType();
4595 qs.addConsistentQualifiers(split.Quals);
4598 return getQualifiedType(type, qs);
4601 /// getConstantArrayElementCount - Returns number of constant array elements.
4603 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4604 uint64_t ElementCount = 1;
4606 ElementCount *= CA->getSize().getZExtValue();
4607 CA = dyn_cast_or_null<ConstantArrayType>(
4608 CA->getElementType()->getAsArrayTypeUnsafe());
4610 return ElementCount;
4613 /// getFloatingRank - Return a relative rank for floating point types.
4614 /// This routine will assert if passed a built-in type that isn't a float.
4615 static FloatingRank getFloatingRank(QualType T) {
4616 if (const ComplexType *CT = T->getAs<ComplexType>())
4617 return getFloatingRank(CT->getElementType());
4619 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4620 switch (T->getAs<BuiltinType>()->getKind()) {
4621 default: llvm_unreachable("getFloatingRank(): not a floating type");
4622 case BuiltinType::Half: return HalfRank;
4623 case BuiltinType::Float: return FloatRank;
4624 case BuiltinType::Double: return DoubleRank;
4625 case BuiltinType::LongDouble: return LongDoubleRank;
4629 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4630 /// point or a complex type (based on typeDomain/typeSize).
4631 /// 'typeDomain' is a real floating point or complex type.
4632 /// 'typeSize' is a real floating point or complex type.
4633 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4634 QualType Domain) const {
4635 FloatingRank EltRank = getFloatingRank(Size);
4636 if (Domain->isComplexType()) {
4638 case HalfRank: llvm_unreachable("Complex half is not supported");
4639 case FloatRank: return FloatComplexTy;
4640 case DoubleRank: return DoubleComplexTy;
4641 case LongDoubleRank: return LongDoubleComplexTy;
4645 assert(Domain->isRealFloatingType() && "Unknown domain!");
4647 case HalfRank: return HalfTy;
4648 case FloatRank: return FloatTy;
4649 case DoubleRank: return DoubleTy;
4650 case LongDoubleRank: return LongDoubleTy;
4652 llvm_unreachable("getFloatingRank(): illegal value for rank");
4655 /// getFloatingTypeOrder - Compare the rank of the two specified floating
4656 /// point types, ignoring the domain of the type (i.e. 'double' ==
4657 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
4658 /// LHS < RHS, return -1.
4659 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
4660 FloatingRank LHSR = getFloatingRank(LHS);
4661 FloatingRank RHSR = getFloatingRank(RHS);
4670 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4671 /// routine will assert if passed a built-in type that isn't an integer or enum,
4672 /// or if it is not canonicalized.
4673 unsigned ASTContext::getIntegerRank(const Type *T) const {
4674 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
4676 switch (cast<BuiltinType>(T)->getKind()) {
4677 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
4678 case BuiltinType::Bool:
4679 return 1 + (getIntWidth(BoolTy) << 3);
4680 case BuiltinType::Char_S:
4681 case BuiltinType::Char_U:
4682 case BuiltinType::SChar:
4683 case BuiltinType::UChar:
4684 return 2 + (getIntWidth(CharTy) << 3);
4685 case BuiltinType::Short:
4686 case BuiltinType::UShort:
4687 return 3 + (getIntWidth(ShortTy) << 3);
4688 case BuiltinType::Int:
4689 case BuiltinType::UInt:
4690 return 4 + (getIntWidth(IntTy) << 3);
4691 case BuiltinType::Long:
4692 case BuiltinType::ULong:
4693 return 5 + (getIntWidth(LongTy) << 3);
4694 case BuiltinType::LongLong:
4695 case BuiltinType::ULongLong:
4696 return 6 + (getIntWidth(LongLongTy) << 3);
4697 case BuiltinType::Int128:
4698 case BuiltinType::UInt128:
4699 return 7 + (getIntWidth(Int128Ty) << 3);
4703 /// \brief Whether this is a promotable bitfield reference according
4704 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4706 /// \returns the type this bit-field will promote to, or NULL if no
4707 /// promotion occurs.
4708 QualType ASTContext::isPromotableBitField(Expr *E) const {
4709 if (E->isTypeDependent() || E->isValueDependent())
4712 // FIXME: We should not do this unless E->refersToBitField() is true. This
4713 // matters in C where getSourceBitField() will find bit-fields for various
4714 // cases where the source expression is not a bit-field designator.
4716 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
4720 QualType FT = Field->getType();
4722 uint64_t BitWidth = Field->getBitWidthValue(*this);
4723 uint64_t IntSize = getTypeSize(IntTy);
4724 // C++ [conv.prom]p5:
4725 // A prvalue for an integral bit-field can be converted to a prvalue of type
4726 // int if int can represent all the values of the bit-field; otherwise, it
4727 // can be converted to unsigned int if unsigned int can represent all the
4728 // values of the bit-field. If the bit-field is larger yet, no integral
4729 // promotion applies to it.
4731 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4732 // If an int can represent all values of the original type (as restricted by
4733 // the width, for a bit-field), the value is converted to an int; otherwise,
4734 // it is converted to an unsigned int.
4736 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4737 // We perform that promotion here to match GCC and C++.
4738 if (BitWidth < IntSize)
4741 if (BitWidth == IntSize)
4742 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4744 // Types bigger than int are not subject to promotions, and therefore act
4745 // like the base type. GCC has some weird bugs in this area that we
4746 // deliberately do not follow (GCC follows a pre-standard resolution to
4747 // C's DR315 which treats bit-width as being part of the type, and this leaks
4748 // into their semantics in some cases).
4752 /// getPromotedIntegerType - Returns the type that Promotable will
4753 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4755 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
4756 assert(!Promotable.isNull());
4757 assert(Promotable->isPromotableIntegerType());
4758 if (const EnumType *ET = Promotable->getAs<EnumType>())
4759 return ET->getDecl()->getPromotionType();
4761 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4762 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4763 // (3.9.1) can be converted to a prvalue of the first of the following
4764 // types that can represent all the values of its underlying type:
4765 // int, unsigned int, long int, unsigned long int, long long int, or
4766 // unsigned long long int [...]
4767 // FIXME: Is there some better way to compute this?
4768 if (BT->getKind() == BuiltinType::WChar_S ||
4769 BT->getKind() == BuiltinType::WChar_U ||
4770 BT->getKind() == BuiltinType::Char16 ||
4771 BT->getKind() == BuiltinType::Char32) {
4772 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4773 uint64_t FromSize = getTypeSize(BT);
4774 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4775 LongLongTy, UnsignedLongLongTy };
4776 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4777 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4778 if (FromSize < ToSize ||
4779 (FromSize == ToSize &&
4780 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4781 return PromoteTypes[Idx];
4783 llvm_unreachable("char type should fit into long long");
4787 // At this point, we should have a signed or unsigned integer type.
4788 if (Promotable->isSignedIntegerType())
4790 uint64_t PromotableSize = getIntWidth(Promotable);
4791 uint64_t IntSize = getIntWidth(IntTy);
4792 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4793 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4796 /// \brief Recurses in pointer/array types until it finds an objc retainable
4797 /// type and returns its ownership.
4798 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4799 while (!T.isNull()) {
4800 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4801 return T.getObjCLifetime();
4802 if (T->isArrayType())
4803 T = getBaseElementType(T);
4804 else if (const PointerType *PT = T->getAs<PointerType>())
4805 T = PT->getPointeeType();
4806 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4807 T = RT->getPointeeType();
4812 return Qualifiers::OCL_None;
4815 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4816 // Incomplete enum types are not treated as integer types.
4817 // FIXME: In C++, enum types are never integer types.
4818 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4819 return ET->getDecl()->getIntegerType().getTypePtr();
4823 /// getIntegerTypeOrder - Returns the highest ranked integer type:
4824 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
4825 /// LHS < RHS, return -1.
4826 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
4827 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4828 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
4830 // Unwrap enums to their underlying type.
4831 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4832 LHSC = getIntegerTypeForEnum(ET);
4833 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4834 RHSC = getIntegerTypeForEnum(ET);
4836 if (LHSC == RHSC) return 0;
4838 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4839 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
4841 unsigned LHSRank = getIntegerRank(LHSC);
4842 unsigned RHSRank = getIntegerRank(RHSC);
4844 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4845 if (LHSRank == RHSRank) return 0;
4846 return LHSRank > RHSRank ? 1 : -1;
4849 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4851 // If the unsigned [LHS] type is larger, return it.
4852 if (LHSRank >= RHSRank)
4855 // If the signed type can represent all values of the unsigned type, it
4856 // wins. Because we are dealing with 2's complement and types that are
4857 // powers of two larger than each other, this is always safe.
4861 // If the unsigned [RHS] type is larger, return it.
4862 if (RHSRank >= LHSRank)
4865 // If the signed type can represent all values of the unsigned type, it
4866 // wins. Because we are dealing with 2's complement and types that are
4867 // powers of two larger than each other, this is always safe.
4871 // getCFConstantStringType - Return the type used for constant CFStrings.
4872 QualType ASTContext::getCFConstantStringType() const {
4873 if (!CFConstantStringTypeDecl) {
4874 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
4875 CFConstantStringTypeDecl->startDefinition();
4877 QualType FieldTypes[4];
4880 FieldTypes[0] = getPointerType(IntTy.withConst());
4882 FieldTypes[1] = IntTy;
4884 FieldTypes[2] = getPointerType(CharTy.withConst());
4886 FieldTypes[3] = LongTy;
4889 for (unsigned i = 0; i < 4; ++i) {
4890 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
4892 SourceLocation(), nullptr,
4893 FieldTypes[i], /*TInfo=*/nullptr,
4894 /*BitWidth=*/nullptr,
4897 Field->setAccess(AS_public);
4898 CFConstantStringTypeDecl->addDecl(Field);
4901 CFConstantStringTypeDecl->completeDefinition();
4904 return getTagDeclType(CFConstantStringTypeDecl);
4907 QualType ASTContext::getObjCSuperType() const {
4908 if (ObjCSuperType.isNull()) {
4909 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
4910 TUDecl->addDecl(ObjCSuperTypeDecl);
4911 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4913 return ObjCSuperType;
4916 void ASTContext::setCFConstantStringType(QualType T) {
4917 const RecordType *Rec = T->getAs<RecordType>();
4918 assert(Rec && "Invalid CFConstantStringType");
4919 CFConstantStringTypeDecl = Rec->getDecl();
4922 QualType ASTContext::getBlockDescriptorType() const {
4923 if (BlockDescriptorType)
4924 return getTagDeclType(BlockDescriptorType);
4927 // FIXME: Needs the FlagAppleBlock bit.
4928 RD = buildImplicitRecord("__block_descriptor");
4929 RD->startDefinition();
4931 QualType FieldTypes[] = {
4936 static const char *const FieldNames[] = {
4941 for (size_t i = 0; i < 2; ++i) {
4942 FieldDecl *Field = FieldDecl::Create(
4943 *this, RD, SourceLocation(), SourceLocation(),
4944 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4945 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
4946 Field->setAccess(AS_public);
4950 RD->completeDefinition();
4952 BlockDescriptorType = RD;
4954 return getTagDeclType(BlockDescriptorType);
4957 QualType ASTContext::getBlockDescriptorExtendedType() const {
4958 if (BlockDescriptorExtendedType)
4959 return getTagDeclType(BlockDescriptorExtendedType);
4962 // FIXME: Needs the FlagAppleBlock bit.
4963 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4964 RD->startDefinition();
4966 QualType FieldTypes[] = {
4969 getPointerType(VoidPtrTy),
4970 getPointerType(VoidPtrTy)
4973 static const char *const FieldNames[] = {
4980 for (size_t i = 0; i < 4; ++i) {
4981 FieldDecl *Field = FieldDecl::Create(
4982 *this, RD, SourceLocation(), SourceLocation(),
4983 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4984 /*BitWidth=*/nullptr,
4985 /*Mutable=*/false, ICIS_NoInit);
4986 Field->setAccess(AS_public);
4990 RD->completeDefinition();
4992 BlockDescriptorExtendedType = RD;
4993 return getTagDeclType(BlockDescriptorExtendedType);
4996 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4997 /// requires copy/dispose. Note that this must match the logic
4998 /// in buildByrefHelpers.
4999 bool ASTContext::BlockRequiresCopying(QualType Ty,
5001 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5002 const Expr *copyExpr = getBlockVarCopyInits(D);
5003 if (!copyExpr && record->hasTrivialDestructor()) return false;
5008 if (!Ty->isObjCRetainableType()) return false;
5010 Qualifiers qs = Ty.getQualifiers();
5012 // If we have lifetime, that dominates.
5013 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
5015 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5017 // These are just bits as far as the runtime is concerned.
5018 case Qualifiers::OCL_ExplicitNone:
5019 case Qualifiers::OCL_Autoreleasing:
5022 // Tell the runtime that this is ARC __weak, called by the
5024 case Qualifiers::OCL_Weak:
5025 // ARC __strong __block variables need to be retained.
5026 case Qualifiers::OCL_Strong:
5029 llvm_unreachable("fell out of lifetime switch!");
5031 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5032 Ty->isObjCObjectPointerType());
5035 bool ASTContext::getByrefLifetime(QualType Ty,
5036 Qualifiers::ObjCLifetime &LifeTime,
5037 bool &HasByrefExtendedLayout) const {
5039 if (!getLangOpts().ObjC1 ||
5040 getLangOpts().getGC() != LangOptions::NonGC)
5043 HasByrefExtendedLayout = false;
5044 if (Ty->isRecordType()) {
5045 HasByrefExtendedLayout = true;
5046 LifeTime = Qualifiers::OCL_None;
5047 } else if ((LifeTime = Ty.getObjCLifetime())) {
5048 // Honor the ARC qualifiers.
5049 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5051 LifeTime = Qualifiers::OCL_ExplicitNone;
5053 LifeTime = Qualifiers::OCL_None;
5058 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5059 if (!ObjCInstanceTypeDecl)
5060 ObjCInstanceTypeDecl =
5061 buildImplicitTypedef(getObjCIdType(), "instancetype");
5062 return ObjCInstanceTypeDecl;
5065 // This returns true if a type has been typedefed to BOOL:
5066 // typedef <type> BOOL;
5067 static bool isTypeTypedefedAsBOOL(QualType T) {
5068 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
5069 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5070 return II->isStr("BOOL");
5075 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
5077 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
5078 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5079 return CharUnits::Zero();
5081 CharUnits sz = getTypeSizeInChars(type);
5083 // Make all integer and enum types at least as large as an int
5084 if (sz.isPositive() && type->isIntegralOrEnumerationType())
5085 sz = std::max(sz, getTypeSizeInChars(IntTy));
5086 // Treat arrays as pointers, since that's how they're passed in.
5087 else if (type->isArrayType())
5088 sz = getTypeSizeInChars(VoidPtrTy);
5092 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
5093 return getTargetInfo().getCXXABI().isMicrosoft() &&
5094 VD->isStaticDataMember() &&
5095 VD->getType()->isIntegralOrEnumerationType() &&
5096 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
5100 std::string charUnitsToString(const CharUnits &CU) {
5101 return llvm::itostr(CU.getQuantity());
5104 /// getObjCEncodingForBlock - Return the encoded type for this block
5106 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5109 const BlockDecl *Decl = Expr->getBlockDecl();
5111 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5112 // Encode result type.
5113 if (getLangOpts().EncodeExtendedBlockSig)
5114 getObjCEncodingForMethodParameter(
5115 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5118 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
5119 // Compute size of all parameters.
5120 // Start with computing size of a pointer in number of bytes.
5121 // FIXME: There might(should) be a better way of doing this computation!
5123 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5124 CharUnits ParmOffset = PtrSize;
5125 for (auto PI : Decl->params()) {
5126 QualType PType = PI->getType();
5127 CharUnits sz = getObjCEncodingTypeSize(PType);
5130 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
5133 // Size of the argument frame
5134 S += charUnitsToString(ParmOffset);
5135 // Block pointer and offset.
5139 ParmOffset = PtrSize;
5140 for (auto PVDecl : Decl->params()) {
5141 QualType PType = PVDecl->getOriginalType();
5142 if (const ArrayType *AT =
5143 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5144 // Use array's original type only if it has known number of
5146 if (!isa<ConstantArrayType>(AT))
5147 PType = PVDecl->getType();
5148 } else if (PType->isFunctionType())
5149 PType = PVDecl->getType();
5150 if (getLangOpts().EncodeExtendedBlockSig)
5151 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5152 S, true /*Extended*/);
5154 getObjCEncodingForType(PType, S);
5155 S += charUnitsToString(ParmOffset);
5156 ParmOffset += getObjCEncodingTypeSize(PType);
5162 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
5164 // Encode result type.
5165 getObjCEncodingForType(Decl->getReturnType(), S);
5166 CharUnits ParmOffset;
5167 // Compute size of all parameters.
5168 for (auto PI : Decl->params()) {
5169 QualType PType = PI->getType();
5170 CharUnits sz = getObjCEncodingTypeSize(PType);
5174 assert (sz.isPositive() &&
5175 "getObjCEncodingForFunctionDecl - Incomplete param type");
5178 S += charUnitsToString(ParmOffset);
5179 ParmOffset = CharUnits::Zero();
5182 for (auto PVDecl : Decl->params()) {
5183 QualType PType = PVDecl->getOriginalType();
5184 if (const ArrayType *AT =
5185 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5186 // Use array's original type only if it has known number of
5188 if (!isa<ConstantArrayType>(AT))
5189 PType = PVDecl->getType();
5190 } else if (PType->isFunctionType())
5191 PType = PVDecl->getType();
5192 getObjCEncodingForType(PType, S);
5193 S += charUnitsToString(ParmOffset);
5194 ParmOffset += getObjCEncodingTypeSize(PType);
5200 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
5201 /// method parameter or return type. If Extended, include class names and
5202 /// block object types.
5203 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5204 QualType T, std::string& S,
5205 bool Extended) const {
5206 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5207 getObjCEncodingForTypeQualifier(QT, S);
5208 // Encode parameter type.
5209 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5210 true /*OutermostType*/,
5211 false /*EncodingProperty*/,
5212 false /*StructField*/,
5213 Extended /*EncodeBlockParameters*/,
5214 Extended /*EncodeClassNames*/);
5217 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
5219 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5221 bool Extended) const {
5222 // FIXME: This is not very efficient.
5223 // Encode return type.
5224 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5225 Decl->getReturnType(), S, Extended);
5226 // Compute size of all parameters.
5227 // Start with computing size of a pointer in number of bytes.
5228 // FIXME: There might(should) be a better way of doing this computation!
5230 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5231 // The first two arguments (self and _cmd) are pointers; account for
5233 CharUnits ParmOffset = 2 * PtrSize;
5234 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5235 E = Decl->sel_param_end(); PI != E; ++PI) {
5236 QualType PType = (*PI)->getType();
5237 CharUnits sz = getObjCEncodingTypeSize(PType);
5241 assert (sz.isPositive() &&
5242 "getObjCEncodingForMethodDecl - Incomplete param type");
5245 S += charUnitsToString(ParmOffset);
5247 S += charUnitsToString(PtrSize);
5250 ParmOffset = 2 * PtrSize;
5251 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5252 E = Decl->sel_param_end(); PI != E; ++PI) {
5253 const ParmVarDecl *PVDecl = *PI;
5254 QualType PType = PVDecl->getOriginalType();
5255 if (const ArrayType *AT =
5256 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5257 // Use array's original type only if it has known number of
5259 if (!isa<ConstantArrayType>(AT))
5260 PType = PVDecl->getType();
5261 } else if (PType->isFunctionType())
5262 PType = PVDecl->getType();
5263 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5264 PType, S, Extended);
5265 S += charUnitsToString(ParmOffset);
5266 ParmOffset += getObjCEncodingTypeSize(PType);
5272 ObjCPropertyImplDecl *
5273 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5274 const ObjCPropertyDecl *PD,
5275 const Decl *Container) const {
5278 if (const ObjCCategoryImplDecl *CID =
5279 dyn_cast<ObjCCategoryImplDecl>(Container)) {
5280 for (auto *PID : CID->property_impls())
5281 if (PID->getPropertyDecl() == PD)
5284 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5285 for (auto *PID : OID->property_impls())
5286 if (PID->getPropertyDecl() == PD)
5292 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
5293 /// property declaration. If non-NULL, Container must be either an
5294 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5295 /// NULL when getting encodings for protocol properties.
5296 /// Property attributes are stored as a comma-delimited C string. The simple
5297 /// attributes readonly and bycopy are encoded as single characters. The
5298 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
5299 /// encoded as single characters, followed by an identifier. Property types
5300 /// are also encoded as a parametrized attribute. The characters used to encode
5301 /// these attributes are defined by the following enumeration:
5303 /// enum PropertyAttributes {
5304 /// kPropertyReadOnly = 'R', // property is read-only.
5305 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5306 /// kPropertyByref = '&', // property is a reference to the value last assigned
5307 /// kPropertyDynamic = 'D', // property is dynamic
5308 /// kPropertyGetter = 'G', // followed by getter selector name
5309 /// kPropertySetter = 'S', // followed by setter selector name
5310 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
5311 /// kPropertyType = 'T' // followed by old-style type encoding.
5312 /// kPropertyWeak = 'W' // 'weak' property
5313 /// kPropertyStrong = 'P' // property GC'able
5314 /// kPropertyNonAtomic = 'N' // property non-atomic
5317 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5318 const Decl *Container,
5319 std::string& S) const {
5320 // Collect information from the property implementation decl(s).
5321 bool Dynamic = false;
5322 ObjCPropertyImplDecl *SynthesizePID = nullptr;
5324 if (ObjCPropertyImplDecl *PropertyImpDecl =
5325 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5326 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5329 SynthesizePID = PropertyImpDecl;
5332 // FIXME: This is not very efficient.
5335 // Encode result type.
5336 // GCC has some special rules regarding encoding of properties which
5337 // closely resembles encoding of ivars.
5338 getObjCEncodingForPropertyType(PD->getType(), S);
5340 if (PD->isReadOnly()) {
5342 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5344 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5346 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5349 switch (PD->getSetterKind()) {
5350 case ObjCPropertyDecl::Assign: break;
5351 case ObjCPropertyDecl::Copy: S += ",C"; break;
5352 case ObjCPropertyDecl::Retain: S += ",&"; break;
5353 case ObjCPropertyDecl::Weak: S += ",W"; break;
5357 // It really isn't clear at all what this means, since properties
5358 // are "dynamic by default".
5362 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5365 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5367 S += PD->getGetterName().getAsString();
5370 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5372 S += PD->getSetterName().getAsString();
5375 if (SynthesizePID) {
5376 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5378 S += OID->getNameAsString();
5381 // FIXME: OBJCGC: weak & strong
5384 /// getLegacyIntegralTypeEncoding -
5385 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5386 /// 'l' or 'L' , but not always. For typedefs, we need to use
5387 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5389 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5390 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5391 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5392 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5393 PointeeTy = UnsignedIntTy;
5395 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5401 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5402 const FieldDecl *Field,
5403 QualType *NotEncodedT) const {
5404 // We follow the behavior of gcc, expanding structures which are
5405 // directly pointed to, and expanding embedded structures. Note that
5406 // these rules are sufficient to prevent recursive encoding of the
5408 getObjCEncodingForTypeImpl(T, S, true, true, Field,
5409 true /* outermost type */, false, false,
5410 false, false, false, NotEncodedT);
5413 void ASTContext::getObjCEncodingForPropertyType(QualType T,
5414 std::string& S) const {
5415 // Encode result type.
5416 // GCC has some special rules regarding encoding of properties which
5417 // closely resembles encoding of ivars.
5418 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5419 true /* outermost type */,
5420 true /* encoding property */);
5423 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5424 BuiltinType::Kind kind) {
5426 case BuiltinType::Void: return 'v';
5427 case BuiltinType::Bool: return 'B';
5428 case BuiltinType::Char_U:
5429 case BuiltinType::UChar: return 'C';
5430 case BuiltinType::Char16:
5431 case BuiltinType::UShort: return 'S';
5432 case BuiltinType::Char32:
5433 case BuiltinType::UInt: return 'I';
5434 case BuiltinType::ULong:
5435 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5436 case BuiltinType::UInt128: return 'T';
5437 case BuiltinType::ULongLong: return 'Q';
5438 case BuiltinType::Char_S:
5439 case BuiltinType::SChar: return 'c';
5440 case BuiltinType::Short: return 's';
5441 case BuiltinType::WChar_S:
5442 case BuiltinType::WChar_U:
5443 case BuiltinType::Int: return 'i';
5444 case BuiltinType::Long:
5445 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5446 case BuiltinType::LongLong: return 'q';
5447 case BuiltinType::Int128: return 't';
5448 case BuiltinType::Float: return 'f';
5449 case BuiltinType::Double: return 'd';
5450 case BuiltinType::LongDouble: return 'D';
5451 case BuiltinType::NullPtr: return '*'; // like char*
5453 case BuiltinType::Half:
5454 // FIXME: potentially need @encodes for these!
5457 case BuiltinType::ObjCId:
5458 case BuiltinType::ObjCClass:
5459 case BuiltinType::ObjCSel:
5460 llvm_unreachable("@encoding ObjC primitive type");
5462 // OpenCL and placeholder types don't need @encodings.
5463 case BuiltinType::OCLImage1d:
5464 case BuiltinType::OCLImage1dArray:
5465 case BuiltinType::OCLImage1dBuffer:
5466 case BuiltinType::OCLImage2d:
5467 case BuiltinType::OCLImage2dArray:
5468 case BuiltinType::OCLImage2dDepth:
5469 case BuiltinType::OCLImage2dArrayDepth:
5470 case BuiltinType::OCLImage2dMSAA:
5471 case BuiltinType::OCLImage2dArrayMSAA:
5472 case BuiltinType::OCLImage2dMSAADepth:
5473 case BuiltinType::OCLImage2dArrayMSAADepth:
5474 case BuiltinType::OCLImage3d:
5475 case BuiltinType::OCLEvent:
5476 case BuiltinType::OCLClkEvent:
5477 case BuiltinType::OCLQueue:
5478 case BuiltinType::OCLNDRange:
5479 case BuiltinType::OCLReserveID:
5480 case BuiltinType::OCLSampler:
5481 case BuiltinType::Dependent:
5482 #define BUILTIN_TYPE(KIND, ID)
5483 #define PLACEHOLDER_TYPE(KIND, ID) \
5484 case BuiltinType::KIND:
5485 #include "clang/AST/BuiltinTypes.def"
5486 llvm_unreachable("invalid builtin type for @encode");
5488 llvm_unreachable("invalid BuiltinType::Kind value");
5491 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5492 EnumDecl *Enum = ET->getDecl();
5494 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5495 if (!Enum->isFixed())
5498 // The encoding of a fixed enum type matches its fixed underlying type.
5499 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5500 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5503 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5504 QualType T, const FieldDecl *FD) {
5505 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5507 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5508 // The GNU runtime requires more information; bitfields are encoded as b,
5509 // then the offset (in bits) of the first element, then the type of the
5510 // bitfield, then the size in bits. For example, in this structure:
5517 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5518 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5519 // information is not especially sensible, but we're stuck with it for
5520 // compatibility with GCC, although providing it breaks anything that
5521 // actually uses runtime introspection and wants to work on both runtimes...
5522 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5523 const RecordDecl *RD = FD->getParent();
5524 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5525 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5526 if (const EnumType *ET = T->getAs<EnumType>())
5527 S += ObjCEncodingForEnumType(Ctx, ET);
5529 const BuiltinType *BT = T->castAs<BuiltinType>();
5530 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5533 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5536 // FIXME: Use SmallString for accumulating string.
5537 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5538 bool ExpandPointedToStructures,
5539 bool ExpandStructures,
5540 const FieldDecl *FD,
5542 bool EncodingProperty,
5544 bool EncodeBlockParameters,
5545 bool EncodeClassNames,
5546 bool EncodePointerToObjCTypedef,
5547 QualType *NotEncodedT) const {
5548 CanQualType CT = getCanonicalType(T);
5549 switch (CT->getTypeClass()) {
5552 if (FD && FD->isBitField())
5553 return EncodeBitField(this, S, T, FD);
5554 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5555 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5557 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5560 case Type::Complex: {
5561 const ComplexType *CT = T->castAs<ComplexType>();
5563 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
5567 case Type::Atomic: {
5568 const AtomicType *AT = T->castAs<AtomicType>();
5570 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
5574 // encoding for pointer or reference types.
5576 case Type::LValueReference:
5577 case Type::RValueReference: {
5579 if (isa<PointerType>(CT)) {
5580 const PointerType *PT = T->castAs<PointerType>();
5581 if (PT->isObjCSelType()) {
5585 PointeeTy = PT->getPointeeType();
5587 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5590 bool isReadOnly = false;
5591 // For historical/compatibility reasons, the read-only qualifier of the
5592 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5593 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5594 // Also, do not emit the 'r' for anything but the outermost type!
5595 if (isa<TypedefType>(T.getTypePtr())) {
5596 if (OutermostType && T.isConstQualified()) {
5600 } else if (OutermostType) {
5601 QualType P = PointeeTy;
5602 while (P->getAs<PointerType>())
5603 P = P->getAs<PointerType>()->getPointeeType();
5604 if (P.isConstQualified()) {
5610 // Another legacy compatibility encoding. Some ObjC qualifier and type
5611 // combinations need to be rearranged.
5612 // Rewrite "in const" from "nr" to "rn"
5613 if (StringRef(S).endswith("nr"))
5614 S.replace(S.end()-2, S.end(), "rn");
5617 if (PointeeTy->isCharType()) {
5618 // char pointer types should be encoded as '*' unless it is a
5619 // type that has been typedef'd to 'BOOL'.
5620 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5624 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5625 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5626 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5630 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5631 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5638 getLegacyIntegralTypeEncoding(PointeeTy);
5640 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5641 nullptr, false, false, false, false, false, false,
5646 case Type::ConstantArray:
5647 case Type::IncompleteArray:
5648 case Type::VariableArray: {
5649 const ArrayType *AT = cast<ArrayType>(CT);
5651 if (isa<IncompleteArrayType>(AT) && !StructField) {
5652 // Incomplete arrays are encoded as a pointer to the array element.
5655 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5656 false, ExpandStructures, FD);
5660 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5661 S += llvm::utostr(CAT->getSize().getZExtValue());
5663 //Variable length arrays are encoded as a regular array with 0 elements.
5664 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5665 "Unknown array type!");
5669 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5670 false, ExpandStructures, FD,
5671 false, false, false, false, false, false,
5678 case Type::FunctionNoProto:
5679 case Type::FunctionProto:
5683 case Type::Record: {
5684 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5685 S += RDecl->isUnion() ? '(' : '{';
5686 // Anonymous structures print as '?'
5687 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5689 if (ClassTemplateSpecializationDecl *Spec
5690 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5691 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5692 llvm::raw_string_ostream OS(S);
5693 TemplateSpecializationType::PrintTemplateArgumentList(OS,
5694 TemplateArgs.data(),
5695 TemplateArgs.size(),
5696 (*this).getPrintingPolicy());
5701 if (ExpandStructures) {
5703 if (!RDecl->isUnion()) {
5704 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
5706 for (const auto *Field : RDecl->fields()) {
5709 S += Field->getNameAsString();
5713 // Special case bit-fields.
5714 if (Field->isBitField()) {
5715 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5718 QualType qt = Field->getType();
5719 getLegacyIntegralTypeEncoding(qt);
5720 getObjCEncodingForTypeImpl(qt, S, false, true,
5721 FD, /*OutermostType*/false,
5722 /*EncodingProperty*/false,
5723 /*StructField*/true,
5724 false, false, false, NotEncodedT);
5729 S += RDecl->isUnion() ? ')' : '}';
5733 case Type::BlockPointer: {
5734 const BlockPointerType *BT = T->castAs<BlockPointerType>();
5735 S += "@?"; // Unlike a pointer-to-function, which is "^?".
5736 if (EncodeBlockParameters) {
5737 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5740 // Block return type
5741 getObjCEncodingForTypeImpl(
5742 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5743 FD, false /* OutermostType */, EncodingProperty,
5744 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5749 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5750 for (const auto &I : FPT->param_types())
5751 getObjCEncodingForTypeImpl(
5752 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5753 false /* OutermostType */, EncodingProperty,
5754 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5755 false, NotEncodedT);
5762 case Type::ObjCObject: {
5763 // hack to match legacy encoding of *id and *Class
5764 QualType Ty = getObjCObjectPointerType(CT);
5765 if (Ty->isObjCIdType()) {
5766 S += "{objc_object=}";
5769 else if (Ty->isObjCClassType()) {
5770 S += "{objc_class=}";
5775 case Type::ObjCInterface: {
5776 // Ignore protocol qualifiers when mangling at this level.
5777 // @encode(class_name)
5778 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
5780 S += OI->getObjCRuntimeNameAsString();
5782 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5783 DeepCollectObjCIvars(OI, true, Ivars);
5784 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5785 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5786 if (Field->isBitField())
5787 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5789 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5790 false, false, false, false, false,
5791 EncodePointerToObjCTypedef,
5798 case Type::ObjCObjectPointer: {
5799 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5800 if (OPT->isObjCIdType()) {
5805 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5806 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5807 // Since this is a binary compatibility issue, need to consult with runtime
5808 // folks. Fortunately, this is a *very* obsure construct.
5813 if (OPT->isObjCQualifiedIdType()) {
5814 getObjCEncodingForTypeImpl(getObjCIdType(), S,
5815 ExpandPointedToStructures,
5816 ExpandStructures, FD);
5817 if (FD || EncodingProperty || EncodeClassNames) {
5818 // Note that we do extended encoding of protocol qualifer list
5819 // Only when doing ivar or property encoding.
5821 for (const auto *I : OPT->quals()) {
5823 S += I->getObjCRuntimeNameAsString();
5831 QualType PointeeTy = OPT->getPointeeType();
5832 if (!EncodingProperty &&
5833 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5834 !EncodePointerToObjCTypedef) {
5835 // Another historical/compatibility reason.
5836 // We encode the underlying type which comes out as
5839 if (FD && OPT->getInterfaceDecl()) {
5840 // Prevent recursive encoding of fields in some rare cases.
5841 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5842 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5843 DeepCollectObjCIvars(OI, true, Ivars);
5844 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5845 if (cast<FieldDecl>(Ivars[i]) == FD) {
5847 S += OI->getObjCRuntimeNameAsString();
5853 getObjCEncodingForTypeImpl(PointeeTy, S,
5854 false, ExpandPointedToStructures,
5856 false, false, false, false, false,
5857 /*EncodePointerToObjCTypedef*/true);
5862 if (OPT->getInterfaceDecl() &&
5863 (FD || EncodingProperty || EncodeClassNames)) {
5865 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
5866 for (const auto *I : OPT->quals()) {
5868 S += I->getObjCRuntimeNameAsString();
5876 // gcc just blithely ignores member pointers.
5877 // FIXME: we shoul do better than that. 'M' is available.
5878 case Type::MemberPointer:
5879 // This matches gcc's encoding, even though technically it is insufficient.
5880 //FIXME. We should do a better job than gcc.
5882 case Type::ExtVector:
5883 // Until we have a coherent encoding of these three types, issue warning.
5889 // We could see an undeduced auto type here during error recovery.
5895 #define ABSTRACT_TYPE(KIND, BASE)
5896 #define TYPE(KIND, BASE)
5897 #define DEPENDENT_TYPE(KIND, BASE) \
5899 #define NON_CANONICAL_TYPE(KIND, BASE) \
5901 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5903 #include "clang/AST/TypeNodes.def"
5904 llvm_unreachable("@encode for dependent type!");
5906 llvm_unreachable("bad type kind!");
5909 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5911 const FieldDecl *FD,
5913 QualType *NotEncodedT) const {
5914 assert(RDecl && "Expected non-null RecordDecl");
5915 assert(!RDecl->isUnion() && "Should not be called for unions");
5916 if (!RDecl->getDefinition())
5919 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5920 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5921 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5924 for (const auto &BI : CXXRec->bases()) {
5925 if (!BI.isVirtual()) {
5926 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5927 if (base->isEmpty())
5929 uint64_t offs = toBits(layout.getBaseClassOffset(base));
5930 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5931 std::make_pair(offs, base));
5937 for (auto *Field : RDecl->fields()) {
5938 uint64_t offs = layout.getFieldOffset(i);
5939 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5940 std::make_pair(offs, Field));
5944 if (CXXRec && includeVBases) {
5945 for (const auto &BI : CXXRec->vbases()) {
5946 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5947 if (base->isEmpty())
5949 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
5950 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5951 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5952 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5953 std::make_pair(offs, base));
5959 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5961 size = layout.getSize();
5965 uint64_t CurOffs = 0;
5967 std::multimap<uint64_t, NamedDecl *>::iterator
5968 CurLayObj = FieldOrBaseOffsets.begin();
5970 if (CXXRec && CXXRec->isDynamicClass() &&
5971 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
5974 std::string recname = CXXRec->getNameAsString();
5975 if (recname.empty()) recname = "?";
5981 CurOffs += getTypeSize(VoidPtrTy);
5985 if (!RDecl->hasFlexibleArrayMember()) {
5986 // Mark the end of the structure.
5987 uint64_t offs = toBits(size);
5988 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5989 std::make_pair(offs, nullptr));
5992 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5994 assert(CurOffs <= CurLayObj->first);
5995 if (CurOffs < CurLayObj->first) {
5996 uint64_t padding = CurLayObj->first - CurOffs;
5997 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5998 // packing/alignment of members is different that normal, in which case
5999 // the encoding will be out-of-sync with the real layout.
6000 // If the runtime switches to just consider the size of types without
6001 // taking into account alignment, we could make padding explicit in the
6002 // encoding (e.g. using arrays of chars). The encoding strings would be
6003 // longer then though.
6008 NamedDecl *dcl = CurLayObj->second;
6010 break; // reached end of structure.
6012 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6013 // We expand the bases without their virtual bases since those are going
6014 // in the initial structure. Note that this differs from gcc which
6015 // expands virtual bases each time one is encountered in the hierarchy,
6016 // making the encoding type bigger than it really is.
6017 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6019 assert(!base->isEmpty());
6021 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
6024 FieldDecl *field = cast<FieldDecl>(dcl);
6027 S += field->getNameAsString();
6031 if (field->isBitField()) {
6032 EncodeBitField(this, S, field->getType(), field);
6034 CurOffs += field->getBitWidthValue(*this);
6037 QualType qt = field->getType();
6038 getLegacyIntegralTypeEncoding(qt);
6039 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6040 /*OutermostType*/false,
6041 /*EncodingProperty*/false,
6042 /*StructField*/true,
6043 false, false, false, NotEncodedT);
6045 CurOffs += getTypeSize(field->getType());
6052 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
6053 std::string& S) const {
6054 if (QT & Decl::OBJC_TQ_In)
6056 if (QT & Decl::OBJC_TQ_Inout)
6058 if (QT & Decl::OBJC_TQ_Out)
6060 if (QT & Decl::OBJC_TQ_Bycopy)
6062 if (QT & Decl::OBJC_TQ_Byref)
6064 if (QT & Decl::OBJC_TQ_Oneway)
6068 TypedefDecl *ASTContext::getObjCIdDecl() const {
6070 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
6071 T = getObjCObjectPointerType(T);
6072 ObjCIdDecl = buildImplicitTypedef(T, "id");
6077 TypedefDecl *ASTContext::getObjCSelDecl() const {
6079 QualType T = getPointerType(ObjCBuiltinSelTy);
6080 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
6085 TypedefDecl *ASTContext::getObjCClassDecl() const {
6086 if (!ObjCClassDecl) {
6087 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
6088 T = getObjCObjectPointerType(T);
6089 ObjCClassDecl = buildImplicitTypedef(T, "Class");
6091 return ObjCClassDecl;
6094 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6095 if (!ObjCProtocolClassDecl) {
6096 ObjCProtocolClassDecl
6097 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6099 &Idents.get("Protocol"),
6100 /*typeParamList=*/nullptr,
6101 /*PrevDecl=*/nullptr,
6102 SourceLocation(), true);
6105 return ObjCProtocolClassDecl;
6108 //===----------------------------------------------------------------------===//
6109 // __builtin_va_list Construction Functions
6110 //===----------------------------------------------------------------------===//
6112 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6114 // typedef char* __builtin[_ms]_va_list;
6115 QualType T = Context->getPointerType(Context->CharTy);
6116 return Context->buildImplicitTypedef(T, Name);
6119 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6120 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6123 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6124 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
6127 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6128 // typedef void* __builtin_va_list;
6129 QualType T = Context->getPointerType(Context->VoidTy);
6130 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6133 static TypedefDecl *
6134 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
6136 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
6137 if (Context->getLangOpts().CPlusPlus) {
6138 // namespace std { struct __va_list {
6140 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6141 Context->getTranslationUnitDecl(),
6142 /*Inline*/ false, SourceLocation(),
6143 SourceLocation(), &Context->Idents.get("std"),
6144 /*PrevDecl*/ nullptr);
6146 VaListTagDecl->setDeclContext(NS);
6149 VaListTagDecl->startDefinition();
6151 const size_t NumFields = 5;
6152 QualType FieldTypes[NumFields];
6153 const char *FieldNames[NumFields];
6156 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6157 FieldNames[0] = "__stack";
6160 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6161 FieldNames[1] = "__gr_top";
6164 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6165 FieldNames[2] = "__vr_top";
6168 FieldTypes[3] = Context->IntTy;
6169 FieldNames[3] = "__gr_offs";
6172 FieldTypes[4] = Context->IntTy;
6173 FieldNames[4] = "__vr_offs";
6176 for (unsigned i = 0; i < NumFields; ++i) {
6177 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6181 &Context->Idents.get(FieldNames[i]),
6182 FieldTypes[i], /*TInfo=*/nullptr,
6183 /*BitWidth=*/nullptr,
6186 Field->setAccess(AS_public);
6187 VaListTagDecl->addDecl(Field);
6189 VaListTagDecl->completeDefinition();
6190 Context->VaListTagDecl = VaListTagDecl;
6191 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6193 // } __builtin_va_list;
6194 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
6197 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6198 // typedef struct __va_list_tag {
6199 RecordDecl *VaListTagDecl;
6201 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6202 VaListTagDecl->startDefinition();
6204 const size_t NumFields = 5;
6205 QualType FieldTypes[NumFields];
6206 const char *FieldNames[NumFields];
6208 // unsigned char gpr;
6209 FieldTypes[0] = Context->UnsignedCharTy;
6210 FieldNames[0] = "gpr";
6212 // unsigned char fpr;
6213 FieldTypes[1] = Context->UnsignedCharTy;
6214 FieldNames[1] = "fpr";
6216 // unsigned short reserved;
6217 FieldTypes[2] = Context->UnsignedShortTy;
6218 FieldNames[2] = "reserved";
6220 // void* overflow_arg_area;
6221 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6222 FieldNames[3] = "overflow_arg_area";
6224 // void* reg_save_area;
6225 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6226 FieldNames[4] = "reg_save_area";
6229 for (unsigned i = 0; i < NumFields; ++i) {
6230 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6233 &Context->Idents.get(FieldNames[i]),
6234 FieldTypes[i], /*TInfo=*/nullptr,
6235 /*BitWidth=*/nullptr,
6238 Field->setAccess(AS_public);
6239 VaListTagDecl->addDecl(Field);
6241 VaListTagDecl->completeDefinition();
6242 Context->VaListTagDecl = VaListTagDecl;
6243 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6246 TypedefDecl *VaListTagTypedefDecl =
6247 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6249 QualType VaListTagTypedefType =
6250 Context->getTypedefType(VaListTagTypedefDecl);
6252 // typedef __va_list_tag __builtin_va_list[1];
6253 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6254 QualType VaListTagArrayType
6255 = Context->getConstantArrayType(VaListTagTypedefType,
6256 Size, ArrayType::Normal, 0);
6257 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6260 static TypedefDecl *
6261 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6262 // struct __va_list_tag {
6263 RecordDecl *VaListTagDecl;
6264 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6265 VaListTagDecl->startDefinition();
6267 const size_t NumFields = 4;
6268 QualType FieldTypes[NumFields];
6269 const char *FieldNames[NumFields];
6271 // unsigned gp_offset;
6272 FieldTypes[0] = Context->UnsignedIntTy;
6273 FieldNames[0] = "gp_offset";
6275 // unsigned fp_offset;
6276 FieldTypes[1] = Context->UnsignedIntTy;
6277 FieldNames[1] = "fp_offset";
6279 // void* overflow_arg_area;
6280 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6281 FieldNames[2] = "overflow_arg_area";
6283 // void* reg_save_area;
6284 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6285 FieldNames[3] = "reg_save_area";
6288 for (unsigned i = 0; i < NumFields; ++i) {
6289 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6293 &Context->Idents.get(FieldNames[i]),
6294 FieldTypes[i], /*TInfo=*/nullptr,
6295 /*BitWidth=*/nullptr,
6298 Field->setAccess(AS_public);
6299 VaListTagDecl->addDecl(Field);
6301 VaListTagDecl->completeDefinition();
6302 Context->VaListTagDecl = VaListTagDecl;
6303 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6307 // typedef struct __va_list_tag __builtin_va_list[1];
6308 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6309 QualType VaListTagArrayType =
6310 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6311 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6314 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6315 // typedef int __builtin_va_list[4];
6316 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6317 QualType IntArrayType
6318 = Context->getConstantArrayType(Context->IntTy,
6319 Size, ArrayType::Normal, 0);
6320 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6323 static TypedefDecl *
6324 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6326 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6327 if (Context->getLangOpts().CPlusPlus) {
6328 // namespace std { struct __va_list {
6330 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6331 Context->getTranslationUnitDecl(),
6332 /*Inline*/false, SourceLocation(),
6333 SourceLocation(), &Context->Idents.get("std"),
6334 /*PrevDecl*/ nullptr);
6336 VaListDecl->setDeclContext(NS);
6339 VaListDecl->startDefinition();
6342 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6346 &Context->Idents.get("__ap"),
6347 Context->getPointerType(Context->VoidTy),
6349 /*BitWidth=*/nullptr,
6352 Field->setAccess(AS_public);
6353 VaListDecl->addDecl(Field);
6356 VaListDecl->completeDefinition();
6358 // typedef struct __va_list __builtin_va_list;
6359 QualType T = Context->getRecordType(VaListDecl);
6360 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6363 static TypedefDecl *
6364 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6365 // struct __va_list_tag {
6366 RecordDecl *VaListTagDecl;
6367 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6368 VaListTagDecl->startDefinition();
6370 const size_t NumFields = 4;
6371 QualType FieldTypes[NumFields];
6372 const char *FieldNames[NumFields];
6375 FieldTypes[0] = Context->LongTy;
6376 FieldNames[0] = "__gpr";
6379 FieldTypes[1] = Context->LongTy;
6380 FieldNames[1] = "__fpr";
6382 // void *__overflow_arg_area;
6383 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6384 FieldNames[2] = "__overflow_arg_area";
6386 // void *__reg_save_area;
6387 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6388 FieldNames[3] = "__reg_save_area";
6391 for (unsigned i = 0; i < NumFields; ++i) {
6392 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6396 &Context->Idents.get(FieldNames[i]),
6397 FieldTypes[i], /*TInfo=*/nullptr,
6398 /*BitWidth=*/nullptr,
6401 Field->setAccess(AS_public);
6402 VaListTagDecl->addDecl(Field);
6404 VaListTagDecl->completeDefinition();
6405 Context->VaListTagDecl = VaListTagDecl;
6406 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6410 // typedef __va_list_tag __builtin_va_list[1];
6411 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6412 QualType VaListTagArrayType =
6413 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6415 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6418 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6419 TargetInfo::BuiltinVaListKind Kind) {
6421 case TargetInfo::CharPtrBuiltinVaList:
6422 return CreateCharPtrBuiltinVaListDecl(Context);
6423 case TargetInfo::VoidPtrBuiltinVaList:
6424 return CreateVoidPtrBuiltinVaListDecl(Context);
6425 case TargetInfo::AArch64ABIBuiltinVaList:
6426 return CreateAArch64ABIBuiltinVaListDecl(Context);
6427 case TargetInfo::PowerABIBuiltinVaList:
6428 return CreatePowerABIBuiltinVaListDecl(Context);
6429 case TargetInfo::X86_64ABIBuiltinVaList:
6430 return CreateX86_64ABIBuiltinVaListDecl(Context);
6431 case TargetInfo::PNaClABIBuiltinVaList:
6432 return CreatePNaClABIBuiltinVaListDecl(Context);
6433 case TargetInfo::AAPCSABIBuiltinVaList:
6434 return CreateAAPCSABIBuiltinVaListDecl(Context);
6435 case TargetInfo::SystemZBuiltinVaList:
6436 return CreateSystemZBuiltinVaListDecl(Context);
6439 llvm_unreachable("Unhandled __builtin_va_list type kind");
6442 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6443 if (!BuiltinVaListDecl) {
6444 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6445 assert(BuiltinVaListDecl->isImplicit());
6448 return BuiltinVaListDecl;
6451 Decl *ASTContext::getVaListTagDecl() const {
6452 // Force the creation of VaListTagDecl by building the __builtin_va_list
6455 (void)getBuiltinVaListDecl();
6457 return VaListTagDecl;
6460 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6461 if (!BuiltinMSVaListDecl)
6462 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6464 return BuiltinMSVaListDecl;
6467 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6468 assert(ObjCConstantStringType.isNull() &&
6469 "'NSConstantString' type already set!");
6471 ObjCConstantStringType = getObjCInterfaceType(Decl);
6474 /// \brief Retrieve the template name that corresponds to a non-empty
6477 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6478 UnresolvedSetIterator End) const {
6479 unsigned size = End - Begin;
6480 assert(size > 1 && "set is not overloaded!");
6482 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6483 size * sizeof(FunctionTemplateDecl*));
6484 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6486 NamedDecl **Storage = OT->getStorage();
6487 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6489 assert(isa<FunctionTemplateDecl>(D) ||
6490 (isa<UsingShadowDecl>(D) &&
6491 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6495 return TemplateName(OT);
6498 /// \brief Retrieve the template name that represents a qualified
6499 /// template name such as \c std::vector.
6501 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6502 bool TemplateKeyword,
6503 TemplateDecl *Template) const {
6504 assert(NNS && "Missing nested-name-specifier in qualified template name");
6506 // FIXME: Canonicalization?
6507 llvm::FoldingSetNodeID ID;
6508 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6510 void *InsertPos = nullptr;
6511 QualifiedTemplateName *QTN =
6512 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6514 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6515 QualifiedTemplateName(NNS, TemplateKeyword, Template);
6516 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6519 return TemplateName(QTN);
6522 /// \brief Retrieve the template name that represents a dependent
6523 /// template name such as \c MetaFun::template apply.
6525 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6526 const IdentifierInfo *Name) const {
6527 assert((!NNS || NNS->isDependent()) &&
6528 "Nested name specifier must be dependent");
6530 llvm::FoldingSetNodeID ID;
6531 DependentTemplateName::Profile(ID, NNS, Name);
6533 void *InsertPos = nullptr;
6534 DependentTemplateName *QTN =
6535 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6538 return TemplateName(QTN);
6540 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6541 if (CanonNNS == NNS) {
6542 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6543 DependentTemplateName(NNS, Name);
6545 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6546 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6547 DependentTemplateName(NNS, Name, Canon);
6548 DependentTemplateName *CheckQTN =
6549 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6550 assert(!CheckQTN && "Dependent type name canonicalization broken");
6554 DependentTemplateNames.InsertNode(QTN, InsertPos);
6555 return TemplateName(QTN);
6558 /// \brief Retrieve the template name that represents a dependent
6559 /// template name such as \c MetaFun::template operator+.
6561 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6562 OverloadedOperatorKind Operator) const {
6563 assert((!NNS || NNS->isDependent()) &&
6564 "Nested name specifier must be dependent");
6566 llvm::FoldingSetNodeID ID;
6567 DependentTemplateName::Profile(ID, NNS, Operator);
6569 void *InsertPos = nullptr;
6570 DependentTemplateName *QTN
6571 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6574 return TemplateName(QTN);
6576 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6577 if (CanonNNS == NNS) {
6578 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6579 DependentTemplateName(NNS, Operator);
6581 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6582 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6583 DependentTemplateName(NNS, Operator, Canon);
6585 DependentTemplateName *CheckQTN
6586 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6587 assert(!CheckQTN && "Dependent template name canonicalization broken");
6591 DependentTemplateNames.InsertNode(QTN, InsertPos);
6592 return TemplateName(QTN);
6596 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6597 TemplateName replacement) const {
6598 llvm::FoldingSetNodeID ID;
6599 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6601 void *insertPos = nullptr;
6602 SubstTemplateTemplateParmStorage *subst
6603 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6606 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6607 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6610 return TemplateName(subst);
6614 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6615 const TemplateArgument &ArgPack) const {
6616 ASTContext &Self = const_cast<ASTContext &>(*this);
6617 llvm::FoldingSetNodeID ID;
6618 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6620 void *InsertPos = nullptr;
6621 SubstTemplateTemplateParmPackStorage *Subst
6622 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6625 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6626 ArgPack.pack_size(),
6627 ArgPack.pack_begin());
6628 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6631 return TemplateName(Subst);
6634 /// getFromTargetType - Given one of the integer types provided by
6635 /// TargetInfo, produce the corresponding type. The unsigned @p Type
6636 /// is actually a value of type @c TargetInfo::IntType.
6637 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6639 case TargetInfo::NoInt: return CanQualType();
6640 case TargetInfo::SignedChar: return SignedCharTy;
6641 case TargetInfo::UnsignedChar: return UnsignedCharTy;
6642 case TargetInfo::SignedShort: return ShortTy;
6643 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6644 case TargetInfo::SignedInt: return IntTy;
6645 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6646 case TargetInfo::SignedLong: return LongTy;
6647 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6648 case TargetInfo::SignedLongLong: return LongLongTy;
6649 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6652 llvm_unreachable("Unhandled TargetInfo::IntType value");
6655 //===----------------------------------------------------------------------===//
6657 //===----------------------------------------------------------------------===//
6659 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6660 /// garbage collection attribute.
6662 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6663 if (getLangOpts().getGC() == LangOptions::NonGC)
6664 return Qualifiers::GCNone;
6666 assert(getLangOpts().ObjC1);
6667 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6669 // Default behaviour under objective-C's gc is for ObjC pointers
6670 // (or pointers to them) be treated as though they were declared
6672 if (GCAttrs == Qualifiers::GCNone) {
6673 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6674 return Qualifiers::Strong;
6675 else if (Ty->isPointerType())
6676 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6678 // It's not valid to set GC attributes on anything that isn't a
6681 QualType CT = Ty->getCanonicalTypeInternal();
6682 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6683 CT = AT->getElementType();
6684 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6690 //===----------------------------------------------------------------------===//
6691 // Type Compatibility Testing
6692 //===----------------------------------------------------------------------===//
6694 /// areCompatVectorTypes - Return true if the two specified vector types are
6696 static bool areCompatVectorTypes(const VectorType *LHS,
6697 const VectorType *RHS) {
6698 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6699 return LHS->getElementType() == RHS->getElementType() &&
6700 LHS->getNumElements() == RHS->getNumElements();
6703 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6704 QualType SecondVec) {
6705 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6706 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6708 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6711 // Treat Neon vector types and most AltiVec vector types as if they are the
6712 // equivalent GCC vector types.
6713 const VectorType *First = FirstVec->getAs<VectorType>();
6714 const VectorType *Second = SecondVec->getAs<VectorType>();
6715 if (First->getNumElements() == Second->getNumElements() &&
6716 hasSameType(First->getElementType(), Second->getElementType()) &&
6717 First->getVectorKind() != VectorType::AltiVecPixel &&
6718 First->getVectorKind() != VectorType::AltiVecBool &&
6719 Second->getVectorKind() != VectorType::AltiVecPixel &&
6720 Second->getVectorKind() != VectorType::AltiVecBool)
6726 //===----------------------------------------------------------------------===//
6727 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6728 //===----------------------------------------------------------------------===//
6730 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6731 /// inheritance hierarchy of 'rProto'.
6733 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6734 ObjCProtocolDecl *rProto) const {
6735 if (declaresSameEntity(lProto, rProto))
6737 for (auto *PI : rProto->protocols())
6738 if (ProtocolCompatibleWithProtocol(lProto, PI))
6743 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6744 /// Class<pr1, ...>.
6745 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6747 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6748 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6749 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6751 for (auto *lhsProto : lhsQID->quals()) {
6753 for (auto *rhsProto : rhsOPT->quals()) {
6754 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6765 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6766 /// ObjCQualifiedIDType.
6767 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6769 // Allow id<P..> and an 'id' or void* type in all cases.
6770 if (lhs->isVoidPointerType() ||
6771 lhs->isObjCIdType() || lhs->isObjCClassType())
6773 else if (rhs->isVoidPointerType() ||
6774 rhs->isObjCIdType() || rhs->isObjCClassType())
6777 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6778 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6780 if (!rhsOPT) return false;
6782 if (rhsOPT->qual_empty()) {
6783 // If the RHS is a unqualified interface pointer "NSString*",
6784 // make sure we check the class hierarchy.
6785 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6786 for (auto *I : lhsQID->quals()) {
6787 // when comparing an id<P> on lhs with a static type on rhs,
6788 // see if static class implements all of id's protocols, directly or
6789 // through its super class and categories.
6790 if (!rhsID->ClassImplementsProtocol(I, true))
6794 // If there are no qualifiers and no interface, we have an 'id'.
6797 // Both the right and left sides have qualifiers.
6798 for (auto *lhsProto : lhsQID->quals()) {
6801 // when comparing an id<P> on lhs with a static type on rhs,
6802 // see if static class implements all of id's protocols, directly or
6803 // through its super class and categories.
6804 for (auto *rhsProto : rhsOPT->quals()) {
6805 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6806 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6811 // If the RHS is a qualified interface pointer "NSString<P>*",
6812 // make sure we check the class hierarchy.
6813 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6814 for (auto *I : lhsQID->quals()) {
6815 // when comparing an id<P> on lhs with a static type on rhs,
6816 // see if static class implements all of id's protocols, directly or
6817 // through its super class and categories.
6818 if (rhsID->ClassImplementsProtocol(I, true)) {
6831 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6832 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6834 if (const ObjCObjectPointerType *lhsOPT =
6835 lhs->getAsObjCInterfacePointerType()) {
6836 // If both the right and left sides have qualifiers.
6837 for (auto *lhsProto : lhsOPT->quals()) {
6840 // when comparing an id<P> on rhs with a static type on lhs,
6841 // see if static class implements all of id's protocols, directly or
6842 // through its super class and categories.
6843 // First, lhs protocols in the qualifier list must be found, direct
6844 // or indirect in rhs's qualifier list or it is a mismatch.
6845 for (auto *rhsProto : rhsQID->quals()) {
6846 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6847 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6856 // Static class's protocols, or its super class or category protocols
6857 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6858 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6859 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6860 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6861 // This is rather dubious but matches gcc's behavior. If lhs has
6862 // no type qualifier and its class has no static protocol(s)
6863 // assume that it is mismatch.
6864 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6866 for (auto *lhsProto : LHSInheritedProtocols) {
6868 for (auto *rhsProto : rhsQID->quals()) {
6869 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6870 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6884 /// canAssignObjCInterfaces - Return true if the two interface types are
6885 /// compatible for assignment from RHS to LHS. This handles validation of any
6886 /// protocol qualifiers on the LHS or RHS.
6888 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6889 const ObjCObjectPointerType *RHSOPT) {
6890 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6891 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6893 // If either type represents the built-in 'id' or 'Class' types, return true.
6894 if (LHS->isObjCUnqualifiedIdOrClass() ||
6895 RHS->isObjCUnqualifiedIdOrClass())
6898 // Function object that propagates a successful result or handles
6900 auto finish = [&](bool succeeded) -> bool {
6904 if (!RHS->isKindOfType())
6907 // Strip off __kindof and protocol qualifiers, then check whether
6908 // we can assign the other way.
6909 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6910 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6913 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6914 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6919 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6920 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6921 QualType(RHSOPT,0)));
6924 // If we have 2 user-defined types, fall into that path.
6925 if (LHS->getInterface() && RHS->getInterface()) {
6926 return finish(canAssignObjCInterfaces(LHS, RHS));
6932 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6933 /// for providing type-safety for objective-c pointers used to pass/return
6934 /// arguments in block literals. When passed as arguments, passing 'A*' where
6935 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6936 /// not OK. For the return type, the opposite is not OK.
6937 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6938 const ObjCObjectPointerType *LHSOPT,
6939 const ObjCObjectPointerType *RHSOPT,
6940 bool BlockReturnType) {
6942 // Function object that propagates a successful result or handles
6944 auto finish = [&](bool succeeded) -> bool {
6948 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6949 if (!Expected->isKindOfType())
6952 // Strip off __kindof and protocol qualifiers, then check whether
6953 // we can assign the other way.
6954 return canAssignObjCInterfacesInBlockPointer(
6955 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6956 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6960 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
6963 if (LHSOPT->isObjCBuiltinType()) {
6964 return finish(RHSOPT->isObjCBuiltinType() ||
6965 RHSOPT->isObjCQualifiedIdType());
6968 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
6969 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6973 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6974 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6975 if (LHS && RHS) { // We have 2 user-defined types.
6977 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
6978 return finish(BlockReturnType);
6979 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
6980 return finish(!BlockReturnType);
6988 /// Comparison routine for Objective-C protocols to be used with
6989 /// llvm::array_pod_sort.
6990 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6991 ObjCProtocolDecl * const *rhs) {
6992 return (*lhs)->getName().compare((*rhs)->getName());
6996 /// getIntersectionOfProtocols - This routine finds the intersection of set
6997 /// of protocols inherited from two distinct objective-c pointer objects with
6998 /// the given common base.
6999 /// It is used to build composite qualifier list of the composite type of
7000 /// the conditional expression involving two objective-c pointer objects.
7002 void getIntersectionOfProtocols(ASTContext &Context,
7003 const ObjCInterfaceDecl *CommonBase,
7004 const ObjCObjectPointerType *LHSOPT,
7005 const ObjCObjectPointerType *RHSOPT,
7006 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
7008 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7009 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7010 assert(LHS->getInterface() && "LHS must have an interface base");
7011 assert(RHS->getInterface() && "RHS must have an interface base");
7013 // Add all of the protocols for the LHS.
7014 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7016 // Start with the protocol qualifiers.
7017 for (auto proto : LHS->quals()) {
7018 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
7021 // Also add the protocols associated with the LHS interface.
7022 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7024 // Add all of the protocls for the RHS.
7025 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7027 // Start with the protocol qualifiers.
7028 for (auto proto : RHS->quals()) {
7029 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
7032 // Also add the protocols associated with the RHS interface.
7033 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7035 // Compute the intersection of the collected protocol sets.
7036 for (auto proto : LHSProtocolSet) {
7037 if (RHSProtocolSet.count(proto))
7038 IntersectionSet.push_back(proto);
7041 // Compute the set of protocols that is implied by either the common type or
7042 // the protocols within the intersection.
7043 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7044 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7046 // Remove any implied protocols from the list of inherited protocols.
7047 if (!ImpliedProtocols.empty()) {
7048 IntersectionSet.erase(
7049 std::remove_if(IntersectionSet.begin(),
7050 IntersectionSet.end(),
7051 [&](ObjCProtocolDecl *proto) -> bool {
7052 return ImpliedProtocols.count(proto) > 0;
7054 IntersectionSet.end());
7057 // Sort the remaining protocols by name.
7058 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7059 compareObjCProtocolsByName);
7062 /// Determine whether the first type is a subtype of the second.
7063 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7065 // Common case: two object pointers.
7066 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7067 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7068 if (lhsOPT && rhsOPT)
7069 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7071 // Two block pointers.
7072 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7073 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7074 if (lhsBlock && rhsBlock)
7075 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7077 // If either is an unqualified 'id' and the other is a block, it's
7079 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7080 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7086 // Check that the given Objective-C type argument lists are equivalent.
7087 static bool sameObjCTypeArgs(ASTContext &ctx,
7088 const ObjCInterfaceDecl *iface,
7089 ArrayRef<QualType> lhsArgs,
7090 ArrayRef<QualType> rhsArgs,
7092 if (lhsArgs.size() != rhsArgs.size())
7095 ObjCTypeParamList *typeParams = iface->getTypeParamList();
7096 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
7097 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7100 switch (typeParams->begin()[i]->getVariance()) {
7101 case ObjCTypeParamVariance::Invariant:
7103 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7104 rhsArgs[i].stripObjCKindOfType(ctx))) {
7109 case ObjCTypeParamVariance::Covariant:
7110 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7114 case ObjCTypeParamVariance::Contravariant:
7115 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7124 QualType ASTContext::areCommonBaseCompatible(
7125 const ObjCObjectPointerType *Lptr,
7126 const ObjCObjectPointerType *Rptr) {
7127 const ObjCObjectType *LHS = Lptr->getObjectType();
7128 const ObjCObjectType *RHS = Rptr->getObjectType();
7129 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7130 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
7132 if (!LDecl || !RDecl)
7135 // Follow the left-hand side up the class hierarchy until we either hit a
7136 // root or find the RHS. Record the ancestors in case we don't find it.
7137 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7140 // Record this ancestor. We'll need this if the common type isn't in the
7141 // path from the LHS to the root.
7142 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
7144 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7145 // Get the type arguments.
7146 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7147 bool anyChanges = false;
7148 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7149 // Both have type arguments, compare them.
7150 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7151 LHS->getTypeArgs(), RHS->getTypeArgs(),
7152 /*stripKindOf=*/true))
7154 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7155 // If only one has type arguments, the result will not have type
7161 // Compute the intersection of protocols.
7162 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7163 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7165 if (!Protocols.empty())
7168 // If anything in the LHS will have changed, build a new result type.
7170 QualType Result = getObjCInterfaceType(LHS->getInterface());
7171 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7172 LHS->isKindOfType());
7173 return getObjCObjectPointerType(Result);
7176 return getObjCObjectPointerType(QualType(LHS, 0));
7179 // Find the superclass.
7180 QualType LHSSuperType = LHS->getSuperClassType();
7181 if (LHSSuperType.isNull())
7184 LHS = LHSSuperType->castAs<ObjCObjectType>();
7187 // We didn't find anything by following the LHS to its root; now check
7188 // the RHS against the cached set of ancestors.
7190 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7191 if (KnownLHS != LHSAncestors.end()) {
7192 LHS = KnownLHS->second;
7194 // Get the type arguments.
7195 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7196 bool anyChanges = false;
7197 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7198 // Both have type arguments, compare them.
7199 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7200 LHS->getTypeArgs(), RHS->getTypeArgs(),
7201 /*stripKindOf=*/true))
7203 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7204 // If only one has type arguments, the result will not have type
7210 // Compute the intersection of protocols.
7211 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7212 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7214 if (!Protocols.empty())
7218 QualType Result = getObjCInterfaceType(RHS->getInterface());
7219 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7220 RHS->isKindOfType());
7221 return getObjCObjectPointerType(Result);
7224 return getObjCObjectPointerType(QualType(RHS, 0));
7227 // Find the superclass of the RHS.
7228 QualType RHSSuperType = RHS->getSuperClassType();
7229 if (RHSSuperType.isNull())
7232 RHS = RHSSuperType->castAs<ObjCObjectType>();
7238 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7239 const ObjCObjectType *RHS) {
7240 assert(LHS->getInterface() && "LHS is not an interface type");
7241 assert(RHS->getInterface() && "RHS is not an interface type");
7243 // Verify that the base decls are compatible: the RHS must be a subclass of
7245 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7246 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7250 // If the LHS has protocol qualifiers, determine whether all of them are
7251 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7253 if (LHS->getNumProtocols() > 0) {
7254 // OK if conversion of LHS to SuperClass results in narrowing of types
7255 // ; i.e., SuperClass may implement at least one of the protocols
7256 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7257 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7258 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7259 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7260 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7262 for (auto *RHSPI : RHS->quals())
7263 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
7264 // If there is no protocols associated with RHS, it is not a match.
7265 if (SuperClassInheritedProtocols.empty())
7268 for (const auto *LHSProto : LHS->quals()) {
7269 bool SuperImplementsProtocol = false;
7270 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7271 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7272 SuperImplementsProtocol = true;
7275 if (!SuperImplementsProtocol)
7280 // If the LHS is specialized, we may need to check type arguments.
7281 if (LHS->isSpecialized()) {
7282 // Follow the superclass chain until we've matched the LHS class in the
7283 // hierarchy. This substitutes type arguments through.
7284 const ObjCObjectType *RHSSuper = RHS;
7285 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7286 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7288 // If the RHS is specializd, compare type arguments.
7289 if (RHSSuper->isSpecialized() &&
7290 !sameObjCTypeArgs(*this, LHS->getInterface(),
7291 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
7292 /*stripKindOf=*/true)) {
7300 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7301 // get the "pointed to" types
7302 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7303 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
7305 if (!LHSOPT || !RHSOPT)
7308 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7309 canAssignObjCInterfaces(RHSOPT, LHSOPT);
7312 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7313 return canAssignObjCInterfaces(
7314 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7315 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7318 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
7319 /// both shall have the identically qualified version of a compatible type.
7320 /// C99 6.2.7p1: Two types have compatible types if their types are the
7321 /// same. See 6.7.[2,3,5] for additional rules.
7322 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7323 bool CompareUnqualified) {
7324 if (getLangOpts().CPlusPlus)
7325 return hasSameType(LHS, RHS);
7327 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
7330 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
7331 return typesAreCompatible(LHS, RHS);
7334 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7335 return !mergeTypes(LHS, RHS, true).isNull();
7338 /// mergeTransparentUnionType - if T is a transparent union type and a member
7339 /// of T is compatible with SubType, return the merged type, else return
7341 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7342 bool OfBlockPointer,
7344 if (const RecordType *UT = T->getAsUnionType()) {
7345 RecordDecl *UD = UT->getDecl();
7346 if (UD->hasAttr<TransparentUnionAttr>()) {
7347 for (const auto *I : UD->fields()) {
7348 QualType ET = I->getType().getUnqualifiedType();
7349 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7359 /// mergeFunctionParameterTypes - merge two types which appear as function
7361 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7362 bool OfBlockPointer,
7364 // GNU extension: two types are compatible if they appear as a function
7365 // argument, one of the types is a transparent union type and the other
7366 // type is compatible with a union member
7367 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7369 if (!lmerge.isNull())
7372 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7374 if (!rmerge.isNull())
7377 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7380 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
7381 bool OfBlockPointer,
7383 const FunctionType *lbase = lhs->getAs<FunctionType>();
7384 const FunctionType *rbase = rhs->getAs<FunctionType>();
7385 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7386 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
7387 bool allLTypes = true;
7388 bool allRTypes = true;
7390 // Check return type
7392 if (OfBlockPointer) {
7393 QualType RHS = rbase->getReturnType();
7394 QualType LHS = lbase->getReturnType();
7395 bool UnqualifiedResult = Unqualified;
7396 if (!UnqualifiedResult)
7397 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
7398 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
7401 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
7403 if (retType.isNull()) return QualType();
7406 retType = retType.getUnqualifiedType();
7408 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7409 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
7411 LRetType = LRetType.getUnqualifiedType();
7412 RRetType = RRetType.getUnqualifiedType();
7415 if (getCanonicalType(retType) != LRetType)
7417 if (getCanonicalType(retType) != RRetType)
7420 // FIXME: double check this
7421 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7422 // rbase->getRegParmAttr() != 0 &&
7423 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
7424 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7425 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
7427 // Compatible functions must have compatible calling conventions
7428 if (lbaseInfo.getCC() != rbaseInfo.getCC())
7431 // Regparm is part of the calling convention.
7432 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7434 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7437 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7440 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7441 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
7443 if (lbaseInfo.getNoReturn() != NoReturn)
7445 if (rbaseInfo.getNoReturn() != NoReturn)
7448 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
7450 if (lproto && rproto) { // two C99 style function prototypes
7451 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7452 "C++ shouldn't be here");
7453 // Compatible functions must have the same number of parameters
7454 if (lproto->getNumParams() != rproto->getNumParams())
7457 // Variadic and non-variadic functions aren't compatible
7458 if (lproto->isVariadic() != rproto->isVariadic())
7461 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7464 if (LangOpts.ObjCAutoRefCount &&
7465 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7468 // Check parameter type compatibility
7469 SmallVector<QualType, 10> types;
7470 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7471 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7472 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7473 QualType paramType = mergeFunctionParameterTypes(
7474 lParamType, rParamType, OfBlockPointer, Unqualified);
7475 if (paramType.isNull())
7479 paramType = paramType.getUnqualifiedType();
7481 types.push_back(paramType);
7483 lParamType = lParamType.getUnqualifiedType();
7484 rParamType = rParamType.getUnqualifiedType();
7487 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
7489 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
7493 if (allLTypes) return lhs;
7494 if (allRTypes) return rhs;
7496 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7497 EPI.ExtInfo = einfo;
7498 return getFunctionType(retType, types, EPI);
7501 if (lproto) allRTypes = false;
7502 if (rproto) allLTypes = false;
7504 const FunctionProtoType *proto = lproto ? lproto : rproto;
7506 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7507 if (proto->isVariadic()) return QualType();
7508 // Check that the types are compatible with the types that
7509 // would result from default argument promotions (C99 6.7.5.3p15).
7510 // The only types actually affected are promotable integer
7511 // types and floats, which would be passed as a different
7512 // type depending on whether the prototype is visible.
7513 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7514 QualType paramTy = proto->getParamType(i);
7516 // Look at the converted type of enum types, since that is the type used
7517 // to pass enum values.
7518 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7519 paramTy = Enum->getDecl()->getIntegerType();
7520 if (paramTy.isNull())
7524 if (paramTy->isPromotableIntegerType() ||
7525 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
7529 if (allLTypes) return lhs;
7530 if (allRTypes) return rhs;
7532 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7533 EPI.ExtInfo = einfo;
7534 return getFunctionType(retType, proto->getParamTypes(), EPI);
7537 if (allLTypes) return lhs;
7538 if (allRTypes) return rhs;
7539 return getFunctionNoProtoType(retType, einfo);
7542 /// Given that we have an enum type and a non-enum type, try to merge them.
7543 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7544 QualType other, bool isBlockReturnType) {
7545 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7546 // a signed integer type, or an unsigned integer type.
7547 // Compatibility is based on the underlying type, not the promotion
7549 QualType underlyingType = ET->getDecl()->getIntegerType();
7550 if (underlyingType.isNull()) return QualType();
7551 if (Context.hasSameType(underlyingType, other))
7554 // In block return types, we're more permissive and accept any
7555 // integral type of the same size.
7556 if (isBlockReturnType && other->isIntegerType() &&
7557 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7563 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
7564 bool OfBlockPointer,
7565 bool Unqualified, bool BlockReturnType) {
7566 // C++ [expr]: If an expression initially has the type "reference to T", the
7567 // type is adjusted to "T" prior to any further analysis, the expression
7568 // designates the object or function denoted by the reference, and the
7569 // expression is an lvalue unless the reference is an rvalue reference and
7570 // the expression is a function call (possibly inside parentheses).
7571 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7572 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
7575 LHS = LHS.getUnqualifiedType();
7576 RHS = RHS.getUnqualifiedType();
7579 QualType LHSCan = getCanonicalType(LHS),
7580 RHSCan = getCanonicalType(RHS);
7582 // If two types are identical, they are compatible.
7583 if (LHSCan == RHSCan)
7586 // If the qualifiers are different, the types aren't compatible... mostly.
7587 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7588 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7589 if (LQuals != RQuals) {
7590 // If any of these qualifiers are different, we have a type
7592 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7593 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7594 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
7597 // Exactly one GC qualifier difference is allowed: __strong is
7598 // okay if the other type has no GC qualifier but is an Objective
7599 // C object pointer (i.e. implicitly strong by default). We fix
7600 // this by pretending that the unqualified type was actually
7601 // qualified __strong.
7602 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7603 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7604 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7606 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7609 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7610 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7612 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7613 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7618 // Okay, qualifiers are equal.
7620 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7621 Type::TypeClass RHSClass = RHSCan->getTypeClass();
7623 // We want to consider the two function types to be the same for these
7624 // comparisons, just force one to the other.
7625 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7626 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
7628 // Same as above for arrays
7629 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7630 LHSClass = Type::ConstantArray;
7631 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7632 RHSClass = Type::ConstantArray;
7634 // ObjCInterfaces are just specialized ObjCObjects.
7635 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7636 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7638 // Canonicalize ExtVector -> Vector.
7639 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7640 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
7642 // If the canonical type classes don't match.
7643 if (LHSClass != RHSClass) {
7644 // Note that we only have special rules for turning block enum
7645 // returns into block int returns, not vice-versa.
7646 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
7647 return mergeEnumWithInteger(*this, ETy, RHS, false);
7649 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
7650 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
7652 // allow block pointer type to match an 'id' type.
7653 if (OfBlockPointer && !BlockReturnType) {
7654 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7656 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7663 // The canonical type classes match.
7665 #define TYPE(Class, Base)
7666 #define ABSTRACT_TYPE(Class, Base)
7667 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
7668 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7669 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
7670 #include "clang/AST/TypeNodes.def"
7671 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
7674 case Type::LValueReference:
7675 case Type::RValueReference:
7676 case Type::MemberPointer:
7677 llvm_unreachable("C++ should never be in mergeTypes");
7679 case Type::ObjCInterface:
7680 case Type::IncompleteArray:
7681 case Type::VariableArray:
7682 case Type::FunctionProto:
7683 case Type::ExtVector:
7684 llvm_unreachable("Types are eliminated above");
7688 // Merge two pointer types, while trying to preserve typedef info
7689 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7690 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
7692 LHSPointee = LHSPointee.getUnqualifiedType();
7693 RHSPointee = RHSPointee.getUnqualifiedType();
7695 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7697 if (ResultType.isNull()) return QualType();
7698 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7700 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7702 return getPointerType(ResultType);
7704 case Type::BlockPointer:
7706 // Merge two block pointer types, while trying to preserve typedef info
7707 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7708 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7710 LHSPointee = LHSPointee.getUnqualifiedType();
7711 RHSPointee = RHSPointee.getUnqualifiedType();
7713 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7715 if (ResultType.isNull()) return QualType();
7716 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7718 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7720 return getBlockPointerType(ResultType);
7724 // Merge two pointer types, while trying to preserve typedef info
7725 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7726 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7728 LHSValue = LHSValue.getUnqualifiedType();
7729 RHSValue = RHSValue.getUnqualifiedType();
7731 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7733 if (ResultType.isNull()) return QualType();
7734 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7736 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7738 return getAtomicType(ResultType);
7740 case Type::ConstantArray:
7742 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7743 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7744 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7747 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7748 QualType RHSElem = getAsArrayType(RHS)->getElementType();
7750 LHSElem = LHSElem.getUnqualifiedType();
7751 RHSElem = RHSElem.getUnqualifiedType();
7754 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7755 if (ResultType.isNull()) return QualType();
7756 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7758 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7760 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7761 ArrayType::ArraySizeModifier(), 0);
7762 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7763 ArrayType::ArraySizeModifier(), 0);
7764 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7765 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7766 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7768 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7771 // FIXME: This isn't correct! But tricky to implement because
7772 // the array's size has to be the size of LHS, but the type
7773 // has to be different.
7777 // FIXME: This isn't correct! But tricky to implement because
7778 // the array's size has to be the size of RHS, but the type
7779 // has to be different.
7782 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7783 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7784 return getIncompleteArrayType(ResultType,
7785 ArrayType::ArraySizeModifier(), 0);
7787 case Type::FunctionNoProto:
7788 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7793 // Only exactly equal builtin types are compatible, which is tested above.
7796 // Distinct complex types are incompatible.
7799 // FIXME: The merged type should be an ExtVector!
7800 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7801 RHSCan->getAs<VectorType>()))
7804 case Type::ObjCObject: {
7805 // Check if the types are assignment compatible.
7806 // FIXME: This should be type compatibility, e.g. whether
7807 // "LHS x; RHS x;" at global scope is legal.
7808 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7809 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7810 if (canAssignObjCInterfaces(LHSIface, RHSIface))
7815 case Type::ObjCObjectPointer: {
7816 if (OfBlockPointer) {
7817 if (canAssignObjCInterfacesInBlockPointer(
7818 LHS->getAs<ObjCObjectPointerType>(),
7819 RHS->getAs<ObjCObjectPointerType>(),
7824 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7825 RHS->getAs<ObjCObjectPointerType>()))
7832 // Merge two pointer types, while trying to preserve typedef info
7833 QualType LHSValue = LHS->getAs<PipeType>()->getElementType();
7834 QualType RHSValue = RHS->getAs<PipeType>()->getElementType();
7836 LHSValue = LHSValue.getUnqualifiedType();
7837 RHSValue = RHSValue.getUnqualifiedType();
7839 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7841 if (ResultType.isNull()) return QualType();
7842 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7844 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7846 return getPipeType(ResultType);
7850 llvm_unreachable("Invalid Type::Class!");
7853 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7854 const FunctionProtoType *FromFunctionType,
7855 const FunctionProtoType *ToFunctionType) {
7856 if (FromFunctionType->hasAnyConsumedParams() !=
7857 ToFunctionType->hasAnyConsumedParams())
7859 FunctionProtoType::ExtProtoInfo FromEPI =
7860 FromFunctionType->getExtProtoInfo();
7861 FunctionProtoType::ExtProtoInfo ToEPI =
7862 ToFunctionType->getExtProtoInfo();
7863 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
7864 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7865 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
7871 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
7872 ObjCLayouts[CD] = nullptr;
7875 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7876 /// 'RHS' attributes and returns the merged version; including for function
7878 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7879 QualType LHSCan = getCanonicalType(LHS),
7880 RHSCan = getCanonicalType(RHS);
7881 // If two types are identical, they are compatible.
7882 if (LHSCan == RHSCan)
7884 if (RHSCan->isFunctionType()) {
7885 if (!LHSCan->isFunctionType())
7887 QualType OldReturnType =
7888 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
7889 QualType NewReturnType =
7890 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
7891 QualType ResReturnType =
7892 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7893 if (ResReturnType.isNull())
7895 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7896 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7897 // In either case, use OldReturnType to build the new function type.
7898 const FunctionType *F = LHS->getAs<FunctionType>();
7899 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7900 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7901 EPI.ExtInfo = getFunctionExtInfo(LHS);
7902 QualType ResultType =
7903 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
7910 // If the qualifiers are different, the types can still be merged.
7911 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7912 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7913 if (LQuals != RQuals) {
7914 // If any of these qualifiers are different, we have a type mismatch.
7915 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7916 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7919 // Exactly one GC qualifier difference is allowed: __strong is
7920 // okay if the other type has no GC qualifier but is an Objective
7921 // C object pointer (i.e. implicitly strong by default). We fix
7922 // this by pretending that the unqualified type was actually
7923 // qualified __strong.
7924 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7925 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7926 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7928 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7931 if (GC_L == Qualifiers::Strong)
7933 if (GC_R == Qualifiers::Strong)
7938 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7939 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7940 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7941 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7942 if (ResQT == LHSBaseQT)
7944 if (ResQT == RHSBaseQT)
7950 //===----------------------------------------------------------------------===//
7951 // Integer Predicates
7952 //===----------------------------------------------------------------------===//
7954 unsigned ASTContext::getIntWidth(QualType T) const {
7955 if (const EnumType *ET = T->getAs<EnumType>())
7956 T = ET->getDecl()->getIntegerType();
7957 if (T->isBooleanType())
7959 // For builtin types, just use the standard type sizing method
7960 return (unsigned)getTypeSize(T);
7963 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
7964 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
7966 // Turn <4 x signed int> -> <4 x unsigned int>
7967 if (const VectorType *VTy = T->getAs<VectorType>())
7968 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
7969 VTy->getNumElements(), VTy->getVectorKind());
7971 // For enums, we return the unsigned version of the base type.
7972 if (const EnumType *ETy = T->getAs<EnumType>())
7973 T = ETy->getDecl()->getIntegerType();
7975 const BuiltinType *BTy = T->getAs<BuiltinType>();
7976 assert(BTy && "Unexpected signed integer type");
7977 switch (BTy->getKind()) {
7978 case BuiltinType::Char_S:
7979 case BuiltinType::SChar:
7980 return UnsignedCharTy;
7981 case BuiltinType::Short:
7982 return UnsignedShortTy;
7983 case BuiltinType::Int:
7984 return UnsignedIntTy;
7985 case BuiltinType::Long:
7986 return UnsignedLongTy;
7987 case BuiltinType::LongLong:
7988 return UnsignedLongLongTy;
7989 case BuiltinType::Int128:
7990 return UnsignedInt128Ty;
7992 llvm_unreachable("Unexpected signed integer type");
7996 ASTMutationListener::~ASTMutationListener() { }
7998 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7999 QualType ReturnType) {}
8001 //===----------------------------------------------------------------------===//
8002 // Builtin Type Computation
8003 //===----------------------------------------------------------------------===//
8005 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
8006 /// pointer over the consumed characters. This returns the resultant type. If
8007 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8008 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8009 /// a vector of "i*".
8011 /// RequiresICE is filled in on return to indicate whether the value is required
8012 /// to be an Integer Constant Expression.
8013 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
8014 ASTContext::GetBuiltinTypeError &Error,
8016 bool AllowTypeModifiers) {
8019 bool Signed = false, Unsigned = false;
8020 RequiresICE = false;
8022 // Read the prefixed modifiers first.
8026 default: Done = true; --Str; break;
8031 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8032 assert(!Signed && "Can't use 'S' modifier multiple times!");
8036 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
8037 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
8041 assert(HowLong <= 2 && "Can't have LLLL modifier");
8045 // This modifier represents int64 type.
8046 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8047 switch (Context.getTargetInfo().getInt64Type()) {
8049 llvm_unreachable("Unexpected integer type");
8050 case TargetInfo::SignedLong:
8053 case TargetInfo::SignedLongLong:
8062 // Read the base type.
8064 default: llvm_unreachable("Unknown builtin type letter!");
8066 assert(HowLong == 0 && !Signed && !Unsigned &&
8067 "Bad modifiers used with 'v'!");
8068 Type = Context.VoidTy;
8071 assert(HowLong == 0 && !Signed && !Unsigned &&
8072 "Bad modifiers used with 'h'!");
8073 Type = Context.HalfTy;
8076 assert(HowLong == 0 && !Signed && !Unsigned &&
8077 "Bad modifiers used with 'f'!");
8078 Type = Context.FloatTy;
8081 assert(HowLong < 2 && !Signed && !Unsigned &&
8082 "Bad modifiers used with 'd'!");
8084 Type = Context.LongDoubleTy;
8086 Type = Context.DoubleTy;
8089 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8091 Type = Context.UnsignedShortTy;
8093 Type = Context.ShortTy;
8097 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8098 else if (HowLong == 2)
8099 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8100 else if (HowLong == 1)
8101 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8103 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8106 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8108 Type = Context.SignedCharTy;
8110 Type = Context.UnsignedCharTy;
8112 Type = Context.CharTy;
8114 case 'b': // boolean
8115 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8116 Type = Context.BoolTy;
8118 case 'z': // size_t.
8119 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8120 Type = Context.getSizeType();
8123 Type = Context.getCFConstantStringType();
8126 Type = Context.getObjCIdType();
8129 Type = Context.getObjCSelType();
8132 Type = Context.getObjCSuperType();
8135 Type = Context.getBuiltinVaListType();
8136 assert(!Type.isNull() && "builtin va list type not initialized!");
8139 // This is a "reference" to a va_list; however, what exactly
8140 // this means depends on how va_list is defined. There are two
8141 // different kinds of va_list: ones passed by value, and ones
8142 // passed by reference. An example of a by-value va_list is
8143 // x86, where va_list is a char*. An example of by-ref va_list
8144 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8145 // we want this argument to be a char*&; for x86-64, we want
8146 // it to be a __va_list_tag*.
8147 Type = Context.getBuiltinVaListType();
8148 assert(!Type.isNull() && "builtin va list type not initialized!");
8149 if (Type->isArrayType())
8150 Type = Context.getArrayDecayedType(Type);
8152 Type = Context.getLValueReferenceType(Type);
8156 unsigned NumElements = strtoul(Str, &End, 10);
8157 assert(End != Str && "Missing vector size");
8160 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8161 RequiresICE, false);
8162 assert(!RequiresICE && "Can't require vector ICE");
8164 // TODO: No way to make AltiVec vectors in builtins yet.
8165 Type = Context.getVectorType(ElementType, NumElements,
8166 VectorType::GenericVector);
8172 unsigned NumElements = strtoul(Str, &End, 10);
8173 assert(End != Str && "Missing vector size");
8177 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8179 Type = Context.getExtVectorType(ElementType, NumElements);
8183 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8185 assert(!RequiresICE && "Can't require complex ICE");
8186 Type = Context.getComplexType(ElementType);
8190 Type = Context.getPointerDiffType();
8194 Type = Context.getFILEType();
8195 if (Type.isNull()) {
8196 Error = ASTContext::GE_Missing_stdio;
8202 Type = Context.getsigjmp_bufType();
8204 Type = Context.getjmp_bufType();
8206 if (Type.isNull()) {
8207 Error = ASTContext::GE_Missing_setjmp;
8212 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8213 Type = Context.getucontext_tType();
8215 if (Type.isNull()) {
8216 Error = ASTContext::GE_Missing_ucontext;
8221 Type = Context.getProcessIDType();
8225 // If there are modifiers and if we're allowed to parse them, go for it.
8226 Done = !AllowTypeModifiers;
8228 switch (char c = *Str++) {
8229 default: Done = true; --Str; break;
8232 // Both pointers and references can have their pointee types
8233 // qualified with an address space.
8235 unsigned AddrSpace = strtoul(Str, &End, 10);
8236 if (End != Str && AddrSpace != 0) {
8237 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8241 Type = Context.getPointerType(Type);
8243 Type = Context.getLValueReferenceType(Type);
8246 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8248 Type = Type.withConst();
8251 Type = Context.getVolatileType(Type);
8254 Type = Type.withRestrict();
8259 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
8260 "Integer constant 'I' type must be an integer");
8265 /// GetBuiltinType - Return the type for the specified builtin.
8266 QualType ASTContext::GetBuiltinType(unsigned Id,
8267 GetBuiltinTypeError &Error,
8268 unsigned *IntegerConstantArgs) const {
8269 const char *TypeStr = BuiltinInfo.getTypeString(Id);
8271 SmallVector<QualType, 8> ArgTypes;
8273 bool RequiresICE = false;
8275 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8277 if (Error != GE_None)
8280 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8282 while (TypeStr[0] && TypeStr[0] != '.') {
8283 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
8284 if (Error != GE_None)
8287 // If this argument is required to be an IntegerConstantExpression and the
8288 // caller cares, fill in the bitmask we return.
8289 if (RequiresICE && IntegerConstantArgs)
8290 *IntegerConstantArgs |= 1 << ArgTypes.size();
8292 // Do array -> pointer decay. The builtin should use the decayed type.
8293 if (Ty->isArrayType())
8294 Ty = getArrayDecayedType(Ty);
8296 ArgTypes.push_back(Ty);
8299 if (Id == Builtin::BI__GetExceptionInfo)
8302 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8303 "'.' should only occur at end of builtin type list!");
8305 FunctionType::ExtInfo EI(CC_C);
8306 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8308 bool Variadic = (TypeStr[0] == '.');
8310 // We really shouldn't be making a no-proto type here, especially in C++.
8311 if (ArgTypes.empty() && Variadic)
8312 return getFunctionNoProtoType(ResType, EI);
8314 FunctionProtoType::ExtProtoInfo EPI;
8316 EPI.Variadic = Variadic;
8318 return getFunctionType(ResType, ArgTypes, EPI);
8321 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8322 const FunctionDecl *FD) {
8323 if (!FD->isExternallyVisible())
8324 return GVA_Internal;
8326 GVALinkage External = GVA_StrongExternal;
8327 switch (FD->getTemplateSpecializationKind()) {
8328 case TSK_Undeclared:
8329 case TSK_ExplicitSpecialization:
8330 External = GVA_StrongExternal;
8333 case TSK_ExplicitInstantiationDefinition:
8334 return GVA_StrongODR;
8336 // C++11 [temp.explicit]p10:
8337 // [ Note: The intent is that an inline function that is the subject of
8338 // an explicit instantiation declaration will still be implicitly
8339 // instantiated when used so that the body can be considered for
8340 // inlining, but that no out-of-line copy of the inline function would be
8341 // generated in the translation unit. -- end note ]
8342 case TSK_ExplicitInstantiationDeclaration:
8343 return GVA_AvailableExternally;
8345 case TSK_ImplicitInstantiation:
8346 External = GVA_DiscardableODR;
8350 if (!FD->isInlined())
8353 if ((!Context.getLangOpts().CPlusPlus &&
8354 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8355 !FD->hasAttr<DLLExportAttr>()) ||
8356 FD->hasAttr<GNUInlineAttr>()) {
8357 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8359 // GNU or C99 inline semantics. Determine whether this symbol should be
8360 // externally visible.
8361 if (FD->isInlineDefinitionExternallyVisible())
8364 // C99 inline semantics, where the symbol is not externally visible.
8365 return GVA_AvailableExternally;
8368 // Functions specified with extern and inline in -fms-compatibility mode
8369 // forcibly get emitted. While the body of the function cannot be later
8370 // replaced, the function definition cannot be discarded.
8371 if (FD->isMSExternInline())
8372 return GVA_StrongODR;
8374 return GVA_DiscardableODR;
8377 static GVALinkage adjustGVALinkageForAttributes(GVALinkage L, const Decl *D) {
8378 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8379 // dllexport/dllimport on inline functions.
8380 if (D->hasAttr<DLLImportAttr>()) {
8381 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8382 return GVA_AvailableExternally;
8383 } else if (D->hasAttr<DLLExportAttr>() || D->hasAttr<CUDAGlobalAttr>()) {
8384 if (L == GVA_DiscardableODR)
8385 return GVA_StrongODR;
8390 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8391 return adjustGVALinkageForAttributes(basicGVALinkageForFunction(*this, FD),
8395 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8396 const VarDecl *VD) {
8397 if (!VD->isExternallyVisible())
8398 return GVA_Internal;
8400 if (VD->isStaticLocal()) {
8401 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8402 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8403 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8404 LexicalContext = LexicalContext->getLexicalParent();
8406 // Let the static local variable inherit its linkage from the nearest
8407 // enclosing function.
8409 StaticLocalLinkage =
8410 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8412 // GVA_StrongODR function linkage is stronger than what we need,
8413 // downgrade to GVA_DiscardableODR.
8414 // This allows us to discard the variable if we never end up needing it.
8415 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8416 : StaticLocalLinkage;
8419 // MSVC treats in-class initialized static data members as definitions.
8420 // By giving them non-strong linkage, out-of-line definitions won't
8421 // cause link errors.
8422 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8423 return GVA_DiscardableODR;
8425 switch (VD->getTemplateSpecializationKind()) {
8426 case TSK_Undeclared:
8427 return GVA_StrongExternal;
8429 case TSK_ExplicitSpecialization:
8430 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8431 VD->isStaticDataMember()
8433 : GVA_StrongExternal;
8435 case TSK_ExplicitInstantiationDefinition:
8436 return GVA_StrongODR;
8438 case TSK_ExplicitInstantiationDeclaration:
8439 return GVA_AvailableExternally;
8441 case TSK_ImplicitInstantiation:
8442 return GVA_DiscardableODR;
8445 llvm_unreachable("Invalid Linkage!");
8448 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8449 return adjustGVALinkageForAttributes(basicGVALinkageForVariable(*this, VD),
8453 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
8454 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8455 if (!VD->isFileVarDecl())
8457 // Global named register variables (GNU extension) are never emitted.
8458 if (VD->getStorageClass() == SC_Register)
8460 if (VD->getDescribedVarTemplate() ||
8461 isa<VarTemplatePartialSpecializationDecl>(VD))
8463 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8464 // We never need to emit an uninstantiated function template.
8465 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8467 } else if (isa<OMPThreadPrivateDecl>(D))
8472 // If this is a member of a class template, we do not need to emit it.
8473 if (D->getDeclContext()->isDependentContext())
8476 // Weak references don't produce any output by themselves.
8477 if (D->hasAttr<WeakRefAttr>())
8480 // Aliases and used decls are required.
8481 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8484 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8485 // Forward declarations aren't required.
8486 if (!FD->doesThisDeclarationHaveABody())
8487 return FD->doesDeclarationForceExternallyVisibleDefinition();
8489 // Constructors and destructors are required.
8490 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8493 // The key function for a class is required. This rule only comes
8494 // into play when inline functions can be key functions, though.
8495 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8496 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8497 const CXXRecordDecl *RD = MD->getParent();
8498 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8499 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8500 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8506 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8508 // static, static inline, always_inline, and extern inline functions can
8509 // always be deferred. Normal inline functions can be deferred in C99/C++.
8510 // Implicit template instantiations can also be deferred in C++.
8511 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8512 Linkage == GVA_DiscardableODR)
8517 const VarDecl *VD = cast<VarDecl>(D);
8518 assert(VD->isFileVarDecl() && "Expected file scoped var");
8520 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8521 !isMSStaticDataMemberInlineDefinition(VD))
8524 // Variables that can be needed in other TUs are required.
8525 GVALinkage L = GetGVALinkageForVariable(VD);
8526 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8527 L != GVA_DiscardableODR)
8530 // Variables that have destruction with side-effects are required.
8531 if (VD->getType().isDestructedType())
8534 // Variables that have initialization with side-effects are required.
8535 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8536 !VD->evaluateValue())
8542 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8543 bool IsCXXMethod) const {
8544 // Pass through to the C++ ABI object
8546 return ABI->getDefaultMethodCallConv(IsVariadic);
8548 if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8550 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
8553 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
8554 // Pass through to the C++ ABI object
8555 return ABI->isNearlyEmpty(RD);
8558 VTableContextBase *ASTContext::getVTableContext() {
8559 if (!VTContext.get()) {
8560 if (Target->getCXXABI().isMicrosoft())
8561 VTContext.reset(new MicrosoftVTableContext(*this));
8563 VTContext.reset(new ItaniumVTableContext(*this));
8565 return VTContext.get();
8568 MangleContext *ASTContext::createMangleContext() {
8569 switch (Target->getCXXABI().getKind()) {
8570 case TargetCXXABI::GenericAArch64:
8571 case TargetCXXABI::GenericItanium:
8572 case TargetCXXABI::GenericARM:
8573 case TargetCXXABI::GenericMIPS:
8574 case TargetCXXABI::iOS:
8575 case TargetCXXABI::iOS64:
8576 case TargetCXXABI::WebAssembly:
8577 case TargetCXXABI::WatchOS:
8578 return ItaniumMangleContext::create(*this, getDiagnostics());
8579 case TargetCXXABI::Microsoft:
8580 return MicrosoftMangleContext::create(*this, getDiagnostics());
8582 llvm_unreachable("Unsupported ABI");
8585 CXXABI::~CXXABI() {}
8587 size_t ASTContext::getSideTableAllocatedMemory() const {
8588 return ASTRecordLayouts.getMemorySize() +
8589 llvm::capacity_in_bytes(ObjCLayouts) +
8590 llvm::capacity_in_bytes(KeyFunctions) +
8591 llvm::capacity_in_bytes(ObjCImpls) +
8592 llvm::capacity_in_bytes(BlockVarCopyInits) +
8593 llvm::capacity_in_bytes(DeclAttrs) +
8594 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8595 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8596 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8597 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8598 llvm::capacity_in_bytes(OverriddenMethods) +
8599 llvm::capacity_in_bytes(Types) +
8600 llvm::capacity_in_bytes(VariableArrayTypes) +
8601 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
8604 /// getIntTypeForBitwidth -
8605 /// sets integer QualTy according to specified details:
8606 /// bitwidth, signed/unsigned.
8607 /// Returns empty type if there is no appropriate target types.
8608 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8609 unsigned Signed) const {
8610 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8611 CanQualType QualTy = getFromTargetType(Ty);
8612 if (!QualTy && DestWidth == 128)
8613 return Signed ? Int128Ty : UnsignedInt128Ty;
8617 /// getRealTypeForBitwidth -
8618 /// sets floating point QualTy according to specified bitwidth.
8619 /// Returns empty type if there is no appropriate target types.
8620 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8621 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8623 case TargetInfo::Float:
8625 case TargetInfo::Double:
8627 case TargetInfo::LongDouble:
8628 return LongDoubleTy;
8629 case TargetInfo::NoFloat:
8633 llvm_unreachable("Unhandled TargetInfo::RealType value");
8636 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8638 MangleNumbers[ND] = Number;
8641 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8642 llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8643 MangleNumbers.find(ND);
8644 return I != MangleNumbers.end() ? I->second : 1;
8647 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8649 StaticLocalNumbers[VD] = Number;
8652 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8653 llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8654 StaticLocalNumbers.find(VD);
8655 return I != StaticLocalNumbers.end() ? I->second : 1;
8658 MangleNumberingContext &
8659 ASTContext::getManglingNumberContext(const DeclContext *DC) {
8660 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8661 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8663 MCtx = createMangleNumberingContext();
8667 MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8668 return ABI->createMangleNumberingContext();
8671 const CXXConstructorDecl *
8672 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8673 return ABI->getCopyConstructorForExceptionObject(
8674 cast<CXXRecordDecl>(RD->getFirstDecl()));
8677 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8678 CXXConstructorDecl *CD) {
8679 return ABI->addCopyConstructorForExceptionObject(
8680 cast<CXXRecordDecl>(RD->getFirstDecl()),
8681 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8684 void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8685 unsigned ParmIdx, Expr *DAE) {
8686 ABI->addDefaultArgExprForConstructor(
8687 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8690 Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8692 return ABI->getDefaultArgExprForConstructor(
8693 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8696 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8697 TypedefNameDecl *DD) {
8698 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8702 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8703 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8706 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8707 DeclaratorDecl *DD) {
8708 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8711 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8712 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8715 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8716 ParamIndices[D] = index;
8719 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8720 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8721 assert(I != ParamIndices.end() &&
8722 "ParmIndices lacks entry set by ParmVarDecl");
8727 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8729 assert(E && E->getStorageDuration() == SD_Static &&
8730 "don't need to cache the computed value for this temporary");
8732 APValue *&MTVI = MaterializedTemporaryValues[E];
8734 MTVI = new (*this) APValue;
8738 return MaterializedTemporaryValues.lookup(E);
8741 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8742 const llvm::Triple &T = getTargetInfo().getTriple();
8743 if (!T.isOSDarwin())
8746 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8747 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8750 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8751 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8752 uint64_t Size = sizeChars.getQuantity();
8753 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8754 unsigned Align = alignChars.getQuantity();
8755 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8756 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8761 ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8762 ASTContext::ParentMapPointers::mapped_type U) {
8763 if (const auto *D = U.dyn_cast<const Decl *>())
8764 return ast_type_traits::DynTypedNode::create(*D);
8765 if (const auto *S = U.dyn_cast<const Stmt *>())
8766 return ast_type_traits::DynTypedNode::create(*S);
8767 return *U.get<ast_type_traits::DynTypedNode *>();
8770 /// Template specializations to abstract away from pointers and TypeLocs.
8772 template <typename T>
8773 ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8774 return ast_type_traits::DynTypedNode::create(*Node);
8777 ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8778 return ast_type_traits::DynTypedNode::create(Node);
8781 ast_type_traits::DynTypedNode
8782 createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8783 return ast_type_traits::DynTypedNode::create(Node);
8787 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8788 /// parents as defined by the \c RecursiveASTVisitor.
8790 /// Note that the relationship described here is purely in terms of AST
8791 /// traversal - there are other relationships (for example declaration context)
8792 /// in the AST that are better modeled by special matchers.
8794 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8795 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8797 /// \brief Builds and returns the translation unit's parent map.
8799 /// The caller takes ownership of the returned \c ParentMap.
8800 static std::pair<ASTContext::ParentMapPointers *,
8801 ASTContext::ParentMapOtherNodes *>
8802 buildMap(TranslationUnitDecl &TU) {
8803 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8804 new ASTContext::ParentMapOtherNodes);
8805 Visitor.TraverseDecl(&TU);
8806 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
8810 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8812 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
8813 ASTContext::ParentMapOtherNodes *OtherParents)
8814 : Parents(Parents), OtherParents(OtherParents) {}
8816 bool shouldVisitTemplateInstantiations() const {
8819 bool shouldVisitImplicitCode() const {
8823 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
8825 bool TraverseNode(T Node, MapNodeTy MapNode,
8826 BaseTraverseFn BaseTraverse, MapTy *Parents) {
8829 if (ParentStack.size() > 0) {
8830 // FIXME: Currently we add the same parent multiple times, but only
8831 // when no memoization data is available for the type.
8832 // For example when we visit all subexpressions of template
8833 // instantiations; this is suboptimal, but benign: the only way to
8834 // visit those is with hasAncestor / hasParent, and those do not create
8836 // The plan is to enable DynTypedNode to be storable in a map or hash
8837 // map. The main problem there is to implement hash functions /
8838 // comparison operators for all types that DynTypedNode supports that
8839 // do not have pointer identity.
8840 auto &NodeOrVector = (*Parents)[MapNode];
8841 if (NodeOrVector.isNull()) {
8842 if (const auto *D = ParentStack.back().get<Decl>())
8844 else if (const auto *S = ParentStack.back().get<Stmt>())
8848 new ast_type_traits::DynTypedNode(ParentStack.back());
8850 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
8851 auto *Vector = new ASTContext::ParentVector(
8852 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
8855 .template dyn_cast<ast_type_traits::DynTypedNode *>())
8857 NodeOrVector = Vector;
8861 NodeOrVector.template get<ASTContext::ParentVector *>();
8862 // Skip duplicates for types that have memoization data.
8863 // We must check that the type has memoization data before calling
8864 // std::find() because DynTypedNode::operator== can't compare all
8866 bool Found = ParentStack.back().getMemoizationData() &&
8867 std::find(Vector->begin(), Vector->end(),
8868 ParentStack.back()) != Vector->end();
8870 Vector->push_back(ParentStack.back());
8873 ParentStack.push_back(createDynTypedNode(Node));
8874 bool Result = BaseTraverse();
8875 ParentStack.pop_back();
8879 bool TraverseDecl(Decl *DeclNode) {
8880 return TraverseNode(DeclNode, DeclNode,
8881 [&] { return VisitorBase::TraverseDecl(DeclNode); },
8885 bool TraverseStmt(Stmt *StmtNode) {
8886 return TraverseNode(StmtNode, StmtNode,
8887 [&] { return VisitorBase::TraverseStmt(StmtNode); },
8891 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
8892 return TraverseNode(
8893 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
8894 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
8898 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
8899 return TraverseNode(
8900 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
8902 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
8907 ASTContext::ParentMapPointers *Parents;
8908 ASTContext::ParentMapOtherNodes *OtherParents;
8909 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8911 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8914 } // anonymous namespace
8916 template <typename NodeTy, typename MapTy>
8917 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
8919 auto I = Map.find(Node);
8920 if (I == Map.end()) {
8921 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
8923 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
8924 return llvm::makeArrayRef(*V);
8926 return getSingleDynTypedNodeFromParentMap(I->second);
8929 ASTContext::DynTypedNodeList
8930 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8931 if (!PointerParents) {
8932 // We always need to run over the whole translation unit, as
8933 // hasAncestor can escape any subtree.
8934 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
8935 PointerParents.reset(Maps.first);
8936 OtherParents.reset(Maps.second);
8938 if (Node.getNodeKind().hasPointerIdentity())
8939 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
8940 return getDynNodeFromMap(Node, *OtherParents);
8944 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8945 const ObjCMethodDecl *MethodImpl) {
8946 // No point trying to match an unavailable/deprecated mothod.
8947 if (MethodDecl->hasAttr<UnavailableAttr>()
8948 || MethodDecl->hasAttr<DeprecatedAttr>())
8950 if (MethodDecl->getObjCDeclQualifier() !=
8951 MethodImpl->getObjCDeclQualifier())
8953 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
8956 if (MethodDecl->param_size() != MethodImpl->param_size())
8959 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8960 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8961 EF = MethodDecl->param_end();
8962 IM != EM && IF != EF; ++IM, ++IF) {
8963 const ParmVarDecl *DeclVar = (*IF);
8964 const ParmVarDecl *ImplVar = (*IM);
8965 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8967 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8970 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8974 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8975 // doesn't include ASTContext.h
8977 clang::LazyGenerationalUpdatePtr<
8978 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8979 clang::LazyGenerationalUpdatePtr<
8980 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8981 const clang::ASTContext &Ctx, Decl *Value);