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/StringExtras.h"
38 #include "llvm/ADT/Triple.h"
39 #include "llvm/Support/Capacity.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
44 using namespace clang;
46 unsigned ASTContext::NumImplicitDefaultConstructors;
47 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
48 unsigned ASTContext::NumImplicitCopyConstructors;
49 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
50 unsigned ASTContext::NumImplicitMoveConstructors;
51 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
52 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
54 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
56 unsigned ASTContext::NumImplicitDestructors;
57 unsigned ASTContext::NumImplicitDestructorsDeclared;
60 HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
63 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
64 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
73 CommentsLoaded = true;
78 // User can not attach documentation to implicit declarations.
82 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
88 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
99 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
121 // TODO: we could look up template parameter documentation in the template
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
128 ArrayRef<RawComment *> RawComments = Comments.getComments();
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
142 isa<ObjCPropertyDecl>(D) ||
143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
145 DeclLoc = D->getLocStart();
147 DeclLoc = D->getLocation();
148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
172 // Find the comment that occurs just after this declaration.
173 ArrayRef<RawComment *>::iterator Comment;
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
200 // Decompose the location for the declaration and find the beginning of the
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
209 std::pair<FileID, unsigned> CommentBeginDecomp
210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
227 // Check that we actually have a non-member Doxygen comment.
228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
235 // If the comment and the declaration aren't in the same file, then they
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
253 if (Text.find_first_of(";{}#@") != StringRef::npos)
260 /// If we have a 'templated' declaration for a template, adjust 'D' to
261 /// refer to the actual template.
262 /// If we have an implicit instantiation, adjust 'D' to refer to template.
263 const Decl *adjustDeclToTemplate(const Decl *D) {
264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
265 // Is this function declaration part of a function template?
266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
298 // Class is an implicit instantiation of a class template or partial
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
327 // FIXME: Adjust alias templates?
330 } // anonymous namespace
332 const RawComment *ASTContext::getRawCommentForAnyRedecl(
334 const Decl **OriginalDecl) const {
335 D = adjustDeclToTemplate(D);
337 // Check whether we have cached a comment for this declaration already.
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
345 *OriginalDecl = Raw.getOriginalDecl();
351 // Search for comments attached to declarations in the redeclaration chain.
352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
354 for (auto I : D->redecls()) {
355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
356 RedeclComments.find(I);
357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
361 OriginalDeclForRC = Raw.getOriginalDecl();
365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
367 RawCommentAndCacheFlags Raw;
369 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
370 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
371 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
374 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
375 Raw.setOriginalDecl(I);
376 RedeclComments[I] = Raw;
382 // If we found a comment, it should be a documentation comment.
383 assert(!RC || RC->isDocumentation());
386 *OriginalDecl = OriginalDeclForRC;
388 // Update cache for every declaration in the redeclaration chain.
389 RawCommentAndCacheFlags Raw;
391 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
392 Raw.setOriginalDecl(OriginalDeclForRC);
394 for (auto I : D->redecls()) {
395 RawCommentAndCacheFlags &R = RedeclComments[I];
396 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
403 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
404 SmallVectorImpl<const NamedDecl *> &Redeclared) {
405 const DeclContext *DC = ObjCMethod->getDeclContext();
406 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
407 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
410 // Add redeclared method here.
411 for (const auto *Ext : ID->known_extensions()) {
412 if (ObjCMethodDecl *RedeclaredMethod =
413 Ext->getMethod(ObjCMethod->getSelector(),
414 ObjCMethod->isInstanceMethod()))
415 Redeclared.push_back(RedeclaredMethod);
420 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
421 const Decl *D) const {
422 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
423 ThisDeclInfo->CommentDecl = D;
424 ThisDeclInfo->IsFilled = false;
425 ThisDeclInfo->fill();
426 ThisDeclInfo->CommentDecl = FC->getDecl();
427 if (!ThisDeclInfo->TemplateParameters)
428 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
429 comments::FullComment *CFC =
430 new (*this) comments::FullComment(FC->getBlocks(),
435 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
436 const RawComment *RC = getRawCommentForDeclNoCache(D);
437 return RC ? RC->parse(*this, nullptr, D) : nullptr;
440 comments::FullComment *ASTContext::getCommentForDecl(
442 const Preprocessor *PP) const {
443 if (D->isInvalidDecl())
445 D = adjustDeclToTemplate(D);
447 const Decl *Canonical = D->getCanonicalDecl();
448 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
449 ParsedComments.find(Canonical);
451 if (Pos != ParsedComments.end()) {
452 if (Canonical != D) {
453 comments::FullComment *FC = Pos->second;
454 comments::FullComment *CFC = cloneFullComment(FC, D);
460 const Decl *OriginalDecl;
462 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
464 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
465 SmallVector<const NamedDecl*, 8> Overridden;
466 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
467 if (OMD && OMD->isPropertyAccessor())
468 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
469 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
470 return cloneFullComment(FC, D);
472 addRedeclaredMethods(OMD, Overridden);
473 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
474 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
475 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
476 return cloneFullComment(FC, D);
478 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
479 // Attach any tag type's documentation to its typedef if latter
480 // does not have one of its own.
481 QualType QT = TD->getUnderlyingType();
482 if (const TagType *TT = QT->getAs<TagType>())
483 if (const Decl *TD = TT->getDecl())
484 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
485 return cloneFullComment(FC, D);
487 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
488 while (IC->getSuperClass()) {
489 IC = IC->getSuperClass();
490 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
491 return cloneFullComment(FC, D);
494 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
495 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
496 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
497 return cloneFullComment(FC, D);
499 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
500 if (!(RD = RD->getDefinition()))
502 // Check non-virtual bases.
503 for (const auto &I : RD->bases()) {
504 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
506 QualType Ty = I.getType();
509 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
510 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
513 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
514 return cloneFullComment(FC, D);
517 // Check virtual bases.
518 for (const auto &I : RD->vbases()) {
519 if (I.getAccessSpecifier() != AS_public)
521 QualType Ty = I.getType();
524 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
525 if (!(VirtualBase= VirtualBase->getDefinition()))
527 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
528 return cloneFullComment(FC, D);
535 // If the RawComment was attached to other redeclaration of this Decl, we
536 // should parse the comment in context of that other Decl. This is important
537 // because comments can contain references to parameter names which can be
538 // different across redeclarations.
539 if (D != OriginalDecl)
540 return getCommentForDecl(OriginalDecl, PP);
542 comments::FullComment *FC = RC->parse(*this, PP, D);
543 ParsedComments[Canonical] = FC;
548 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
549 TemplateTemplateParmDecl *Parm) {
550 ID.AddInteger(Parm->getDepth());
551 ID.AddInteger(Parm->getPosition());
552 ID.AddBoolean(Parm->isParameterPack());
554 TemplateParameterList *Params = Parm->getTemplateParameters();
555 ID.AddInteger(Params->size());
556 for (TemplateParameterList::const_iterator P = Params->begin(),
557 PEnd = Params->end();
559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
561 ID.AddBoolean(TTP->isParameterPack());
565 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
567 ID.AddBoolean(NTTP->isParameterPack());
568 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
569 if (NTTP->isExpandedParameterPack()) {
571 ID.AddInteger(NTTP->getNumExpansionTypes());
572 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
573 QualType T = NTTP->getExpansionType(I);
574 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
577 ID.AddBoolean(false);
581 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
587 TemplateTemplateParmDecl *
588 ASTContext::getCanonicalTemplateTemplateParmDecl(
589 TemplateTemplateParmDecl *TTP) const {
590 // Check if we already have a canonical template template parameter.
591 llvm::FoldingSetNodeID ID;
592 CanonicalTemplateTemplateParm::Profile(ID, TTP);
593 void *InsertPos = nullptr;
594 CanonicalTemplateTemplateParm *Canonical
595 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
597 return Canonical->getParam();
599 // Build a canonical template parameter list.
600 TemplateParameterList *Params = TTP->getTemplateParameters();
601 SmallVector<NamedDecl *, 4> CanonParams;
602 CanonParams.reserve(Params->size());
603 for (TemplateParameterList::const_iterator P = Params->begin(),
604 PEnd = Params->end();
606 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
607 CanonParams.push_back(
608 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
612 TTP->getIndex(), nullptr, false,
613 TTP->isParameterPack()));
614 else if (NonTypeTemplateParmDecl *NTTP
615 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
616 QualType T = getCanonicalType(NTTP->getType());
617 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
618 NonTypeTemplateParmDecl *Param;
619 if (NTTP->isExpandedParameterPack()) {
620 SmallVector<QualType, 2> ExpandedTypes;
621 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
623 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
624 ExpandedTInfos.push_back(
625 getTrivialTypeSourceInfo(ExpandedTypes.back()));
628 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
632 NTTP->getPosition(), nullptr,
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
642 NTTP->getPosition(), nullptr,
644 NTTP->isParameterPack(),
647 CanonParams.push_back(Param);
650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
654 assert(!TTP->getRequiresClause() &&
655 "Unexpected requires-clause on template template-parameter");
656 Expr *const CanonRequiresClause = nullptr;
658 TemplateTemplateParmDecl *CanonTTP
659 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
660 SourceLocation(), TTP->getDepth(),
662 TTP->isParameterPack(),
664 TemplateParameterList::Create(*this, SourceLocation(),
668 CanonRequiresClause));
670 // Get the new insert position for the node we care about.
671 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
672 assert(!Canonical && "Shouldn't be in the map!");
675 // Create the canonical template template parameter entry.
676 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
677 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
681 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
682 if (!LangOpts.CPlusPlus) return nullptr;
684 switch (T.getCXXABI().getKind()) {
685 case TargetCXXABI::GenericARM: // Same as Itanium at this level
686 case TargetCXXABI::iOS:
687 case TargetCXXABI::iOS64:
688 case TargetCXXABI::WatchOS:
689 case TargetCXXABI::GenericAArch64:
690 case TargetCXXABI::GenericMIPS:
691 case TargetCXXABI::GenericItanium:
692 case TargetCXXABI::WebAssembly:
693 return CreateItaniumCXXABI(*this);
694 case TargetCXXABI::Microsoft:
695 return CreateMicrosoftCXXABI(*this);
697 llvm_unreachable("Invalid CXXABI type!");
700 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
701 const LangOptions &LOpts) {
702 if (LOpts.FakeAddressSpaceMap) {
703 // The fake address space map must have a distinct entry for each
704 // language-specific address space.
705 static const unsigned FakeAddrSpaceMap[] = {
709 2, // opencl_constant
715 return &FakeAddrSpaceMap;
717 return &T.getAddressSpaceMap();
721 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
722 const LangOptions &LangOpts) {
723 switch (LangOpts.getAddressSpaceMapMangling()) {
724 case LangOptions::ASMM_Target:
725 return TI.useAddressSpaceMapMangling();
726 case LangOptions::ASMM_On:
728 case LangOptions::ASMM_Off:
731 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
734 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
735 IdentifierTable &idents, SelectorTable &sels,
736 Builtin::Context &builtins)
737 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
738 DependentTemplateSpecializationTypes(this_()),
739 SubstTemplateTemplateParmPacks(this_()),
740 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
741 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
742 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
743 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
744 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
745 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
746 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
747 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
748 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
749 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
750 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
751 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
752 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
753 LangOpts.XRayNeverInstrumentFiles, SM)),
754 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
755 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
756 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
757 Listener(nullptr), Comments(SM), CommentsLoaded(false),
758 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
759 TUDecl = TranslationUnitDecl::Create(*this);
762 ASTContext::~ASTContext() {
763 ReleaseParentMapEntries();
765 // Release the DenseMaps associated with DeclContext objects.
766 // FIXME: Is this the ideal solution?
767 ReleaseDeclContextMaps();
769 // Call all of the deallocation functions on all of their targets.
770 for (auto &Pair : Deallocations)
771 (Pair.first)(Pair.second);
773 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
774 // because they can contain DenseMaps.
775 for (llvm::DenseMap<const ObjCContainerDecl*,
776 const ASTRecordLayout*>::iterator
777 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
778 // Increment in loop to prevent using deallocated memory.
779 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
782 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
783 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
784 // Increment in loop to prevent using deallocated memory.
785 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
789 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
790 AEnd = DeclAttrs.end();
792 A->second->~AttrVec();
794 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
795 MaterializedTemporaryValues)
796 MTVPair.second->~APValue();
798 for (const auto &Value : ModuleInitializers)
799 Value.second->~PerModuleInitializers();
802 void ASTContext::ReleaseParentMapEntries() {
803 if (!PointerParents) return;
804 for (const auto &Entry : *PointerParents) {
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 *>();
811 for (const auto &Entry : *OtherParents) {
812 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
813 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
814 } else if (Entry.second.is<ParentVector *>()) {
815 delete Entry.second.get<ParentVector *>();
820 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
821 Deallocations.push_back({Callback, Data});
825 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
826 ExternalSource = std::move(Source);
829 void ASTContext::PrintStats() const {
830 llvm::errs() << "\n*** AST Context Stats:\n";
831 llvm::errs() << " " << Types.size() << " types total.\n";
833 unsigned counts[] = {
834 #define TYPE(Name, Parent) 0,
835 #define ABSTRACT_TYPE(Name, Parent)
836 #include "clang/AST/TypeNodes.def"
840 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
842 counts[(unsigned)T->getTypeClass()]++;
846 unsigned TotalBytes = 0;
847 #define TYPE(Name, Parent) \
849 llvm::errs() << " " << counts[Idx] << " " << #Name \
851 TotalBytes += counts[Idx] * sizeof(Name##Type); \
853 #define ABSTRACT_TYPE(Name, Parent)
854 #include "clang/AST/TypeNodes.def"
856 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
858 // Implicit special member functions.
859 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
860 << NumImplicitDefaultConstructors
861 << " implicit default constructors created\n";
862 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
863 << NumImplicitCopyConstructors
864 << " implicit copy constructors created\n";
865 if (getLangOpts().CPlusPlus)
866 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
867 << NumImplicitMoveConstructors
868 << " implicit move constructors created\n";
869 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
870 << NumImplicitCopyAssignmentOperators
871 << " implicit copy assignment operators created\n";
872 if (getLangOpts().CPlusPlus)
873 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
874 << NumImplicitMoveAssignmentOperators
875 << " implicit move assignment operators created\n";
876 llvm::errs() << NumImplicitDestructorsDeclared << "/"
877 << NumImplicitDestructors
878 << " implicit destructors created\n";
880 if (ExternalSource) {
881 llvm::errs() << "\n";
882 ExternalSource->PrintStats();
885 BumpAlloc.PrintStats();
888 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
889 bool NotifyListeners) {
891 if (auto *Listener = getASTMutationListener())
892 Listener->RedefinedHiddenDefinition(ND, M);
894 if (getLangOpts().ModulesLocalVisibility)
895 MergedDefModules[ND].push_back(M);
897 ND->setHidden(false);
900 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
901 auto It = MergedDefModules.find(ND);
902 if (It == MergedDefModules.end())
905 auto &Merged = It->second;
906 llvm::DenseSet<Module*> Found;
907 for (Module *&M : Merged)
908 if (!Found.insert(M).second)
910 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
913 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
914 if (LazyInitializers.empty())
917 auto *Source = Ctx.getExternalSource();
918 assert(Source && "lazy initializers but no external source");
920 auto LazyInits = std::move(LazyInitializers);
921 LazyInitializers.clear();
923 for (auto ID : LazyInits)
924 Initializers.push_back(Source->GetExternalDecl(ID));
926 assert(LazyInitializers.empty() &&
927 "GetExternalDecl for lazy module initializer added more inits");
930 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
931 // One special case: if we add a module initializer that imports another
932 // module, and that module's only initializer is an ImportDecl, simplify.
933 if (auto *ID = dyn_cast<ImportDecl>(D)) {
934 auto It = ModuleInitializers.find(ID->getImportedModule());
936 // Maybe the ImportDecl does nothing at all. (Common case.)
937 if (It == ModuleInitializers.end())
940 // Maybe the ImportDecl only imports another ImportDecl.
941 auto &Imported = *It->second;
942 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
943 Imported.resolve(*this);
944 auto *OnlyDecl = Imported.Initializers.front();
945 if (isa<ImportDecl>(OnlyDecl))
950 auto *&Inits = ModuleInitializers[M];
952 Inits = new (*this) PerModuleInitializers;
953 Inits->Initializers.push_back(D);
956 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
957 auto *&Inits = ModuleInitializers[M];
959 Inits = new (*this) PerModuleInitializers;
960 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
961 IDs.begin(), IDs.end());
964 ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
965 auto It = ModuleInitializers.find(M);
966 if (It == ModuleInitializers.end())
969 auto *Inits = It->second;
970 Inits->resolve(*this);
971 return Inits->Initializers;
974 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
976 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
978 return ExternCContext;
981 BuiltinTemplateDecl *
982 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
983 const IdentifierInfo *II) const {
984 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
985 BuiltinTemplate->setImplicit();
986 TUDecl->addDecl(BuiltinTemplate);
988 return BuiltinTemplate;
991 BuiltinTemplateDecl *
992 ASTContext::getMakeIntegerSeqDecl() const {
993 if (!MakeIntegerSeqDecl)
994 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
995 getMakeIntegerSeqName());
996 return MakeIntegerSeqDecl;
999 BuiltinTemplateDecl *
1000 ASTContext::getTypePackElementDecl() const {
1001 if (!TypePackElementDecl)
1002 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1003 getTypePackElementName());
1004 return TypePackElementDecl;
1007 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1008 RecordDecl::TagKind TK) const {
1010 RecordDecl *NewDecl;
1011 if (getLangOpts().CPlusPlus)
1012 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1013 Loc, &Idents.get(Name));
1015 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1017 NewDecl->setImplicit();
1018 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1019 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1023 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1024 StringRef Name) const {
1025 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1026 TypedefDecl *NewDecl = TypedefDecl::Create(
1027 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1028 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1029 NewDecl->setImplicit();
1033 TypedefDecl *ASTContext::getInt128Decl() const {
1035 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1039 TypedefDecl *ASTContext::getUInt128Decl() const {
1041 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1045 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1046 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
1047 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1048 Types.push_back(Ty);
1051 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1052 const TargetInfo *AuxTarget) {
1053 assert((!this->Target || this->Target == &Target) &&
1054 "Incorrect target reinitialization");
1055 assert(VoidTy.isNull() && "Context reinitialized?");
1057 this->Target = &Target;
1058 this->AuxTarget = AuxTarget;
1060 ABI.reset(createCXXABI(Target));
1061 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1062 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1065 InitBuiltinType(VoidTy, BuiltinType::Void);
1068 InitBuiltinType(BoolTy, BuiltinType::Bool);
1070 if (LangOpts.CharIsSigned)
1071 InitBuiltinType(CharTy, BuiltinType::Char_S);
1073 InitBuiltinType(CharTy, BuiltinType::Char_U);
1075 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1076 InitBuiltinType(ShortTy, BuiltinType::Short);
1077 InitBuiltinType(IntTy, BuiltinType::Int);
1078 InitBuiltinType(LongTy, BuiltinType::Long);
1079 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1082 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1083 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1084 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1085 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1086 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1089 InitBuiltinType(FloatTy, BuiltinType::Float);
1090 InitBuiltinType(DoubleTy, BuiltinType::Double);
1091 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1093 // GNU extension, __float128 for IEEE quadruple precision
1094 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1096 // GNU extension, 128-bit integers.
1097 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1098 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1101 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1102 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1103 else // -fshort-wchar makes wchar_t be unsigned.
1104 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1105 if (LangOpts.CPlusPlus && LangOpts.WChar)
1106 WideCharTy = WCharTy;
1108 // C99 (or C++ using -fno-wchar).
1109 WideCharTy = getFromTargetType(Target.getWCharType());
1112 WIntTy = getFromTargetType(Target.getWIntType());
1114 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1115 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1117 Char16Ty = getFromTargetType(Target.getChar16Type());
1119 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1120 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1122 Char32Ty = getFromTargetType(Target.getChar32Type());
1124 // Placeholder type for type-dependent expressions whose type is
1125 // completely unknown. No code should ever check a type against
1126 // DependentTy and users should never see it; however, it is here to
1127 // help diagnose failures to properly check for type-dependent
1129 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1131 // Placeholder type for functions.
1132 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1134 // Placeholder type for bound members.
1135 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1137 // Placeholder type for pseudo-objects.
1138 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1140 // "any" type; useful for debugger-like clients.
1141 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1143 // Placeholder type for unbridged ARC casts.
1144 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1146 // Placeholder type for builtin functions.
1147 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1149 // Placeholder type for OMP array sections.
1150 if (LangOpts.OpenMP)
1151 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1154 FloatComplexTy = getComplexType(FloatTy);
1155 DoubleComplexTy = getComplexType(DoubleTy);
1156 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1157 Float128ComplexTy = getComplexType(Float128Ty);
1159 // Builtin types for 'id', 'Class', and 'SEL'.
1160 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1161 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1162 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1164 if (LangOpts.OpenCL) {
1165 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1166 InitBuiltinType(SingletonId, BuiltinType::Id);
1167 #include "clang/Basic/OpenCLImageTypes.def"
1169 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1170 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1171 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1172 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1173 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1176 // Builtin type for __objc_yes and __objc_no
1177 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1178 SignedCharTy : BoolTy);
1180 ObjCConstantStringType = QualType();
1182 ObjCSuperType = QualType();
1185 VoidPtrTy = getPointerType(VoidTy);
1187 // nullptr type (C++0x 2.14.7)
1188 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1190 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1191 InitBuiltinType(HalfTy, BuiltinType::Half);
1193 // Builtin type used to help define __builtin_va_list.
1194 VaListTagDecl = nullptr;
1197 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1198 return SourceMgr.getDiagnostics();
1201 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1202 AttrVec *&Result = DeclAttrs[D];
1204 void *Mem = Allocate(sizeof(AttrVec));
1205 Result = new (Mem) AttrVec;
1211 /// \brief Erase the attributes corresponding to the given declaration.
1212 void ASTContext::eraseDeclAttrs(const Decl *D) {
1213 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1214 if (Pos != DeclAttrs.end()) {
1215 Pos->second->~AttrVec();
1216 DeclAttrs.erase(Pos);
1221 MemberSpecializationInfo *
1222 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1223 assert(Var->isStaticDataMember() && "Not a static data member");
1224 return getTemplateOrSpecializationInfo(Var)
1225 .dyn_cast<MemberSpecializationInfo *>();
1228 ASTContext::TemplateOrSpecializationInfo
1229 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1230 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1231 TemplateOrInstantiation.find(Var);
1232 if (Pos == TemplateOrInstantiation.end())
1233 return TemplateOrSpecializationInfo();
1239 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1240 TemplateSpecializationKind TSK,
1241 SourceLocation PointOfInstantiation) {
1242 assert(Inst->isStaticDataMember() && "Not a static data member");
1243 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1244 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1245 Tmpl, TSK, PointOfInstantiation));
1249 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1250 TemplateOrSpecializationInfo TSI) {
1251 assert(!TemplateOrInstantiation[Inst] &&
1252 "Already noted what the variable was instantiated from");
1253 TemplateOrInstantiation[Inst] = TSI;
1256 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1257 const FunctionDecl *FD){
1258 assert(FD && "Specialization is 0");
1259 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1260 = ClassScopeSpecializationPattern.find(FD);
1261 if (Pos == ClassScopeSpecializationPattern.end())
1267 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1268 FunctionDecl *Pattern) {
1269 assert(FD && "Specialization is 0");
1270 assert(Pattern && "Class scope specialization pattern is 0");
1271 ClassScopeSpecializationPattern[FD] = Pattern;
1275 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1276 auto Pos = InstantiatedFromUsingDecl.find(UUD);
1277 if (Pos == InstantiatedFromUsingDecl.end())
1284 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1285 assert((isa<UsingDecl>(Pattern) ||
1286 isa<UnresolvedUsingValueDecl>(Pattern) ||
1287 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1288 "pattern decl is not a using decl");
1289 assert((isa<UsingDecl>(Inst) ||
1290 isa<UnresolvedUsingValueDecl>(Inst) ||
1291 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1292 "instantiation did not produce a using decl");
1293 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1294 InstantiatedFromUsingDecl[Inst] = Pattern;
1298 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1299 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1300 = InstantiatedFromUsingShadowDecl.find(Inst);
1301 if (Pos == InstantiatedFromUsingShadowDecl.end())
1308 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1309 UsingShadowDecl *Pattern) {
1310 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1311 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1314 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1315 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1316 = InstantiatedFromUnnamedFieldDecl.find(Field);
1317 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1323 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1325 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1326 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1327 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1328 "Already noted what unnamed field was instantiated from");
1330 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1333 ASTContext::overridden_cxx_method_iterator
1334 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1335 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1336 OverriddenMethods.find(Method->getCanonicalDecl());
1337 if (Pos == OverriddenMethods.end())
1339 return Pos->second.begin();
1342 ASTContext::overridden_cxx_method_iterator
1343 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1344 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1345 OverriddenMethods.find(Method->getCanonicalDecl());
1346 if (Pos == OverriddenMethods.end())
1348 return Pos->second.end();
1352 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1353 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1354 OverriddenMethods.find(Method->getCanonicalDecl());
1355 if (Pos == OverriddenMethods.end())
1357 return Pos->second.size();
1360 ASTContext::overridden_method_range
1361 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1362 return overridden_method_range(overridden_methods_begin(Method),
1363 overridden_methods_end(Method));
1366 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1367 const CXXMethodDecl *Overridden) {
1368 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1369 OverriddenMethods[Method].push_back(Overridden);
1372 void ASTContext::getOverriddenMethods(
1374 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1377 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1378 Overridden.append(overridden_methods_begin(CXXMethod),
1379 overridden_methods_end(CXXMethod));
1383 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1387 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1388 Method->getOverriddenMethods(OverDecls);
1389 Overridden.append(OverDecls.begin(), OverDecls.end());
1392 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1393 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1394 assert(!Import->isFromASTFile() && "Non-local import declaration");
1395 if (!FirstLocalImport) {
1396 FirstLocalImport = Import;
1397 LastLocalImport = Import;
1401 LastLocalImport->NextLocalImport = Import;
1402 LastLocalImport = Import;
1405 //===----------------------------------------------------------------------===//
1406 // Type Sizing and Analysis
1407 //===----------------------------------------------------------------------===//
1409 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1410 /// scalar floating point type.
1411 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1412 const BuiltinType *BT = T->getAs<BuiltinType>();
1413 assert(BT && "Not a floating point type!");
1414 switch (BT->getKind()) {
1415 default: llvm_unreachable("Not a floating point type!");
1416 case BuiltinType::Half: return Target->getHalfFormat();
1417 case BuiltinType::Float: return Target->getFloatFormat();
1418 case BuiltinType::Double: return Target->getDoubleFormat();
1419 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1420 case BuiltinType::Float128: return Target->getFloat128Format();
1424 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1425 unsigned Align = Target->getCharWidth();
1427 bool UseAlignAttrOnly = false;
1428 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1429 Align = AlignFromAttr;
1431 // __attribute__((aligned)) can increase or decrease alignment
1432 // *except* on a struct or struct member, where it only increases
1433 // alignment unless 'packed' is also specified.
1435 // It is an error for alignas to decrease alignment, so we can
1436 // ignore that possibility; Sema should diagnose it.
1437 if (isa<FieldDecl>(D)) {
1438 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1439 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1441 UseAlignAttrOnly = true;
1444 else if (isa<FieldDecl>(D))
1446 D->hasAttr<PackedAttr>() ||
1447 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1449 // If we're using the align attribute only, just ignore everything
1450 // else about the declaration and its type.
1451 if (UseAlignAttrOnly) {
1454 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1455 QualType T = VD->getType();
1456 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
1458 T = RT->getPointeeType();
1460 T = getPointerType(RT->getPointeeType());
1462 QualType BaseT = getBaseElementType(T);
1463 if (T->isFunctionType())
1464 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1465 else if (!BaseT->isIncompleteType()) {
1466 // Adjust alignments of declarations with array type by the
1467 // large-array alignment on the target.
1468 if (const ArrayType *arrayType = getAsArrayType(T)) {
1469 unsigned MinWidth = Target->getLargeArrayMinWidth();
1470 if (!ForAlignof && MinWidth) {
1471 if (isa<VariableArrayType>(arrayType))
1472 Align = std::max(Align, Target->getLargeArrayAlign());
1473 else if (isa<ConstantArrayType>(arrayType) &&
1474 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1475 Align = std::max(Align, Target->getLargeArrayAlign());
1478 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1479 if (BaseT.getQualifiers().hasUnaligned())
1480 Align = Target->getCharWidth();
1481 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1482 if (VD->hasGlobalStorage() && !ForAlignof)
1483 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1487 // Fields can be subject to extra alignment constraints, like if
1488 // the field is packed, the struct is packed, or the struct has a
1489 // a max-field-alignment constraint (#pragma pack). So calculate
1490 // the actual alignment of the field within the struct, and then
1491 // (as we're expected to) constrain that by the alignment of the type.
1492 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1493 const RecordDecl *Parent = Field->getParent();
1494 // We can only produce a sensible answer if the record is valid.
1495 if (!Parent->isInvalidDecl()) {
1496 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1498 // Start with the record's overall alignment.
1499 unsigned FieldAlign = toBits(Layout.getAlignment());
1501 // Use the GCD of that and the offset within the record.
1502 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1504 // Alignment is always a power of 2, so the GCD will be a power of 2,
1505 // which means we get to do this crazy thing instead of Euclid's.
1506 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1507 if (LowBitOfOffset < FieldAlign)
1508 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1511 Align = std::min(Align, FieldAlign);
1516 return toCharUnitsFromBits(Align);
1519 // getTypeInfoDataSizeInChars - Return the size of a type, in
1520 // chars. If the type is a record, its data size is returned. This is
1521 // the size of the memcpy that's performed when assigning this type
1522 // using a trivial copy/move assignment operator.
1523 std::pair<CharUnits, CharUnits>
1524 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1525 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1527 // In C++, objects can sometimes be allocated into the tail padding
1528 // of a base-class subobject. We decide whether that's possible
1529 // during class layout, so here we can just trust the layout results.
1530 if (getLangOpts().CPlusPlus) {
1531 if (const RecordType *RT = T->getAs<RecordType>()) {
1532 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1533 sizeAndAlign.first = layout.getDataSize();
1537 return sizeAndAlign;
1540 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1541 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1542 std::pair<CharUnits, CharUnits>
1543 static getConstantArrayInfoInChars(const ASTContext &Context,
1544 const ConstantArrayType *CAT) {
1545 std::pair<CharUnits, CharUnits> EltInfo =
1546 Context.getTypeInfoInChars(CAT->getElementType());
1547 uint64_t Size = CAT->getSize().getZExtValue();
1548 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1549 (uint64_t)(-1)/Size) &&
1550 "Overflow in array type char size evaluation");
1551 uint64_t Width = EltInfo.first.getQuantity() * Size;
1552 unsigned Align = EltInfo.second.getQuantity();
1553 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1554 Context.getTargetInfo().getPointerWidth(0) == 64)
1555 Width = llvm::alignTo(Width, Align);
1556 return std::make_pair(CharUnits::fromQuantity(Width),
1557 CharUnits::fromQuantity(Align));
1560 std::pair<CharUnits, CharUnits>
1561 ASTContext::getTypeInfoInChars(const Type *T) const {
1562 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1563 return getConstantArrayInfoInChars(*this, CAT);
1564 TypeInfo Info = getTypeInfo(T);
1565 return std::make_pair(toCharUnitsFromBits(Info.Width),
1566 toCharUnitsFromBits(Info.Align));
1569 std::pair<CharUnits, CharUnits>
1570 ASTContext::getTypeInfoInChars(QualType T) const {
1571 return getTypeInfoInChars(T.getTypePtr());
1574 bool ASTContext::isAlignmentRequired(const Type *T) const {
1575 return getTypeInfo(T).AlignIsRequired;
1578 bool ASTContext::isAlignmentRequired(QualType T) const {
1579 return isAlignmentRequired(T.getTypePtr());
1582 unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1583 // An alignment on a typedef overrides anything else.
1584 if (auto *TT = T->getAs<TypedefType>())
1585 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1588 // If we have an (array of) complete type, we're done.
1589 T = getBaseElementType(T);
1590 if (!T->isIncompleteType())
1591 return getTypeAlign(T);
1593 // If we had an array type, its element type might be a typedef
1594 // type with an alignment attribute.
1595 if (auto *TT = T->getAs<TypedefType>())
1596 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1599 // Otherwise, see if the declaration of the type had an attribute.
1600 if (auto *TT = T->getAs<TagType>())
1601 return TT->getDecl()->getMaxAlignment();
1606 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1607 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1608 if (I != MemoizedTypeInfo.end())
1611 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1612 TypeInfo TI = getTypeInfoImpl(T);
1613 MemoizedTypeInfo[T] = TI;
1617 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1618 /// method does not work on incomplete types.
1620 /// FIXME: Pointers into different addr spaces could have different sizes and
1621 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1622 /// should take a QualType, &c.
1623 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1626 bool AlignIsRequired = false;
1627 switch (T->getTypeClass()) {
1628 #define TYPE(Class, Base)
1629 #define ABSTRACT_TYPE(Class, Base)
1630 #define NON_CANONICAL_TYPE(Class, Base)
1631 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1632 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1634 assert(!T->isDependentType() && "should not see dependent types here"); \
1635 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1636 #include "clang/AST/TypeNodes.def"
1637 llvm_unreachable("Should not see dependent types");
1639 case Type::FunctionNoProto:
1640 case Type::FunctionProto:
1641 // GCC extension: alignof(function) = 32 bits
1646 case Type::IncompleteArray:
1647 case Type::VariableArray:
1649 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1652 case Type::ConstantArray: {
1653 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1655 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1656 uint64_t Size = CAT->getSize().getZExtValue();
1657 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1658 "Overflow in array type bit size evaluation");
1659 Width = EltInfo.Width * Size;
1660 Align = EltInfo.Align;
1661 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1662 getTargetInfo().getPointerWidth(0) == 64)
1663 Width = llvm::alignTo(Width, Align);
1666 case Type::ExtVector:
1667 case Type::Vector: {
1668 const VectorType *VT = cast<VectorType>(T);
1669 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1670 Width = EltInfo.Width * VT->getNumElements();
1672 // If the alignment is not a power of 2, round up to the next power of 2.
1673 // This happens for non-power-of-2 length vectors.
1674 if (Align & (Align-1)) {
1675 Align = llvm::NextPowerOf2(Align);
1676 Width = llvm::alignTo(Width, Align);
1678 // Adjust the alignment based on the target max.
1679 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1680 if (TargetVectorAlign && TargetVectorAlign < Align)
1681 Align = TargetVectorAlign;
1686 switch (cast<BuiltinType>(T)->getKind()) {
1687 default: llvm_unreachable("Unknown builtin type!");
1688 case BuiltinType::Void:
1689 // GCC extension: alignof(void) = 8 bits.
1694 case BuiltinType::Bool:
1695 Width = Target->getBoolWidth();
1696 Align = Target->getBoolAlign();
1698 case BuiltinType::Char_S:
1699 case BuiltinType::Char_U:
1700 case BuiltinType::UChar:
1701 case BuiltinType::SChar:
1702 Width = Target->getCharWidth();
1703 Align = Target->getCharAlign();
1705 case BuiltinType::WChar_S:
1706 case BuiltinType::WChar_U:
1707 Width = Target->getWCharWidth();
1708 Align = Target->getWCharAlign();
1710 case BuiltinType::Char16:
1711 Width = Target->getChar16Width();
1712 Align = Target->getChar16Align();
1714 case BuiltinType::Char32:
1715 Width = Target->getChar32Width();
1716 Align = Target->getChar32Align();
1718 case BuiltinType::UShort:
1719 case BuiltinType::Short:
1720 Width = Target->getShortWidth();
1721 Align = Target->getShortAlign();
1723 case BuiltinType::UInt:
1724 case BuiltinType::Int:
1725 Width = Target->getIntWidth();
1726 Align = Target->getIntAlign();
1728 case BuiltinType::ULong:
1729 case BuiltinType::Long:
1730 Width = Target->getLongWidth();
1731 Align = Target->getLongAlign();
1733 case BuiltinType::ULongLong:
1734 case BuiltinType::LongLong:
1735 Width = Target->getLongLongWidth();
1736 Align = Target->getLongLongAlign();
1738 case BuiltinType::Int128:
1739 case BuiltinType::UInt128:
1741 Align = 128; // int128_t is 128-bit aligned on all targets.
1743 case BuiltinType::Half:
1744 Width = Target->getHalfWidth();
1745 Align = Target->getHalfAlign();
1747 case BuiltinType::Float:
1748 Width = Target->getFloatWidth();
1749 Align = Target->getFloatAlign();
1751 case BuiltinType::Double:
1752 Width = Target->getDoubleWidth();
1753 Align = Target->getDoubleAlign();
1755 case BuiltinType::LongDouble:
1756 Width = Target->getLongDoubleWidth();
1757 Align = Target->getLongDoubleAlign();
1759 case BuiltinType::Float128:
1760 Width = Target->getFloat128Width();
1761 Align = Target->getFloat128Align();
1763 case BuiltinType::NullPtr:
1764 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1765 Align = Target->getPointerAlign(0); // == sizeof(void*)
1767 case BuiltinType::ObjCId:
1768 case BuiltinType::ObjCClass:
1769 case BuiltinType::ObjCSel:
1770 Width = Target->getPointerWidth(0);
1771 Align = Target->getPointerAlign(0);
1773 case BuiltinType::OCLSampler: {
1774 auto AS = getTargetAddressSpace(LangAS::opencl_constant);
1775 Width = Target->getPointerWidth(AS);
1776 Align = Target->getPointerAlign(AS);
1779 case BuiltinType::OCLEvent:
1780 case BuiltinType::OCLClkEvent:
1781 case BuiltinType::OCLQueue:
1782 case BuiltinType::OCLReserveID:
1783 // Currently these types are pointers to opaque types.
1784 Width = Target->getPointerWidth(0);
1785 Align = Target->getPointerAlign(0);
1787 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1788 case BuiltinType::Id:
1789 #include "clang/Basic/OpenCLImageTypes.def"
1791 auto AS = getTargetAddressSpace(Target->getOpenCLImageAddrSpace());
1792 Width = Target->getPointerWidth(AS);
1793 Align = Target->getPointerAlign(AS);
1797 case Type::ObjCObjectPointer:
1798 Width = Target->getPointerWidth(0);
1799 Align = Target->getPointerAlign(0);
1801 case Type::BlockPointer: {
1802 unsigned AS = getTargetAddressSpace(
1803 cast<BlockPointerType>(T)->getPointeeType());
1804 Width = Target->getPointerWidth(AS);
1805 Align = Target->getPointerAlign(AS);
1808 case Type::LValueReference:
1809 case Type::RValueReference: {
1810 // alignof and sizeof should never enter this code path here, so we go
1811 // the pointer route.
1812 unsigned AS = getTargetAddressSpace(
1813 cast<ReferenceType>(T)->getPointeeType());
1814 Width = Target->getPointerWidth(AS);
1815 Align = Target->getPointerAlign(AS);
1818 case Type::Pointer: {
1819 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1820 Width = Target->getPointerWidth(AS);
1821 Align = Target->getPointerAlign(AS);
1824 case Type::MemberPointer: {
1825 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1826 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1829 case Type::Complex: {
1830 // Complex types have the same alignment as their elements, but twice the
1832 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1833 Width = EltInfo.Width * 2;
1834 Align = EltInfo.Align;
1837 case Type::ObjCObject:
1838 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1839 case Type::Adjusted:
1841 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1842 case Type::ObjCInterface: {
1843 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1844 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1845 Width = toBits(Layout.getSize());
1846 Align = toBits(Layout.getAlignment());
1851 const TagType *TT = cast<TagType>(T);
1853 if (TT->getDecl()->isInvalidDecl()) {
1859 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1860 const EnumDecl *ED = ET->getDecl();
1862 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1863 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1864 Info.Align = AttrAlign;
1865 Info.AlignIsRequired = true;
1870 const RecordType *RT = cast<RecordType>(TT);
1871 const RecordDecl *RD = RT->getDecl();
1872 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
1873 Width = toBits(Layout.getSize());
1874 Align = toBits(Layout.getAlignment());
1875 AlignIsRequired = RD->hasAttr<AlignedAttr>();
1879 case Type::SubstTemplateTypeParm:
1880 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1881 getReplacementType().getTypePtr());
1884 case Type::DeducedTemplateSpecialization: {
1885 const DeducedType *A = cast<DeducedType>(T);
1886 assert(!A->getDeducedType().isNull() &&
1887 "cannot request the size of an undeduced or dependent auto type");
1888 return getTypeInfo(A->getDeducedType().getTypePtr());
1892 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1894 case Type::ObjCTypeParam:
1895 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1897 case Type::Typedef: {
1898 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1899 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1900 // If the typedef has an aligned attribute on it, it overrides any computed
1901 // alignment we have. This violates the GCC documentation (which says that
1902 // attribute(aligned) can only round up) but matches its implementation.
1903 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
1905 AlignIsRequired = true;
1908 AlignIsRequired = Info.AlignIsRequired;
1914 case Type::Elaborated:
1915 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1917 case Type::Attributed:
1919 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1921 case Type::Atomic: {
1922 // Start with the base type information.
1923 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1927 // If the size of the type doesn't exceed the platform's max
1928 // atomic promotion width, make the size and alignment more
1929 // favorable to atomic operations:
1930 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1931 // Round the size up to a power of 2.
1932 if (!llvm::isPowerOf2_64(Width))
1933 Width = llvm::NextPowerOf2(Width);
1935 // Set the alignment equal to the size.
1936 Align = static_cast<unsigned>(Width);
1942 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1949 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1950 return TypeInfo(Width, Align, AlignIsRequired);
1953 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1954 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1955 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1956 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1957 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1958 getTargetInfo().getABI() == "elfv1-qpx" &&
1959 T->isSpecificBuiltinType(BuiltinType::Double))
1964 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1965 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1966 return CharUnits::fromQuantity(BitSize / getCharWidth());
1969 /// toBits - Convert a size in characters to a size in characters.
1970 int64_t ASTContext::toBits(CharUnits CharSize) const {
1971 return CharSize.getQuantity() * getCharWidth();
1974 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1975 /// This method does not work on incomplete types.
1976 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1977 return getTypeInfoInChars(T).first;
1979 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1980 return getTypeInfoInChars(T).first;
1983 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1984 /// characters. This method does not work on incomplete types.
1985 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1986 return toCharUnitsFromBits(getTypeAlign(T));
1988 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1989 return toCharUnitsFromBits(getTypeAlign(T));
1992 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1993 /// type for the current target in bits. This can be different than the ABI
1994 /// alignment in cases where it is beneficial for performance to overalign
1996 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1997 TypeInfo TI = getTypeInfo(T);
1998 unsigned ABIAlign = TI.Align;
2000 T = T->getBaseElementTypeUnsafe();
2002 // The preferred alignment of member pointers is that of a pointer.
2003 if (T->isMemberPointerType())
2004 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2006 if (!Target->allowsLargerPreferedTypeAlignment())
2009 // Double and long long should be naturally aligned if possible.
2010 if (const ComplexType *CT = T->getAs<ComplexType>())
2011 T = CT->getElementType().getTypePtr();
2012 if (const EnumType *ET = T->getAs<EnumType>())
2013 T = ET->getDecl()->getIntegerType().getTypePtr();
2014 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2015 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2016 T->isSpecificBuiltinType(BuiltinType::ULongLong))
2017 // Don't increase the alignment if an alignment attribute was specified on a
2018 // typedef declaration.
2019 if (!TI.AlignIsRequired)
2020 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2025 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2026 /// for __attribute__((aligned)) on this target, to be used if no alignment
2027 /// value is specified.
2028 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2029 return getTargetInfo().getDefaultAlignForAttributeAligned();
2032 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2033 /// to a global variable of the specified type.
2034 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2035 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2038 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2039 /// should be given to a global variable of the specified type.
2040 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2041 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2044 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2045 CharUnits Offset = CharUnits::Zero();
2046 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2047 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2048 Offset += Layout->getBaseClassOffset(Base);
2049 Layout = &getASTRecordLayout(Base);
2054 /// DeepCollectObjCIvars -
2055 /// This routine first collects all declared, but not synthesized, ivars in
2056 /// super class and then collects all ivars, including those synthesized for
2057 /// current class. This routine is used for implementation of current class
2058 /// when all ivars, declared and synthesized are known.
2060 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2062 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2063 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2064 DeepCollectObjCIvars(SuperClass, false, Ivars);
2066 for (const auto *I : OI->ivars())
2069 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2070 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2071 Iv= Iv->getNextIvar())
2072 Ivars.push_back(Iv);
2076 /// CollectInheritedProtocols - Collect all protocols in current class and
2077 /// those inherited by it.
2078 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2079 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2080 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2081 // We can use protocol_iterator here instead of
2082 // all_referenced_protocol_iterator since we are walking all categories.
2083 for (auto *Proto : OI->all_referenced_protocols()) {
2084 CollectInheritedProtocols(Proto, Protocols);
2087 // Categories of this Interface.
2088 for (const auto *Cat : OI->visible_categories())
2089 CollectInheritedProtocols(Cat, Protocols);
2091 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2093 CollectInheritedProtocols(SD, Protocols);
2094 SD = SD->getSuperClass();
2096 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2097 for (auto *Proto : OC->protocols()) {
2098 CollectInheritedProtocols(Proto, Protocols);
2100 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2101 // Insert the protocol.
2102 if (!Protocols.insert(
2103 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2106 for (auto *Proto : OP->protocols())
2107 CollectInheritedProtocols(Proto, Protocols);
2111 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2113 // Count ivars declared in class extension.
2114 for (const auto *Ext : OI->known_extensions())
2115 count += Ext->ivar_size();
2117 // Count ivar defined in this class's implementation. This
2118 // includes synthesized ivars.
2119 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2120 count += ImplDecl->ivar_size();
2125 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2129 // nullptr_t is always treated as null.
2130 if (E->getType()->isNullPtrType()) return true;
2132 if (E->getType()->isAnyPointerType() &&
2133 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2134 Expr::NPC_ValueDependentIsNull))
2137 // Unfortunately, __null has type 'int'.
2138 if (isa<GNUNullExpr>(E)) return true;
2143 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2144 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2145 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2146 I = ObjCImpls.find(D);
2147 if (I != ObjCImpls.end())
2148 return cast<ObjCImplementationDecl>(I->second);
2151 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2152 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2153 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2154 I = ObjCImpls.find(D);
2155 if (I != ObjCImpls.end())
2156 return cast<ObjCCategoryImplDecl>(I->second);
2160 /// \brief Set the implementation of ObjCInterfaceDecl.
2161 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2162 ObjCImplementationDecl *ImplD) {
2163 assert(IFaceD && ImplD && "Passed null params");
2164 ObjCImpls[IFaceD] = ImplD;
2166 /// \brief Set the implementation of ObjCCategoryDecl.
2167 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2168 ObjCCategoryImplDecl *ImplD) {
2169 assert(CatD && ImplD && "Passed null params");
2170 ObjCImpls[CatD] = ImplD;
2173 const ObjCMethodDecl *
2174 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2175 return ObjCMethodRedecls.lookup(MD);
2178 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2179 const ObjCMethodDecl *Redecl) {
2180 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2181 ObjCMethodRedecls[MD] = Redecl;
2184 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2185 const NamedDecl *ND) const {
2186 if (const ObjCInterfaceDecl *ID =
2187 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2189 if (const ObjCCategoryDecl *CD =
2190 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2191 return CD->getClassInterface();
2192 if (const ObjCImplDecl *IMD =
2193 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2194 return IMD->getClassInterface();
2199 /// \brief Get the copy initialization expression of VarDecl,or NULL if
2201 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
2202 assert(VD && "Passed null params");
2203 assert(VD->hasAttr<BlocksAttr>() &&
2204 "getBlockVarCopyInits - not __block var");
2205 llvm::DenseMap<const VarDecl*, Expr*>::iterator
2206 I = BlockVarCopyInits.find(VD);
2207 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
2210 /// \brief Set the copy inialization expression of a block var decl.
2211 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2212 assert(VD && Init && "Passed null params");
2213 assert(VD->hasAttr<BlocksAttr>() &&
2214 "setBlockVarCopyInits - not __block var");
2215 BlockVarCopyInits[VD] = Init;
2218 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2219 unsigned DataSize) const {
2221 DataSize = TypeLoc::getFullDataSizeForType(T);
2223 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2224 "incorrect data size provided to CreateTypeSourceInfo!");
2226 TypeSourceInfo *TInfo =
2227 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2228 new (TInfo) TypeSourceInfo(T);
2232 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2233 SourceLocation L) const {
2234 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2235 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2239 const ASTRecordLayout &
2240 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2241 return getObjCLayout(D, nullptr);
2244 const ASTRecordLayout &
2245 ASTContext::getASTObjCImplementationLayout(
2246 const ObjCImplementationDecl *D) const {
2247 return getObjCLayout(D->getClassInterface(), D);
2250 //===----------------------------------------------------------------------===//
2251 // Type creation/memoization methods
2252 //===----------------------------------------------------------------------===//
2255 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2256 unsigned fastQuals = quals.getFastQualifiers();
2257 quals.removeFastQualifiers();
2259 // Check if we've already instantiated this type.
2260 llvm::FoldingSetNodeID ID;
2261 ExtQuals::Profile(ID, baseType, quals);
2262 void *insertPos = nullptr;
2263 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2264 assert(eq->getQualifiers() == quals);
2265 return QualType(eq, fastQuals);
2268 // If the base type is not canonical, make the appropriate canonical type.
2270 if (!baseType->isCanonicalUnqualified()) {
2271 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2272 canonSplit.Quals.addConsistentQualifiers(quals);
2273 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2275 // Re-find the insert position.
2276 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2279 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2280 ExtQualNodes.InsertNode(eq, insertPos);
2281 return QualType(eq, fastQuals);
2285 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2286 QualType CanT = getCanonicalType(T);
2287 if (CanT.getAddressSpace() == AddressSpace)
2290 // If we are composing extended qualifiers together, merge together
2291 // into one ExtQuals node.
2292 QualifierCollector Quals;
2293 const Type *TypeNode = Quals.strip(T);
2295 // If this type already has an address space specified, it cannot get
2297 assert(!Quals.hasAddressSpace() &&
2298 "Type cannot be in multiple addr spaces!");
2299 Quals.addAddressSpace(AddressSpace);
2301 return getExtQualType(TypeNode, Quals);
2304 QualType ASTContext::getObjCGCQualType(QualType T,
2305 Qualifiers::GC GCAttr) const {
2306 QualType CanT = getCanonicalType(T);
2307 if (CanT.getObjCGCAttr() == GCAttr)
2310 if (const PointerType *ptr = T->getAs<PointerType>()) {
2311 QualType Pointee = ptr->getPointeeType();
2312 if (Pointee->isAnyPointerType()) {
2313 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2314 return getPointerType(ResultType);
2318 // If we are composing extended qualifiers together, merge together
2319 // into one ExtQuals node.
2320 QualifierCollector Quals;
2321 const Type *TypeNode = Quals.strip(T);
2323 // If this type already has an ObjCGC specified, it cannot get
2325 assert(!Quals.hasObjCGCAttr() &&
2326 "Type cannot have multiple ObjCGCs!");
2327 Quals.addObjCGCAttr(GCAttr);
2329 return getExtQualType(TypeNode, Quals);
2332 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2333 FunctionType::ExtInfo Info) {
2334 if (T->getExtInfo() == Info)
2338 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2339 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2341 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2342 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2344 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2347 return cast<FunctionType>(Result.getTypePtr());
2350 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2351 QualType ResultType) {
2352 FD = FD->getMostRecentDecl();
2354 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2355 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2356 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2357 if (FunctionDecl *Next = FD->getPreviousDecl())
2362 if (ASTMutationListener *L = getASTMutationListener())
2363 L->DeducedReturnType(FD, ResultType);
2366 /// Get a function type and produce the equivalent function type with the
2367 /// specified exception specification. Type sugar that can be present on a
2368 /// declaration of a function with an exception specification is permitted
2369 /// and preserved. Other type sugar (for instance, typedefs) is not.
2370 static QualType getFunctionTypeWithExceptionSpec(
2371 ASTContext &Context, QualType Orig,
2372 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2373 // Might have some parens.
2374 if (auto *PT = dyn_cast<ParenType>(Orig))
2375 return Context.getParenType(
2376 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2378 // Might have a calling-convention attribute.
2379 if (auto *AT = dyn_cast<AttributedType>(Orig))
2380 return Context.getAttributedType(
2382 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2383 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2386 // Anything else must be a function type. Rebuild it with the new exception
2388 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2389 return Context.getFunctionType(
2390 Proto->getReturnType(), Proto->getParamTypes(),
2391 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2394 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2396 return hasSameType(T, U) ||
2397 (getLangOpts().CPlusPlus1z &&
2398 hasSameType(getFunctionTypeWithExceptionSpec(*this, T, EST_None),
2399 getFunctionTypeWithExceptionSpec(*this, U, EST_None)));
2402 void ASTContext::adjustExceptionSpec(
2403 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2407 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2408 FD->setType(Updated);
2413 // Update the type in the type source information too.
2414 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2415 // If the type and the type-as-written differ, we may need to update
2416 // the type-as-written too.
2417 if (TSInfo->getType() != FD->getType())
2418 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2420 // FIXME: When we get proper type location information for exceptions,
2421 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2422 // up the TypeSourceInfo;
2423 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2424 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2425 "TypeLoc size mismatch from updating exception specification");
2426 TSInfo->overrideType(Updated);
2430 /// getComplexType - Return the uniqued reference to the type for a complex
2431 /// number with the specified element type.
2432 QualType ASTContext::getComplexType(QualType T) const {
2433 // Unique pointers, to guarantee there is only one pointer of a particular
2435 llvm::FoldingSetNodeID ID;
2436 ComplexType::Profile(ID, T);
2438 void *InsertPos = nullptr;
2439 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2440 return QualType(CT, 0);
2442 // If the pointee type isn't canonical, this won't be a canonical type either,
2443 // so fill in the canonical type field.
2445 if (!T.isCanonical()) {
2446 Canonical = getComplexType(getCanonicalType(T));
2448 // Get the new insert position for the node we care about.
2449 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2450 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2452 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2453 Types.push_back(New);
2454 ComplexTypes.InsertNode(New, InsertPos);
2455 return QualType(New, 0);
2458 /// getPointerType - Return the uniqued reference to the type for a pointer to
2459 /// the specified type.
2460 QualType ASTContext::getPointerType(QualType T) const {
2461 // Unique pointers, to guarantee there is only one pointer of a particular
2463 llvm::FoldingSetNodeID ID;
2464 PointerType::Profile(ID, T);
2466 void *InsertPos = nullptr;
2467 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2468 return QualType(PT, 0);
2470 // If the pointee type isn't canonical, this won't be a canonical type either,
2471 // so fill in the canonical type field.
2473 if (!T.isCanonical()) {
2474 Canonical = getPointerType(getCanonicalType(T));
2476 // Get the new insert position for the node we care about.
2477 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2478 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2480 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2481 Types.push_back(New);
2482 PointerTypes.InsertNode(New, InsertPos);
2483 return QualType(New, 0);
2486 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2487 llvm::FoldingSetNodeID ID;
2488 AdjustedType::Profile(ID, Orig, New);
2489 void *InsertPos = nullptr;
2490 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2492 return QualType(AT, 0);
2494 QualType Canonical = getCanonicalType(New);
2496 // Get the new insert position for the node we care about.
2497 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2498 assert(!AT && "Shouldn't be in the map!");
2500 AT = new (*this, TypeAlignment)
2501 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2502 Types.push_back(AT);
2503 AdjustedTypes.InsertNode(AT, InsertPos);
2504 return QualType(AT, 0);
2507 QualType ASTContext::getDecayedType(QualType T) const {
2508 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2513 // A declaration of a parameter as "array of type" shall be
2514 // adjusted to "qualified pointer to type", where the type
2515 // qualifiers (if any) are those specified within the [ and ] of
2516 // the array type derivation.
2517 if (T->isArrayType())
2518 Decayed = getArrayDecayedType(T);
2521 // A declaration of a parameter as "function returning type"
2522 // shall be adjusted to "pointer to function returning type", as
2524 if (T->isFunctionType())
2525 Decayed = getPointerType(T);
2527 llvm::FoldingSetNodeID ID;
2528 AdjustedType::Profile(ID, T, Decayed);
2529 void *InsertPos = nullptr;
2530 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2532 return QualType(AT, 0);
2534 QualType Canonical = getCanonicalType(Decayed);
2536 // Get the new insert position for the node we care about.
2537 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2538 assert(!AT && "Shouldn't be in the map!");
2540 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2541 Types.push_back(AT);
2542 AdjustedTypes.InsertNode(AT, InsertPos);
2543 return QualType(AT, 0);
2546 /// getBlockPointerType - Return the uniqued reference to the type for
2547 /// a pointer to the specified block.
2548 QualType ASTContext::getBlockPointerType(QualType T) const {
2549 assert(T->isFunctionType() && "block of function types only");
2550 // Unique pointers, to guarantee there is only one block of a particular
2552 llvm::FoldingSetNodeID ID;
2553 BlockPointerType::Profile(ID, T);
2555 void *InsertPos = nullptr;
2556 if (BlockPointerType *PT =
2557 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2558 return QualType(PT, 0);
2560 // If the block pointee type isn't canonical, this won't be a canonical
2561 // type either so fill in the canonical type field.
2563 if (!T.isCanonical()) {
2564 Canonical = getBlockPointerType(getCanonicalType(T));
2566 // Get the new insert position for the node we care about.
2567 BlockPointerType *NewIP =
2568 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2569 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2571 BlockPointerType *New
2572 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2573 Types.push_back(New);
2574 BlockPointerTypes.InsertNode(New, InsertPos);
2575 return QualType(New, 0);
2578 /// getLValueReferenceType - Return the uniqued reference to the type for an
2579 /// lvalue reference to the specified type.
2581 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2582 assert(getCanonicalType(T) != OverloadTy &&
2583 "Unresolved overloaded function type");
2585 // Unique pointers, to guarantee there is only one pointer of a particular
2587 llvm::FoldingSetNodeID ID;
2588 ReferenceType::Profile(ID, T, SpelledAsLValue);
2590 void *InsertPos = nullptr;
2591 if (LValueReferenceType *RT =
2592 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2593 return QualType(RT, 0);
2595 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2597 // If the referencee type isn't canonical, this won't be a canonical type
2598 // either, so fill in the canonical type field.
2600 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2601 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2602 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2604 // Get the new insert position for the node we care about.
2605 LValueReferenceType *NewIP =
2606 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2607 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2610 LValueReferenceType *New
2611 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2613 Types.push_back(New);
2614 LValueReferenceTypes.InsertNode(New, InsertPos);
2616 return QualType(New, 0);
2619 /// getRValueReferenceType - Return the uniqued reference to the type for an
2620 /// rvalue reference to the specified type.
2621 QualType ASTContext::getRValueReferenceType(QualType T) const {
2622 // Unique pointers, to guarantee there is only one pointer of a particular
2624 llvm::FoldingSetNodeID ID;
2625 ReferenceType::Profile(ID, T, false);
2627 void *InsertPos = nullptr;
2628 if (RValueReferenceType *RT =
2629 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2630 return QualType(RT, 0);
2632 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2634 // If the referencee type isn't canonical, this won't be a canonical type
2635 // either, so fill in the canonical type field.
2637 if (InnerRef || !T.isCanonical()) {
2638 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2639 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2641 // Get the new insert position for the node we care about.
2642 RValueReferenceType *NewIP =
2643 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2644 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2647 RValueReferenceType *New
2648 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2649 Types.push_back(New);
2650 RValueReferenceTypes.InsertNode(New, InsertPos);
2651 return QualType(New, 0);
2654 /// getMemberPointerType - Return the uniqued reference to the type for a
2655 /// member pointer to the specified type, in the specified class.
2656 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2657 // Unique pointers, to guarantee there is only one pointer of a particular
2659 llvm::FoldingSetNodeID ID;
2660 MemberPointerType::Profile(ID, T, Cls);
2662 void *InsertPos = nullptr;
2663 if (MemberPointerType *PT =
2664 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2665 return QualType(PT, 0);
2667 // If the pointee or class type isn't canonical, this won't be a canonical
2668 // type either, so fill in the canonical type field.
2670 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2671 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2673 // Get the new insert position for the node we care about.
2674 MemberPointerType *NewIP =
2675 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2676 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2678 MemberPointerType *New
2679 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2680 Types.push_back(New);
2681 MemberPointerTypes.InsertNode(New, InsertPos);
2682 return QualType(New, 0);
2685 /// getConstantArrayType - Return the unique reference to the type for an
2686 /// array of the specified element type.
2687 QualType ASTContext::getConstantArrayType(QualType EltTy,
2688 const llvm::APInt &ArySizeIn,
2689 ArrayType::ArraySizeModifier ASM,
2690 unsigned IndexTypeQuals) const {
2691 assert((EltTy->isDependentType() ||
2692 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2693 "Constant array of VLAs is illegal!");
2695 // Convert the array size into a canonical width matching the pointer size for
2697 llvm::APInt ArySize(ArySizeIn);
2698 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
2700 llvm::FoldingSetNodeID ID;
2701 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2703 void *InsertPos = nullptr;
2704 if (ConstantArrayType *ATP =
2705 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2706 return QualType(ATP, 0);
2708 // If the element type isn't canonical or has qualifiers, this won't
2709 // be a canonical type either, so fill in the canonical type field.
2711 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2712 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2713 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2714 ASM, IndexTypeQuals);
2715 Canon = getQualifiedType(Canon, canonSplit.Quals);
2717 // Get the new insert position for the node we care about.
2718 ConstantArrayType *NewIP =
2719 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2720 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2723 ConstantArrayType *New = new(*this,TypeAlignment)
2724 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2725 ConstantArrayTypes.InsertNode(New, InsertPos);
2726 Types.push_back(New);
2727 return QualType(New, 0);
2730 /// getVariableArrayDecayedType - Turns the given type, which may be
2731 /// variably-modified, into the corresponding type with all the known
2732 /// sizes replaced with [*].
2733 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2734 // Vastly most common case.
2735 if (!type->isVariablyModifiedType()) return type;
2739 SplitQualType split = type.getSplitDesugaredType();
2740 const Type *ty = split.Ty;
2741 switch (ty->getTypeClass()) {
2742 #define TYPE(Class, Base)
2743 #define ABSTRACT_TYPE(Class, Base)
2744 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2745 #include "clang/AST/TypeNodes.def"
2746 llvm_unreachable("didn't desugar past all non-canonical types?");
2748 // These types should never be variably-modified.
2752 case Type::ExtVector:
2753 case Type::DependentSizedExtVector:
2754 case Type::ObjCObject:
2755 case Type::ObjCInterface:
2756 case Type::ObjCObjectPointer:
2759 case Type::UnresolvedUsing:
2760 case Type::TypeOfExpr:
2762 case Type::Decltype:
2763 case Type::UnaryTransform:
2764 case Type::DependentName:
2765 case Type::InjectedClassName:
2766 case Type::TemplateSpecialization:
2767 case Type::DependentTemplateSpecialization:
2768 case Type::TemplateTypeParm:
2769 case Type::SubstTemplateTypeParmPack:
2771 case Type::DeducedTemplateSpecialization:
2772 case Type::PackExpansion:
2773 llvm_unreachable("type should never be variably-modified");
2775 // These types can be variably-modified but should never need to
2777 case Type::FunctionNoProto:
2778 case Type::FunctionProto:
2779 case Type::BlockPointer:
2780 case Type::MemberPointer:
2784 // These types can be variably-modified. All these modifications
2785 // preserve structure except as noted by comments.
2786 // TODO: if we ever care about optimizing VLAs, there are no-op
2787 // optimizations available here.
2789 result = getPointerType(getVariableArrayDecayedType(
2790 cast<PointerType>(ty)->getPointeeType()));
2793 case Type::LValueReference: {
2794 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2795 result = getLValueReferenceType(
2796 getVariableArrayDecayedType(lv->getPointeeType()),
2797 lv->isSpelledAsLValue());
2801 case Type::RValueReference: {
2802 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2803 result = getRValueReferenceType(
2804 getVariableArrayDecayedType(lv->getPointeeType()));
2808 case Type::Atomic: {
2809 const AtomicType *at = cast<AtomicType>(ty);
2810 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2814 case Type::ConstantArray: {
2815 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2816 result = getConstantArrayType(
2817 getVariableArrayDecayedType(cat->getElementType()),
2819 cat->getSizeModifier(),
2820 cat->getIndexTypeCVRQualifiers());
2824 case Type::DependentSizedArray: {
2825 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2826 result = getDependentSizedArrayType(
2827 getVariableArrayDecayedType(dat->getElementType()),
2829 dat->getSizeModifier(),
2830 dat->getIndexTypeCVRQualifiers(),
2831 dat->getBracketsRange());
2835 // Turn incomplete types into [*] types.
2836 case Type::IncompleteArray: {
2837 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2838 result = getVariableArrayType(
2839 getVariableArrayDecayedType(iat->getElementType()),
2842 iat->getIndexTypeCVRQualifiers(),
2847 // Turn VLA types into [*] types.
2848 case Type::VariableArray: {
2849 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2850 result = getVariableArrayType(
2851 getVariableArrayDecayedType(vat->getElementType()),
2854 vat->getIndexTypeCVRQualifiers(),
2855 vat->getBracketsRange());
2860 // Apply the top-level qualifiers from the original.
2861 return getQualifiedType(result, split.Quals);
2864 /// getVariableArrayType - Returns a non-unique reference to the type for a
2865 /// variable array of the specified element type.
2866 QualType ASTContext::getVariableArrayType(QualType EltTy,
2868 ArrayType::ArraySizeModifier ASM,
2869 unsigned IndexTypeQuals,
2870 SourceRange Brackets) const {
2871 // Since we don't unique expressions, it isn't possible to unique VLA's
2872 // that have an expression provided for their size.
2875 // Be sure to pull qualifiers off the element type.
2876 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2877 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2878 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2879 IndexTypeQuals, Brackets);
2880 Canon = getQualifiedType(Canon, canonSplit.Quals);
2883 VariableArrayType *New = new(*this, TypeAlignment)
2884 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2886 VariableArrayTypes.push_back(New);
2887 Types.push_back(New);
2888 return QualType(New, 0);
2891 /// getDependentSizedArrayType - Returns a non-unique reference to
2892 /// the type for a dependently-sized array of the specified element
2894 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2896 ArrayType::ArraySizeModifier ASM,
2897 unsigned elementTypeQuals,
2898 SourceRange brackets) const {
2899 assert((!numElements || numElements->isTypeDependent() ||
2900 numElements->isValueDependent()) &&
2901 "Size must be type- or value-dependent!");
2903 // Dependently-sized array types that do not have a specified number
2904 // of elements will have their sizes deduced from a dependent
2905 // initializer. We do no canonicalization here at all, which is okay
2906 // because they can't be used in most locations.
2908 DependentSizedArrayType *newType
2909 = new (*this, TypeAlignment)
2910 DependentSizedArrayType(*this, elementType, QualType(),
2911 numElements, ASM, elementTypeQuals,
2913 Types.push_back(newType);
2914 return QualType(newType, 0);
2917 // Otherwise, we actually build a new type every time, but we
2918 // also build a canonical type.
2920 SplitQualType canonElementType = getCanonicalType(elementType).split();
2922 void *insertPos = nullptr;
2923 llvm::FoldingSetNodeID ID;
2924 DependentSizedArrayType::Profile(ID, *this,
2925 QualType(canonElementType.Ty, 0),
2926 ASM, elementTypeQuals, numElements);
2928 // Look for an existing type with these properties.
2929 DependentSizedArrayType *canonTy =
2930 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2932 // If we don't have one, build one.
2934 canonTy = new (*this, TypeAlignment)
2935 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2936 QualType(), numElements, ASM, elementTypeQuals,
2938 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2939 Types.push_back(canonTy);
2942 // Apply qualifiers from the element type to the array.
2943 QualType canon = getQualifiedType(QualType(canonTy,0),
2944 canonElementType.Quals);
2946 // If we didn't need extra canonicalization for the element type or the size
2947 // expression, then just use that as our result.
2948 if (QualType(canonElementType.Ty, 0) == elementType &&
2949 canonTy->getSizeExpr() == numElements)
2952 // Otherwise, we need to build a type which follows the spelling
2953 // of the element type.
2954 DependentSizedArrayType *sugaredType
2955 = new (*this, TypeAlignment)
2956 DependentSizedArrayType(*this, elementType, canon, numElements,
2957 ASM, elementTypeQuals, brackets);
2958 Types.push_back(sugaredType);
2959 return QualType(sugaredType, 0);
2962 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2963 ArrayType::ArraySizeModifier ASM,
2964 unsigned elementTypeQuals) const {
2965 llvm::FoldingSetNodeID ID;
2966 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2968 void *insertPos = nullptr;
2969 if (IncompleteArrayType *iat =
2970 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2971 return QualType(iat, 0);
2973 // If the element type isn't canonical, this won't be a canonical type
2974 // either, so fill in the canonical type field. We also have to pull
2975 // qualifiers off the element type.
2978 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2979 SplitQualType canonSplit = getCanonicalType(elementType).split();
2980 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2981 ASM, elementTypeQuals);
2982 canon = getQualifiedType(canon, canonSplit.Quals);
2984 // Get the new insert position for the node we care about.
2985 IncompleteArrayType *existing =
2986 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2987 assert(!existing && "Shouldn't be in the map!"); (void) existing;
2990 IncompleteArrayType *newType = new (*this, TypeAlignment)
2991 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2993 IncompleteArrayTypes.InsertNode(newType, insertPos);
2994 Types.push_back(newType);
2995 return QualType(newType, 0);
2998 /// getVectorType - Return the unique reference to a vector type of
2999 /// the specified element type and size. VectorType must be a built-in type.
3000 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3001 VectorType::VectorKind VecKind) const {
3002 assert(vecType->isBuiltinType());
3004 // Check if we've already instantiated a vector of this type.
3005 llvm::FoldingSetNodeID ID;
3006 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3008 void *InsertPos = nullptr;
3009 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3010 return QualType(VTP, 0);
3012 // If the element type isn't canonical, this won't be a canonical type either,
3013 // so fill in the canonical type field.
3015 if (!vecType.isCanonical()) {
3016 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3018 // Get the new insert position for the node we care about.
3019 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3020 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3022 VectorType *New = new (*this, TypeAlignment)
3023 VectorType(vecType, NumElts, Canonical, VecKind);
3024 VectorTypes.InsertNode(New, InsertPos);
3025 Types.push_back(New);
3026 return QualType(New, 0);
3029 /// getExtVectorType - Return the unique reference to an extended vector type of
3030 /// the specified element type and size. VectorType must be a built-in type.
3032 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3033 assert(vecType->isBuiltinType() || vecType->isDependentType());
3035 // Check if we've already instantiated a vector of this type.
3036 llvm::FoldingSetNodeID ID;
3037 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3038 VectorType::GenericVector);
3039 void *InsertPos = nullptr;
3040 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3041 return QualType(VTP, 0);
3043 // If the element type isn't canonical, this won't be a canonical type either,
3044 // so fill in the canonical type field.
3046 if (!vecType.isCanonical()) {
3047 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3049 // Get the new insert position for the node we care about.
3050 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3051 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3053 ExtVectorType *New = new (*this, TypeAlignment)
3054 ExtVectorType(vecType, NumElts, Canonical);
3055 VectorTypes.InsertNode(New, InsertPos);
3056 Types.push_back(New);
3057 return QualType(New, 0);
3061 ASTContext::getDependentSizedExtVectorType(QualType vecType,
3063 SourceLocation AttrLoc) const {
3064 llvm::FoldingSetNodeID ID;
3065 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
3068 void *InsertPos = nullptr;
3069 DependentSizedExtVectorType *Canon
3070 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3071 DependentSizedExtVectorType *New;
3073 // We already have a canonical version of this array type; use it as
3074 // the canonical type for a newly-built type.
3075 New = new (*this, TypeAlignment)
3076 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3079 QualType CanonVecTy = getCanonicalType(vecType);
3080 if (CanonVecTy == vecType) {
3081 New = new (*this, TypeAlignment)
3082 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3085 DependentSizedExtVectorType *CanonCheck
3086 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3087 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3089 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3091 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3093 New = new (*this, TypeAlignment)
3094 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
3098 Types.push_back(New);
3099 return QualType(New, 0);
3102 /// \brief Determine whether \p T is canonical as the result type of a function.
3103 static bool isCanonicalResultType(QualType T) {
3104 return T.isCanonical() &&
3105 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3106 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3109 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
3112 ASTContext::getFunctionNoProtoType(QualType ResultTy,
3113 const FunctionType::ExtInfo &Info) const {
3114 // Unique functions, to guarantee there is only one function of a particular
3116 llvm::FoldingSetNodeID ID;
3117 FunctionNoProtoType::Profile(ID, ResultTy, Info);
3119 void *InsertPos = nullptr;
3120 if (FunctionNoProtoType *FT =
3121 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3122 return QualType(FT, 0);
3125 if (!isCanonicalResultType(ResultTy)) {
3127 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
3129 // Get the new insert position for the node we care about.
3130 FunctionNoProtoType *NewIP =
3131 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3132 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3135 FunctionNoProtoType *New = new (*this, TypeAlignment)
3136 FunctionNoProtoType(ResultTy, Canonical, Info);
3137 Types.push_back(New);
3138 FunctionNoProtoTypes.InsertNode(New, InsertPos);
3139 return QualType(New, 0);
3143 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3144 CanQualType CanResultType = getCanonicalType(ResultType);
3146 // Canonical result types do not have ARC lifetime qualifiers.
3147 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3148 Qualifiers Qs = CanResultType.getQualifiers();
3149 Qs.removeObjCLifetime();
3150 return CanQualType::CreateUnsafe(
3151 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3154 return CanResultType;
3157 static bool isCanonicalExceptionSpecification(
3158 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3159 if (ESI.Type == EST_None)
3161 if (!NoexceptInType)
3164 // C++17 onwards: exception specification is part of the type, as a simple
3165 // boolean "can this function type throw".
3166 if (ESI.Type == EST_BasicNoexcept)
3169 // A dynamic exception specification is canonical if it only contains pack
3170 // expansions (so we can't tell whether it's non-throwing) and all its
3171 // contained types are canonical.
3172 if (ESI.Type == EST_Dynamic) {
3173 bool AnyPackExpansions = false;
3174 for (QualType ET : ESI.Exceptions) {
3175 if (!ET.isCanonical())
3177 if (ET->getAs<PackExpansionType>())
3178 AnyPackExpansions = true;
3180 return AnyPackExpansions;
3183 // A noexcept(expr) specification is (possibly) canonical if expr is
3185 if (ESI.Type == EST_ComputedNoexcept)
3186 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3191 QualType ASTContext::getFunctionTypeInternal(
3192 QualType ResultTy, ArrayRef<QualType> ArgArray,
3193 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
3194 size_t NumArgs = ArgArray.size();
3196 // Unique functions, to guarantee there is only one function of a particular
3198 llvm::FoldingSetNodeID ID;
3199 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3203 bool Unique = false;
3205 void *InsertPos = nullptr;
3206 if (FunctionProtoType *FPT =
3207 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3208 QualType Existing = QualType(FPT, 0);
3210 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3211 // it so long as our exception specification doesn't contain a dependent
3212 // noexcept expression, or we're just looking for a canonical type.
3213 // Otherwise, we're going to need to create a type
3214 // sugar node to hold the concrete expression.
3215 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
3216 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3219 // We need a new type sugar node for this one, to hold the new noexcept
3220 // expression. We do no canonicalization here, but that's OK since we don't
3221 // expect to see the same noexcept expression much more than once.
3222 Canonical = getCanonicalType(Existing);
3226 bool NoexceptInType = getLangOpts().CPlusPlus1z;
3227 bool IsCanonicalExceptionSpec =
3228 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3230 // Determine whether the type being created is already canonical or not.
3231 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
3232 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
3233 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
3234 if (!ArgArray[i].isCanonicalAsParam())
3235 isCanonical = false;
3237 if (OnlyWantCanonical)
3238 assert(isCanonical &&
3239 "given non-canonical parameters constructing canonical type");
3241 // If this type isn't canonical, get the canonical version of it if we don't
3242 // already have it. The exception spec is only partially part of the
3243 // canonical type, and only in C++17 onwards.
3244 if (!isCanonical && Canonical.isNull()) {
3245 SmallVector<QualType, 16> CanonicalArgs;
3246 CanonicalArgs.reserve(NumArgs);
3247 for (unsigned i = 0; i != NumArgs; ++i)
3248 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
3250 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
3251 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
3252 CanonicalEPI.HasTrailingReturn = false;
3254 if (IsCanonicalExceptionSpec) {
3255 // Exception spec is already OK.
3256 } else if (NoexceptInType) {
3257 switch (EPI.ExceptionSpec.Type) {
3258 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3259 // We don't know yet. It shouldn't matter what we pick here; no-one
3260 // should ever look at this.
3262 case EST_None: case EST_MSAny:
3263 CanonicalEPI.ExceptionSpec.Type = EST_None;
3266 // A dynamic exception specification is almost always "not noexcept",
3267 // with the exception that a pack expansion might expand to no types.
3269 bool AnyPacks = false;
3270 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3271 if (ET->getAs<PackExpansionType>())
3273 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3276 CanonicalEPI.ExceptionSpec.Type = EST_None;
3278 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3279 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3284 case EST_DynamicNone: case EST_BasicNoexcept:
3285 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3288 case EST_ComputedNoexcept:
3289 llvm::APSInt Value(1);
3290 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3291 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3292 /*IsEvaluated*/false)) {
3293 // This noexcept specification is invalid.
3294 // FIXME: Should this be able to happen?
3295 CanonicalEPI.ExceptionSpec.Type = EST_None;
3299 CanonicalEPI.ExceptionSpec.Type =
3300 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3304 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3307 // Adjust the canonical function result type.
3308 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
3310 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
3312 // Get the new insert position for the node we care about.
3313 FunctionProtoType *NewIP =
3314 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3315 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3318 // FunctionProtoType objects are allocated with extra bytes after
3319 // them for three variable size arrays at the end:
3320 // - parameter types
3321 // - exception types
3322 // - extended parameter information
3323 // Instead of the exception types, there could be a noexcept
3324 // expression, or information used to resolve the exception
3326 size_t Size = sizeof(FunctionProtoType) +
3327 NumArgs * sizeof(QualType);
3329 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3330 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3331 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3332 Size += sizeof(Expr*);
3333 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3334 Size += 2 * sizeof(FunctionDecl*);
3335 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3336 Size += sizeof(FunctionDecl*);
3339 // Put the ExtParameterInfos last. If all were equal, it would make
3340 // more sense to put these before the exception specification, because
3341 // it's much easier to skip past them compared to the elaborate switch
3342 // required to skip the exception specification. However, all is not
3343 // equal; ExtParameterInfos are used to model very uncommon features,
3344 // and it's better not to burden the more common paths.
3345 if (EPI.ExtParameterInfos) {
3346 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3349 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
3350 FunctionProtoType::ExtProtoInfo newEPI = EPI;
3351 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3352 Types.push_back(FTP);
3354 FunctionProtoTypes.InsertNode(FTP, InsertPos);
3355 return QualType(FTP, 0);
3358 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
3359 llvm::FoldingSetNodeID ID;
3360 PipeType::Profile(ID, T, ReadOnly);
3362 void *InsertPos = 0;
3363 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3364 return QualType(PT, 0);
3366 // If the pipe element type isn't canonical, this won't be a canonical type
3367 // either, so fill in the canonical type field.
3369 if (!T.isCanonical()) {
3370 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
3372 // Get the new insert position for the node we care about.
3373 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3374 assert(!NewIP && "Shouldn't be in the map!");
3377 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
3378 Types.push_back(New);
3379 PipeTypes.InsertNode(New, InsertPos);
3380 return QualType(New, 0);
3383 QualType ASTContext::getReadPipeType(QualType T) const {
3384 return getPipeType(T, true);
3387 QualType ASTContext::getWritePipeType(QualType T) const {
3388 return getPipeType(T, false);
3392 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3393 if (!isa<CXXRecordDecl>(D)) return false;
3394 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3395 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3397 if (RD->getDescribedClassTemplate() &&
3398 !isa<ClassTemplateSpecializationDecl>(RD))
3404 /// getInjectedClassNameType - Return the unique reference to the
3405 /// injected class name type for the specified templated declaration.
3406 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
3407 QualType TST) const {
3408 assert(NeedsInjectedClassNameType(Decl));
3409 if (Decl->TypeForDecl) {
3410 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3411 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
3412 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3413 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3414 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3417 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
3418 Decl->TypeForDecl = newType;
3419 Types.push_back(newType);
3421 return QualType(Decl->TypeForDecl, 0);
3424 /// getTypeDeclType - Return the unique reference to the type for the
3425 /// specified type declaration.
3426 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3427 assert(Decl && "Passed null for Decl param");
3428 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3430 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3431 return getTypedefType(Typedef);
3433 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3434 "Template type parameter types are always available.");
3436 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
3437 assert(Record->isFirstDecl() && "struct/union has previous declaration");
3438 assert(!NeedsInjectedClassNameType(Record));
3439 return getRecordType(Record);
3440 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
3441 assert(Enum->isFirstDecl() && "enum has previous declaration");
3442 return getEnumType(Enum);
3443 } else if (const UnresolvedUsingTypenameDecl *Using =
3444 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3445 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3446 Decl->TypeForDecl = newType;
3447 Types.push_back(newType);
3449 llvm_unreachable("TypeDecl without a type?");
3451 return QualType(Decl->TypeForDecl, 0);
3454 /// getTypedefType - Return the unique reference to the type for the
3455 /// specified typedef name decl.
3457 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3458 QualType Canonical) const {
3459 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3461 if (Canonical.isNull())
3462 Canonical = getCanonicalType(Decl->getUnderlyingType());
3463 TypedefType *newType = new(*this, TypeAlignment)
3464 TypedefType(Type::Typedef, Decl, Canonical);
3465 Decl->TypeForDecl = newType;
3466 Types.push_back(newType);
3467 return QualType(newType, 0);
3470 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
3471 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3473 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3474 if (PrevDecl->TypeForDecl)
3475 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3477 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3478 Decl->TypeForDecl = newType;
3479 Types.push_back(newType);
3480 return QualType(newType, 0);
3483 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3484 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3486 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3487 if (PrevDecl->TypeForDecl)
3488 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3490 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3491 Decl->TypeForDecl = newType;
3492 Types.push_back(newType);
3493 return QualType(newType, 0);
3496 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3497 QualType modifiedType,
3498 QualType equivalentType) {
3499 llvm::FoldingSetNodeID id;
3500 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3502 void *insertPos = nullptr;
3503 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3504 if (type) return QualType(type, 0);
3506 QualType canon = getCanonicalType(equivalentType);
3507 type = new (*this, TypeAlignment)
3508 AttributedType(canon, attrKind, modifiedType, equivalentType);
3510 Types.push_back(type);
3511 AttributedTypes.InsertNode(type, insertPos);
3513 return QualType(type, 0);
3516 /// \brief Retrieve a substitution-result type.
3518 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3519 QualType Replacement) const {
3520 assert(Replacement.isCanonical()
3521 && "replacement types must always be canonical");
3523 llvm::FoldingSetNodeID ID;
3524 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3525 void *InsertPos = nullptr;
3526 SubstTemplateTypeParmType *SubstParm
3527 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3530 SubstParm = new (*this, TypeAlignment)
3531 SubstTemplateTypeParmType(Parm, Replacement);
3532 Types.push_back(SubstParm);
3533 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3536 return QualType(SubstParm, 0);
3539 /// \brief Retrieve a
3540 QualType ASTContext::getSubstTemplateTypeParmPackType(
3541 const TemplateTypeParmType *Parm,
3542 const TemplateArgument &ArgPack) {
3544 for (const auto &P : ArgPack.pack_elements()) {
3545 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3546 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
3550 llvm::FoldingSetNodeID ID;
3551 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3552 void *InsertPos = nullptr;
3553 if (SubstTemplateTypeParmPackType *SubstParm
3554 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3555 return QualType(SubstParm, 0);
3558 if (!Parm->isCanonicalUnqualified()) {
3559 Canon = getCanonicalType(QualType(Parm, 0));
3560 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3562 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3565 SubstTemplateTypeParmPackType *SubstParm
3566 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3568 Types.push_back(SubstParm);
3569 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3570 return QualType(SubstParm, 0);
3573 /// \brief Retrieve the template type parameter type for a template
3574 /// parameter or parameter pack with the given depth, index, and (optionally)
3576 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3578 TemplateTypeParmDecl *TTPDecl) const {
3579 llvm::FoldingSetNodeID ID;
3580 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3581 void *InsertPos = nullptr;
3582 TemplateTypeParmType *TypeParm
3583 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3586 return QualType(TypeParm, 0);
3589 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3590 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3592 TemplateTypeParmType *TypeCheck
3593 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3594 assert(!TypeCheck && "Template type parameter canonical type broken");
3597 TypeParm = new (*this, TypeAlignment)
3598 TemplateTypeParmType(Depth, Index, ParameterPack);
3600 Types.push_back(TypeParm);
3601 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3603 return QualType(TypeParm, 0);
3607 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3608 SourceLocation NameLoc,
3609 const TemplateArgumentListInfo &Args,
3610 QualType Underlying) const {
3611 assert(!Name.getAsDependentTemplateName() &&
3612 "No dependent template names here!");
3613 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3615 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3616 TemplateSpecializationTypeLoc TL =
3617 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3618 TL.setTemplateKeywordLoc(SourceLocation());
3619 TL.setTemplateNameLoc(NameLoc);
3620 TL.setLAngleLoc(Args.getLAngleLoc());
3621 TL.setRAngleLoc(Args.getRAngleLoc());
3622 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3623 TL.setArgLocInfo(i, Args[i].getLocInfo());
3628 ASTContext::getTemplateSpecializationType(TemplateName Template,
3629 const TemplateArgumentListInfo &Args,
3630 QualType Underlying) const {
3631 assert(!Template.getAsDependentTemplateName() &&
3632 "No dependent template names here!");
3634 SmallVector<TemplateArgument, 4> ArgVec;
3635 ArgVec.reserve(Args.size());
3636 for (const TemplateArgumentLoc &Arg : Args.arguments())
3637 ArgVec.push_back(Arg.getArgument());
3639 return getTemplateSpecializationType(Template, ArgVec, Underlying);
3643 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3644 for (const TemplateArgument &Arg : Args)
3645 if (Arg.isPackExpansion())
3653 ASTContext::getTemplateSpecializationType(TemplateName Template,
3654 ArrayRef<TemplateArgument> Args,
3655 QualType Underlying) const {
3656 assert(!Template.getAsDependentTemplateName() &&
3657 "No dependent template names here!");
3658 // Look through qualified template names.
3659 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3660 Template = TemplateName(QTN->getTemplateDecl());
3663 Template.getAsTemplateDecl() &&
3664 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3666 if (!Underlying.isNull())
3667 CanonType = getCanonicalType(Underlying);
3669 // We can get here with an alias template when the specialization contains
3670 // a pack expansion that does not match up with a parameter pack.
3671 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
3672 "Caller must compute aliased type");
3673 IsTypeAlias = false;
3674 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
3677 // Allocate the (non-canonical) template specialization type, but don't
3678 // try to unique it: these types typically have location information that
3679 // we don't unique and don't want to lose.
3680 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3681 sizeof(TemplateArgument) * Args.size() +
3682 (IsTypeAlias? sizeof(QualType) : 0),
3684 TemplateSpecializationType *Spec
3685 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
3686 IsTypeAlias ? Underlying : QualType());
3688 Types.push_back(Spec);
3689 return QualType(Spec, 0);
3692 QualType ASTContext::getCanonicalTemplateSpecializationType(
3693 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
3694 assert(!Template.getAsDependentTemplateName() &&
3695 "No dependent template names here!");
3697 // Look through qualified template names.
3698 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3699 Template = TemplateName(QTN->getTemplateDecl());
3701 // Build the canonical template specialization type.
3702 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3703 SmallVector<TemplateArgument, 4> CanonArgs;
3704 unsigned NumArgs = Args.size();
3705 CanonArgs.reserve(NumArgs);
3706 for (const TemplateArgument &Arg : Args)
3707 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
3709 // Determine whether this canonical template specialization type already
3711 llvm::FoldingSetNodeID ID;
3712 TemplateSpecializationType::Profile(ID, CanonTemplate,
3715 void *InsertPos = nullptr;
3716 TemplateSpecializationType *Spec
3717 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3720 // Allocate a new canonical template specialization type.
3721 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3722 sizeof(TemplateArgument) * NumArgs),
3724 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3726 QualType(), QualType());
3727 Types.push_back(Spec);
3728 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3731 assert(Spec->isDependentType() &&
3732 "Non-dependent template-id type must have a canonical type");
3733 return QualType(Spec, 0);
3737 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3738 NestedNameSpecifier *NNS,
3739 QualType NamedType) const {
3740 llvm::FoldingSetNodeID ID;
3741 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3743 void *InsertPos = nullptr;
3744 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3746 return QualType(T, 0);
3748 QualType Canon = NamedType;
3749 if (!Canon.isCanonical()) {
3750 Canon = getCanonicalType(NamedType);
3751 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3752 assert(!CheckT && "Elaborated canonical type broken");
3756 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
3758 ElaboratedTypes.InsertNode(T, InsertPos);
3759 return QualType(T, 0);
3763 ASTContext::getParenType(QualType InnerType) const {
3764 llvm::FoldingSetNodeID ID;
3765 ParenType::Profile(ID, InnerType);
3767 void *InsertPos = nullptr;
3768 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3770 return QualType(T, 0);
3772 QualType Canon = InnerType;
3773 if (!Canon.isCanonical()) {
3774 Canon = getCanonicalType(InnerType);
3775 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3776 assert(!CheckT && "Paren canonical type broken");
3780 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
3782 ParenTypes.InsertNode(T, InsertPos);
3783 return QualType(T, 0);
3786 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3787 NestedNameSpecifier *NNS,
3788 const IdentifierInfo *Name,
3789 QualType Canon) const {
3790 if (Canon.isNull()) {
3791 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3792 if (CanonNNS != NNS)
3793 Canon = getDependentNameType(Keyword, CanonNNS, Name);
3796 llvm::FoldingSetNodeID ID;
3797 DependentNameType::Profile(ID, Keyword, NNS, Name);
3799 void *InsertPos = nullptr;
3800 DependentNameType *T
3801 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3803 return QualType(T, 0);
3805 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
3807 DependentNameTypes.InsertNode(T, InsertPos);
3808 return QualType(T, 0);
3812 ASTContext::getDependentTemplateSpecializationType(
3813 ElaboratedTypeKeyword Keyword,
3814 NestedNameSpecifier *NNS,
3815 const IdentifierInfo *Name,
3816 const TemplateArgumentListInfo &Args) const {
3817 // TODO: avoid this copy
3818 SmallVector<TemplateArgument, 16> ArgCopy;
3819 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3820 ArgCopy.push_back(Args[I].getArgument());
3821 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
3825 ASTContext::getDependentTemplateSpecializationType(
3826 ElaboratedTypeKeyword Keyword,
3827 NestedNameSpecifier *NNS,
3828 const IdentifierInfo *Name,
3829 ArrayRef<TemplateArgument> Args) const {
3830 assert((!NNS || NNS->isDependent()) &&
3831 "nested-name-specifier must be dependent");
3833 llvm::FoldingSetNodeID ID;
3834 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3837 void *InsertPos = nullptr;
3838 DependentTemplateSpecializationType *T
3839 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3841 return QualType(T, 0);
3843 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3845 ElaboratedTypeKeyword CanonKeyword = Keyword;
3846 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3848 bool AnyNonCanonArgs = false;
3849 unsigned NumArgs = Args.size();
3850 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3851 for (unsigned I = 0; I != NumArgs; ++I) {
3852 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3853 if (!CanonArgs[I].structurallyEquals(Args[I]))
3854 AnyNonCanonArgs = true;
3858 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3859 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3863 // Find the insert position again.
3864 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3867 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3868 sizeof(TemplateArgument) * NumArgs),
3870 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3873 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3874 return QualType(T, 0);
3877 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
3878 TemplateArgument Arg;
3879 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3880 QualType ArgType = getTypeDeclType(TTP);
3881 if (TTP->isParameterPack())
3882 ArgType = getPackExpansionType(ArgType, None);
3884 Arg = TemplateArgument(ArgType);
3885 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3886 Expr *E = new (*this) DeclRefExpr(
3887 NTTP, /*enclosing*/false,
3888 NTTP->getType().getNonLValueExprType(*this),
3889 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
3891 if (NTTP->isParameterPack())
3892 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
3894 Arg = TemplateArgument(E);
3896 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
3897 if (TTP->isParameterPack())
3898 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
3900 Arg = TemplateArgument(TemplateName(TTP));
3903 if (Param->isTemplateParameterPack())
3904 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
3910 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
3911 SmallVectorImpl<TemplateArgument> &Args) {
3912 Args.reserve(Args.size() + Params->size());
3914 for (NamedDecl *Param : *Params)
3915 Args.push_back(getInjectedTemplateArg(Param));
3918 QualType ASTContext::getPackExpansionType(QualType Pattern,
3919 Optional<unsigned> NumExpansions) {
3920 llvm::FoldingSetNodeID ID;
3921 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3923 assert(Pattern->containsUnexpandedParameterPack() &&
3924 "Pack expansions must expand one or more parameter packs");
3925 void *InsertPos = nullptr;
3926 PackExpansionType *T
3927 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3929 return QualType(T, 0);
3932 if (!Pattern.isCanonical()) {
3933 Canon = getCanonicalType(Pattern);
3934 // The canonical type might not contain an unexpanded parameter pack, if it
3935 // contains an alias template specialization which ignores one of its
3937 if (Canon->containsUnexpandedParameterPack()) {
3938 Canon = getPackExpansionType(Canon, NumExpansions);
3940 // Find the insert position again, in case we inserted an element into
3941 // PackExpansionTypes and invalidated our insert position.
3942 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3946 T = new (*this, TypeAlignment)
3947 PackExpansionType(Pattern, Canon, NumExpansions);
3949 PackExpansionTypes.InsertNode(T, InsertPos);
3950 return QualType(T, 0);
3953 /// CmpProtocolNames - Comparison predicate for sorting protocols
3955 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3956 ObjCProtocolDecl *const *RHS) {
3957 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
3960 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3961 if (Protocols.empty()) return true;
3963 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3966 for (unsigned i = 1; i != Protocols.size(); ++i)
3967 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
3968 Protocols[i]->getCanonicalDecl() != Protocols[i])
3974 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
3975 // Sort protocols, keyed by name.
3976 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
3979 for (ObjCProtocolDecl *&P : Protocols)
3980 P = P->getCanonicalDecl();
3982 // Remove duplicates.
3983 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3984 Protocols.erase(ProtocolsEnd, Protocols.end());
3987 QualType ASTContext::getObjCObjectType(QualType BaseType,
3988 ObjCProtocolDecl * const *Protocols,
3989 unsigned NumProtocols) const {
3990 return getObjCObjectType(BaseType, { },
3991 llvm::makeArrayRef(Protocols, NumProtocols),
3992 /*isKindOf=*/false);
3995 QualType ASTContext::getObjCObjectType(
3997 ArrayRef<QualType> typeArgs,
3998 ArrayRef<ObjCProtocolDecl *> protocols,
3999 bool isKindOf) const {
4000 // If the base type is an interface and there aren't any protocols or
4001 // type arguments to add, then the interface type will do just fine.
4002 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4003 isa<ObjCInterfaceType>(baseType))
4006 // Look in the folding set for an existing type.
4007 llvm::FoldingSetNodeID ID;
4008 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
4009 void *InsertPos = nullptr;
4010 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4011 return QualType(QT, 0);
4013 // Determine the type arguments to be used for canonicalization,
4014 // which may be explicitly specified here or written on the base
4016 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4017 if (effectiveTypeArgs.empty()) {
4018 if (auto baseObject = baseType->getAs<ObjCObjectType>())
4019 effectiveTypeArgs = baseObject->getTypeArgs();
4022 // Build the canonical type, which has the canonical base type and a
4023 // sorted-and-uniqued list of protocols and the type arguments
4026 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4027 effectiveTypeArgs.end(),
4028 [&](QualType type) {
4029 return type.isCanonical();
4031 bool protocolsSorted = areSortedAndUniqued(protocols);
4032 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4033 // Determine the canonical type arguments.
4034 ArrayRef<QualType> canonTypeArgs;
4035 SmallVector<QualType, 4> canonTypeArgsVec;
4036 if (!typeArgsAreCanonical) {
4037 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4038 for (auto typeArg : effectiveTypeArgs)
4039 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4040 canonTypeArgs = canonTypeArgsVec;
4042 canonTypeArgs = effectiveTypeArgs;
4045 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4046 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4047 if (!protocolsSorted) {
4048 canonProtocolsVec.append(protocols.begin(), protocols.end());
4049 SortAndUniqueProtocols(canonProtocolsVec);
4050 canonProtocols = canonProtocolsVec;
4052 canonProtocols = protocols;
4055 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
4056 canonProtocols, isKindOf);
4058 // Regenerate InsertPos.
4059 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4062 unsigned size = sizeof(ObjCObjectTypeImpl);
4063 size += typeArgs.size() * sizeof(QualType);
4064 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4065 void *mem = Allocate(size, TypeAlignment);
4066 ObjCObjectTypeImpl *T =
4067 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4071 ObjCObjectTypes.InsertNode(T, InsertPos);
4072 return QualType(T, 0);
4075 /// Apply Objective-C protocol qualifiers to the given type.
4076 /// If this is for the canonical type of a type parameter, we can apply
4077 /// protocol qualifiers on the ObjCObjectPointerType.
4079 ASTContext::applyObjCProtocolQualifiers(QualType type,
4080 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4081 bool allowOnPointerType) const {
4084 if (const ObjCTypeParamType *objT =
4085 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4086 return getObjCTypeParamType(objT->getDecl(), protocols);
4089 // Apply protocol qualifiers to ObjCObjectPointerType.
4090 if (allowOnPointerType) {
4091 if (const ObjCObjectPointerType *objPtr =
4092 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4093 const ObjCObjectType *objT = objPtr->getObjectType();
4094 // Merge protocol lists and construct ObjCObjectType.
4095 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4096 protocolsVec.append(objT->qual_begin(),
4098 protocolsVec.append(protocols.begin(), protocols.end());
4099 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4100 type = getObjCObjectType(
4101 objT->getBaseType(),
4102 objT->getTypeArgsAsWritten(),
4104 objT->isKindOfTypeAsWritten());
4105 return getObjCObjectPointerType(type);
4109 // Apply protocol qualifiers to ObjCObjectType.
4110 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4111 // FIXME: Check for protocols to which the class type is already
4112 // known to conform.
4114 return getObjCObjectType(objT->getBaseType(),
4115 objT->getTypeArgsAsWritten(),
4117 objT->isKindOfTypeAsWritten());
4120 // If the canonical type is ObjCObjectType, ...
4121 if (type->isObjCObjectType()) {
4122 // Silently overwrite any existing protocol qualifiers.
4123 // TODO: determine whether that's the right thing to do.
4125 // FIXME: Check for protocols to which the class type is already
4126 // known to conform.
4127 return getObjCObjectType(type, { }, protocols, false);
4130 // id<protocol-list>
4131 if (type->isObjCIdType()) {
4132 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4133 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols,
4134 objPtr->isKindOfType());
4135 return getObjCObjectPointerType(type);
4138 // Class<protocol-list>
4139 if (type->isObjCClassType()) {
4140 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4141 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols,
4142 objPtr->isKindOfType());
4143 return getObjCObjectPointerType(type);
4151 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4152 ArrayRef<ObjCProtocolDecl *> protocols,
4153 QualType Canonical) const {
4154 // Look in the folding set for an existing type.
4155 llvm::FoldingSetNodeID ID;
4156 ObjCTypeParamType::Profile(ID, Decl, protocols);
4157 void *InsertPos = nullptr;
4158 if (ObjCTypeParamType *TypeParam =
4159 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4160 return QualType(TypeParam, 0);
4162 if (Canonical.isNull()) {
4163 // We canonicalize to the underlying type.
4164 Canonical = getCanonicalType(Decl->getUnderlyingType());
4165 if (!protocols.empty()) {
4166 // Apply the protocol qualifers.
4168 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4169 true/*allowOnPointerType*/);
4170 assert(!hasError && "Error when apply protocol qualifier to bound type");
4174 unsigned size = sizeof(ObjCTypeParamType);
4175 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4176 void *mem = Allocate(size, TypeAlignment);
4177 ObjCTypeParamType *newType = new (mem)
4178 ObjCTypeParamType(Decl, Canonical, protocols);
4180 Types.push_back(newType);
4181 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4182 return QualType(newType, 0);
4185 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4186 /// protocol list adopt all protocols in QT's qualified-id protocol
4188 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4189 ObjCInterfaceDecl *IC) {
4190 if (!QT->isObjCQualifiedIdType())
4193 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4194 // If both the right and left sides have qualifiers.
4195 for (auto *Proto : OPT->quals()) {
4196 if (!IC->ClassImplementsProtocol(Proto, false))
4204 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4205 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
4207 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4208 ObjCInterfaceDecl *IDecl) {
4209 if (!QT->isObjCQualifiedIdType())
4211 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4214 if (!IDecl->hasDefinition())
4216 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4217 CollectInheritedProtocols(IDecl, InheritedProtocols);
4218 if (InheritedProtocols.empty())
4220 // Check that if every protocol in list of id<plist> conforms to a protcol
4221 // of IDecl's, then bridge casting is ok.
4222 bool Conforms = false;
4223 for (auto *Proto : OPT->quals()) {
4225 for (auto *PI : InheritedProtocols) {
4226 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4237 for (auto *PI : InheritedProtocols) {
4238 // If both the right and left sides have qualifiers.
4239 bool Adopts = false;
4240 for (auto *Proto : OPT->quals()) {
4241 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
4242 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
4251 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4252 /// the given object type.
4253 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
4254 llvm::FoldingSetNodeID ID;
4255 ObjCObjectPointerType::Profile(ID, ObjectT);
4257 void *InsertPos = nullptr;
4258 if (ObjCObjectPointerType *QT =
4259 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4260 return QualType(QT, 0);
4262 // Find the canonical object type.
4264 if (!ObjectT.isCanonical()) {
4265 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4267 // Regenerate InsertPos.
4268 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4272 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4273 ObjCObjectPointerType *QType =
4274 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
4276 Types.push_back(QType);
4277 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
4278 return QualType(QType, 0);
4281 /// getObjCInterfaceType - Return the unique reference to the type for the
4282 /// specified ObjC interface decl. The list of protocols is optional.
4283 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4284 ObjCInterfaceDecl *PrevDecl) const {
4285 if (Decl->TypeForDecl)
4286 return QualType(Decl->TypeForDecl, 0);
4289 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4290 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4291 return QualType(PrevDecl->TypeForDecl, 0);
4294 // Prefer the definition, if there is one.
4295 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4298 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4299 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4300 Decl->TypeForDecl = T;
4302 return QualType(T, 0);
4305 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4306 /// TypeOfExprType AST's (since expression's are never shared). For example,
4307 /// multiple declarations that refer to "typeof(x)" all contain different
4308 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
4309 /// on canonical type's (which are always unique).
4310 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
4311 TypeOfExprType *toe;
4312 if (tofExpr->isTypeDependent()) {
4313 llvm::FoldingSetNodeID ID;
4314 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
4316 void *InsertPos = nullptr;
4317 DependentTypeOfExprType *Canon
4318 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4320 // We already have a "canonical" version of an identical, dependent
4321 // typeof(expr) type. Use that as our canonical type.
4322 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
4323 QualType((TypeOfExprType*)Canon, 0));
4325 // Build a new, canonical typeof(expr) type.
4327 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
4328 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4332 QualType Canonical = getCanonicalType(tofExpr->getType());
4333 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
4335 Types.push_back(toe);
4336 return QualType(toe, 0);
4339 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
4340 /// TypeOfType nodes. The only motivation to unique these nodes would be
4341 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
4342 /// an issue. This doesn't affect the type checker, since it operates
4343 /// on canonical types (which are always unique).
4344 QualType ASTContext::getTypeOfType(QualType tofType) const {
4345 QualType Canonical = getCanonicalType(tofType);
4346 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
4347 Types.push_back(tot);
4348 return QualType(tot, 0);
4351 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4352 /// nodes. This would never be helpful, since each such type has its own
4353 /// expression, and would not give a significant memory saving, since there
4354 /// is an Expr tree under each such type.
4355 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
4358 // C++11 [temp.type]p2:
4359 // If an expression e involves a template parameter, decltype(e) denotes a
4360 // unique dependent type. Two such decltype-specifiers refer to the same
4361 // type only if their expressions are equivalent (14.5.6.1).
4362 if (e->isInstantiationDependent()) {
4363 llvm::FoldingSetNodeID ID;
4364 DependentDecltypeType::Profile(ID, *this, e);
4366 void *InsertPos = nullptr;
4367 DependentDecltypeType *Canon
4368 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
4370 // Build a new, canonical decltype(expr) type.
4371 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
4372 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
4374 dt = new (*this, TypeAlignment)
4375 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
4377 dt = new (*this, TypeAlignment)
4378 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
4380 Types.push_back(dt);
4381 return QualType(dt, 0);
4384 /// getUnaryTransformationType - We don't unique these, since the memory
4385 /// savings are minimal and these are rare.
4386 QualType ASTContext::getUnaryTransformType(QualType BaseType,
4387 QualType UnderlyingType,
4388 UnaryTransformType::UTTKind Kind)
4390 UnaryTransformType *ut = nullptr;
4392 if (BaseType->isDependentType()) {
4393 // Look in the folding set for an existing type.
4394 llvm::FoldingSetNodeID ID;
4395 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4397 void *InsertPos = nullptr;
4398 DependentUnaryTransformType *Canon
4399 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4402 // Build a new, canonical __underlying_type(type) type.
4403 Canon = new (*this, TypeAlignment)
4404 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4406 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4408 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4410 QualType(Canon, 0));
4412 QualType CanonType = getCanonicalType(UnderlyingType);
4413 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4414 UnderlyingType, Kind,
4417 Types.push_back(ut);
4418 return QualType(ut, 0);
4421 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
4422 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4423 /// canonical deduced-but-dependent 'auto' type.
4424 QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
4425 bool IsDependent) const {
4426 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
4427 return getAutoDeductType();
4429 // Look in the folding set for an existing type.
4430 void *InsertPos = nullptr;
4431 llvm::FoldingSetNodeID ID;
4432 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
4433 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4434 return QualType(AT, 0);
4436 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
4439 Types.push_back(AT);
4441 AutoTypes.InsertNode(AT, InsertPos);
4442 return QualType(AT, 0);
4445 /// Return the uniqued reference to the deduced template specialization type
4446 /// which has been deduced to the given type, or to the canonical undeduced
4447 /// such type, or the canonical deduced-but-dependent such type.
4448 QualType ASTContext::getDeducedTemplateSpecializationType(
4449 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4450 // Look in the folding set for an existing type.
4451 void *InsertPos = nullptr;
4452 llvm::FoldingSetNodeID ID;
4453 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4455 if (DeducedTemplateSpecializationType *DTST =
4456 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4457 return QualType(DTST, 0);
4459 DeducedTemplateSpecializationType *DTST = new (*this, TypeAlignment)
4460 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4461 Types.push_back(DTST);
4463 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4464 return QualType(DTST, 0);
4467 /// getAtomicType - Return the uniqued reference to the atomic type for
4468 /// the given value type.
4469 QualType ASTContext::getAtomicType(QualType T) const {
4470 // Unique pointers, to guarantee there is only one pointer of a particular
4472 llvm::FoldingSetNodeID ID;
4473 AtomicType::Profile(ID, T);
4475 void *InsertPos = nullptr;
4476 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4477 return QualType(AT, 0);
4479 // If the atomic value type isn't canonical, this won't be a canonical type
4480 // either, so fill in the canonical type field.
4482 if (!T.isCanonical()) {
4483 Canonical = getAtomicType(getCanonicalType(T));
4485 // Get the new insert position for the node we care about.
4486 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
4487 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4489 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4490 Types.push_back(New);
4491 AtomicTypes.InsertNode(New, InsertPos);
4492 return QualType(New, 0);
4495 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
4496 QualType ASTContext::getAutoDeductType() const {
4497 if (AutoDeductTy.isNull())
4498 AutoDeductTy = QualType(
4499 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
4500 /*dependent*/false),
4502 return AutoDeductTy;
4505 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4506 QualType ASTContext::getAutoRRefDeductType() const {
4507 if (AutoRRefDeductTy.isNull())
4508 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4509 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4510 return AutoRRefDeductTy;
4513 /// getTagDeclType - Return the unique reference to the type for the
4514 /// specified TagDecl (struct/union/class/enum) decl.
4515 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
4517 // FIXME: What is the design on getTagDeclType when it requires casting
4518 // away const? mutable?
4519 return getTypeDeclType(const_cast<TagDecl*>(Decl));
4522 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4523 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4524 /// needs to agree with the definition in <stddef.h>.
4525 CanQualType ASTContext::getSizeType() const {
4526 return getFromTargetType(Target->getSizeType());
4529 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4530 CanQualType ASTContext::getIntMaxType() const {
4531 return getFromTargetType(Target->getIntMaxType());
4534 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4535 CanQualType ASTContext::getUIntMaxType() const {
4536 return getFromTargetType(Target->getUIntMaxType());
4539 /// getSignedWCharType - Return the type of "signed wchar_t".
4540 /// Used when in C++, as a GCC extension.
4541 QualType ASTContext::getSignedWCharType() const {
4542 // FIXME: derive from "Target" ?
4546 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4547 /// Used when in C++, as a GCC extension.
4548 QualType ASTContext::getUnsignedWCharType() const {
4549 // FIXME: derive from "Target" ?
4550 return UnsignedIntTy;
4553 QualType ASTContext::getIntPtrType() const {
4554 return getFromTargetType(Target->getIntPtrType());
4557 QualType ASTContext::getUIntPtrType() const {
4558 return getCorrespondingUnsignedType(getIntPtrType());
4561 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
4562 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4563 QualType ASTContext::getPointerDiffType() const {
4564 return getFromTargetType(Target->getPtrDiffType(0));
4567 /// \brief Return the unique type for "pid_t" defined in
4568 /// <sys/types.h>. We need this to compute the correct type for vfork().
4569 QualType ASTContext::getProcessIDType() const {
4570 return getFromTargetType(Target->getProcessIDType());
4573 //===----------------------------------------------------------------------===//
4575 //===----------------------------------------------------------------------===//
4577 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
4578 // Push qualifiers into arrays, and then discard any remaining
4580 T = getCanonicalType(T);
4581 T = getVariableArrayDecayedType(T);
4582 const Type *Ty = T.getTypePtr();
4584 if (isa<ArrayType>(Ty)) {
4585 Result = getArrayDecayedType(QualType(Ty,0));
4586 } else if (isa<FunctionType>(Ty)) {
4587 Result = getPointerType(QualType(Ty, 0));
4589 Result = QualType(Ty, 0);
4592 return CanQualType::CreateUnsafe(Result);
4595 QualType ASTContext::getUnqualifiedArrayType(QualType type,
4596 Qualifiers &quals) {
4597 SplitQualType splitType = type.getSplitUnqualifiedType();
4599 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4600 // the unqualified desugared type and then drops it on the floor.
4601 // We then have to strip that sugar back off with
4602 // getUnqualifiedDesugaredType(), which is silly.
4603 const ArrayType *AT =
4604 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
4606 // If we don't have an array, just use the results in splitType.
4608 quals = splitType.Quals;
4609 return QualType(splitType.Ty, 0);
4612 // Otherwise, recurse on the array's element type.
4613 QualType elementType = AT->getElementType();
4614 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4616 // If that didn't change the element type, AT has no qualifiers, so we
4617 // can just use the results in splitType.
4618 if (elementType == unqualElementType) {
4619 assert(quals.empty()); // from the recursive call
4620 quals = splitType.Quals;
4621 return QualType(splitType.Ty, 0);
4624 // Otherwise, add in the qualifiers from the outermost type, then
4625 // build the type back up.
4626 quals.addConsistentQualifiers(splitType.Quals);
4628 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4629 return getConstantArrayType(unqualElementType, CAT->getSize(),
4630 CAT->getSizeModifier(), 0);
4633 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
4634 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
4637 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
4638 return getVariableArrayType(unqualElementType,
4640 VAT->getSizeModifier(),
4641 VAT->getIndexTypeCVRQualifiers(),
4642 VAT->getBracketsRange());
4645 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
4646 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
4647 DSAT->getSizeModifier(), 0,
4651 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4652 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4653 /// they point to and return true. If T1 and T2 aren't pointer types
4654 /// or pointer-to-member types, or if they are not similar at this
4655 /// level, returns false and leaves T1 and T2 unchanged. Top-level
4656 /// qualifiers on T1 and T2 are ignored. This function will typically
4657 /// be called in a loop that successively "unwraps" pointer and
4658 /// pointer-to-member types to compare them at each level.
4659 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4660 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4661 *T2PtrType = T2->getAs<PointerType>();
4662 if (T1PtrType && T2PtrType) {
4663 T1 = T1PtrType->getPointeeType();
4664 T2 = T2PtrType->getPointeeType();
4668 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4669 *T2MPType = T2->getAs<MemberPointerType>();
4670 if (T1MPType && T2MPType &&
4671 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4672 QualType(T2MPType->getClass(), 0))) {
4673 T1 = T1MPType->getPointeeType();
4674 T2 = T2MPType->getPointeeType();
4678 if (getLangOpts().ObjC1) {
4679 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4680 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4681 if (T1OPType && T2OPType) {
4682 T1 = T1OPType->getPointeeType();
4683 T2 = T2OPType->getPointeeType();
4688 // FIXME: Block pointers, too?
4694 ASTContext::getNameForTemplate(TemplateName Name,
4695 SourceLocation NameLoc) const {
4696 switch (Name.getKind()) {
4697 case TemplateName::QualifiedTemplate:
4698 case TemplateName::Template:
4699 // DNInfo work in progress: CHECKME: what about DNLoc?
4700 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4703 case TemplateName::OverloadedTemplate: {
4704 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4705 // DNInfo work in progress: CHECKME: what about DNLoc?
4706 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4709 case TemplateName::DependentTemplate: {
4710 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4711 DeclarationName DName;
4712 if (DTN->isIdentifier()) {
4713 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4714 return DeclarationNameInfo(DName, NameLoc);
4716 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4717 // DNInfo work in progress: FIXME: source locations?
4718 DeclarationNameLoc DNLoc;
4719 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4720 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4721 return DeclarationNameInfo(DName, NameLoc, DNLoc);
4725 case TemplateName::SubstTemplateTemplateParm: {
4726 SubstTemplateTemplateParmStorage *subst
4727 = Name.getAsSubstTemplateTemplateParm();
4728 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4732 case TemplateName::SubstTemplateTemplateParmPack: {
4733 SubstTemplateTemplateParmPackStorage *subst
4734 = Name.getAsSubstTemplateTemplateParmPack();
4735 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4740 llvm_unreachable("bad template name kind!");
4743 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4744 switch (Name.getKind()) {
4745 case TemplateName::QualifiedTemplate:
4746 case TemplateName::Template: {
4747 TemplateDecl *Template = Name.getAsTemplateDecl();
4748 if (TemplateTemplateParmDecl *TTP
4749 = dyn_cast<TemplateTemplateParmDecl>(Template))
4750 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4752 // The canonical template name is the canonical template declaration.
4753 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4756 case TemplateName::OverloadedTemplate:
4757 llvm_unreachable("cannot canonicalize overloaded template");
4759 case TemplateName::DependentTemplate: {
4760 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4761 assert(DTN && "Non-dependent template names must refer to template decls.");
4762 return DTN->CanonicalTemplateName;
4765 case TemplateName::SubstTemplateTemplateParm: {
4766 SubstTemplateTemplateParmStorage *subst
4767 = Name.getAsSubstTemplateTemplateParm();
4768 return getCanonicalTemplateName(subst->getReplacement());
4771 case TemplateName::SubstTemplateTemplateParmPack: {
4772 SubstTemplateTemplateParmPackStorage *subst
4773 = Name.getAsSubstTemplateTemplateParmPack();
4774 TemplateTemplateParmDecl *canonParameter
4775 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4776 TemplateArgument canonArgPack
4777 = getCanonicalTemplateArgument(subst->getArgumentPack());
4778 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4782 llvm_unreachable("bad template name!");
4785 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4786 X = getCanonicalTemplateName(X);
4787 Y = getCanonicalTemplateName(Y);
4788 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4792 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4793 switch (Arg.getKind()) {
4794 case TemplateArgument::Null:
4797 case TemplateArgument::Expression:
4800 case TemplateArgument::Declaration: {
4801 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4802 return TemplateArgument(D, Arg.getParamTypeForDecl());
4805 case TemplateArgument::NullPtr:
4806 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4809 case TemplateArgument::Template:
4810 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4812 case TemplateArgument::TemplateExpansion:
4813 return TemplateArgument(getCanonicalTemplateName(
4814 Arg.getAsTemplateOrTemplatePattern()),
4815 Arg.getNumTemplateExpansions());
4817 case TemplateArgument::Integral:
4818 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4820 case TemplateArgument::Type:
4821 return TemplateArgument(getCanonicalType(Arg.getAsType()));
4823 case TemplateArgument::Pack: {
4824 if (Arg.pack_size() == 0)
4827 TemplateArgument *CanonArgs
4828 = new (*this) TemplateArgument[Arg.pack_size()];
4830 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4831 AEnd = Arg.pack_end();
4832 A != AEnd; (void)++A, ++Idx)
4833 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4835 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
4839 // Silence GCC warning
4840 llvm_unreachable("Unhandled template argument kind");
4843 NestedNameSpecifier *
4844 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4848 switch (NNS->getKind()) {
4849 case NestedNameSpecifier::Identifier:
4850 // Canonicalize the prefix but keep the identifier the same.
4851 return NestedNameSpecifier::Create(*this,
4852 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4853 NNS->getAsIdentifier());
4855 case NestedNameSpecifier::Namespace:
4856 // A namespace is canonical; build a nested-name-specifier with
4857 // this namespace and no prefix.
4858 return NestedNameSpecifier::Create(*this, nullptr,
4859 NNS->getAsNamespace()->getOriginalNamespace());
4861 case NestedNameSpecifier::NamespaceAlias:
4862 // A namespace is canonical; build a nested-name-specifier with
4863 // this namespace and no prefix.
4864 return NestedNameSpecifier::Create(*this, nullptr,
4865 NNS->getAsNamespaceAlias()->getNamespace()
4866 ->getOriginalNamespace());
4868 case NestedNameSpecifier::TypeSpec:
4869 case NestedNameSpecifier::TypeSpecWithTemplate: {
4870 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4872 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4873 // break it apart into its prefix and identifier, then reconsititute those
4874 // as the canonical nested-name-specifier. This is required to canonicalize
4875 // a dependent nested-name-specifier involving typedefs of dependent-name
4877 // typedef typename T::type T1;
4878 // typedef typename T1::type T2;
4879 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4880 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4881 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4883 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4884 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4886 return NestedNameSpecifier::Create(*this, nullptr, false,
4887 const_cast<Type *>(T.getTypePtr()));
4890 case NestedNameSpecifier::Global:
4891 case NestedNameSpecifier::Super:
4892 // The global specifier and __super specifer are canonical and unique.
4896 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4899 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4900 // Handle the non-qualified case efficiently.
4901 if (!T.hasLocalQualifiers()) {
4902 // Handle the common positive case fast.
4903 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4907 // Handle the common negative case fast.
4908 if (!isa<ArrayType>(T.getCanonicalType()))
4911 // Apply any qualifiers from the array type to the element type. This
4912 // implements C99 6.7.3p8: "If the specification of an array type includes
4913 // any type qualifiers, the element type is so qualified, not the array type."
4915 // If we get here, we either have type qualifiers on the type, or we have
4916 // sugar such as a typedef in the way. If we have type qualifiers on the type
4917 // we must propagate them down into the element type.
4919 SplitQualType split = T.getSplitDesugaredType();
4920 Qualifiers qs = split.Quals;
4922 // If we have a simple case, just return now.
4923 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4924 if (!ATy || qs.empty())
4927 // Otherwise, we have an array and we have qualifiers on it. Push the
4928 // qualifiers into the array element type and return a new array type.
4929 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4931 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4932 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4933 CAT->getSizeModifier(),
4934 CAT->getIndexTypeCVRQualifiers()));
4935 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4936 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4937 IAT->getSizeModifier(),
4938 IAT->getIndexTypeCVRQualifiers()));
4940 if (const DependentSizedArrayType *DSAT
4941 = dyn_cast<DependentSizedArrayType>(ATy))
4942 return cast<ArrayType>(
4943 getDependentSizedArrayType(NewEltTy,
4944 DSAT->getSizeExpr(),
4945 DSAT->getSizeModifier(),
4946 DSAT->getIndexTypeCVRQualifiers(),
4947 DSAT->getBracketsRange()));
4949 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4950 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4952 VAT->getSizeModifier(),
4953 VAT->getIndexTypeCVRQualifiers(),
4954 VAT->getBracketsRange()));
4957 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4958 if (T->isArrayType() || T->isFunctionType())
4959 return getDecayedType(T);
4963 QualType ASTContext::getSignatureParameterType(QualType T) const {
4964 T = getVariableArrayDecayedType(T);
4965 T = getAdjustedParameterType(T);
4966 return T.getUnqualifiedType();
4969 QualType ASTContext::getExceptionObjectType(QualType T) const {
4970 // C++ [except.throw]p3:
4971 // A throw-expression initializes a temporary object, called the exception
4972 // object, the type of which is determined by removing any top-level
4973 // cv-qualifiers from the static type of the operand of throw and adjusting
4974 // the type from "array of T" or "function returning T" to "pointer to T"
4975 // or "pointer to function returning T", [...]
4976 T = getVariableArrayDecayedType(T);
4977 if (T->isArrayType() || T->isFunctionType())
4978 T = getDecayedType(T);
4979 return T.getUnqualifiedType();
4982 /// getArrayDecayedType - Return the properly qualified result of decaying the
4983 /// specified array type to a pointer. This operation is non-trivial when
4984 /// handling typedefs etc. The canonical type of "T" must be an array type,
4985 /// this returns a pointer to a properly qualified element of the array.
4987 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4988 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4989 // Get the element type with 'getAsArrayType' so that we don't lose any
4990 // typedefs in the element type of the array. This also handles propagation
4991 // of type qualifiers from the array type into the element type if present
4993 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4994 assert(PrettyArrayType && "Not an array type!");
4996 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4998 // int x[restrict 4] -> int *restrict
4999 QualType Result = getQualifiedType(PtrTy,
5000 PrettyArrayType->getIndexTypeQualifiers());
5002 // int x[_Nullable] -> int * _Nullable
5003 if (auto Nullability = Ty->getNullability(*this)) {
5004 Result = const_cast<ASTContext *>(this)->getAttributedType(
5005 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5010 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5011 return getBaseElementType(array->getElementType());
5014 QualType ASTContext::getBaseElementType(QualType type) const {
5017 SplitQualType split = type.getSplitDesugaredType();
5018 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
5021 type = array->getElementType();
5022 qs.addConsistentQualifiers(split.Quals);
5025 return getQualifiedType(type, qs);
5028 /// getConstantArrayElementCount - Returns number of constant array elements.
5030 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5031 uint64_t ElementCount = 1;
5033 ElementCount *= CA->getSize().getZExtValue();
5034 CA = dyn_cast_or_null<ConstantArrayType>(
5035 CA->getElementType()->getAsArrayTypeUnsafe());
5037 return ElementCount;
5040 /// getFloatingRank - Return a relative rank for floating point types.
5041 /// This routine will assert if passed a built-in type that isn't a float.
5042 static FloatingRank getFloatingRank(QualType T) {
5043 if (const ComplexType *CT = T->getAs<ComplexType>())
5044 return getFloatingRank(CT->getElementType());
5046 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5047 switch (T->getAs<BuiltinType>()->getKind()) {
5048 default: llvm_unreachable("getFloatingRank(): not a floating type");
5049 case BuiltinType::Half: return HalfRank;
5050 case BuiltinType::Float: return FloatRank;
5051 case BuiltinType::Double: return DoubleRank;
5052 case BuiltinType::LongDouble: return LongDoubleRank;
5053 case BuiltinType::Float128: return Float128Rank;
5057 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5058 /// point or a complex type (based on typeDomain/typeSize).
5059 /// 'typeDomain' is a real floating point or complex type.
5060 /// 'typeSize' is a real floating point or complex type.
5061 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5062 QualType Domain) const {
5063 FloatingRank EltRank = getFloatingRank(Size);
5064 if (Domain->isComplexType()) {
5066 case HalfRank: llvm_unreachable("Complex half is not supported");
5067 case FloatRank: return FloatComplexTy;
5068 case DoubleRank: return DoubleComplexTy;
5069 case LongDoubleRank: return LongDoubleComplexTy;
5070 case Float128Rank: return Float128ComplexTy;
5074 assert(Domain->isRealFloatingType() && "Unknown domain!");
5076 case HalfRank: return HalfTy;
5077 case FloatRank: return FloatTy;
5078 case DoubleRank: return DoubleTy;
5079 case LongDoubleRank: return LongDoubleTy;
5080 case Float128Rank: return Float128Ty;
5082 llvm_unreachable("getFloatingRank(): illegal value for rank");
5085 /// getFloatingTypeOrder - Compare the rank of the two specified floating
5086 /// point types, ignoring the domain of the type (i.e. 'double' ==
5087 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
5088 /// LHS < RHS, return -1.
5089 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
5090 FloatingRank LHSR = getFloatingRank(LHS);
5091 FloatingRank RHSR = getFloatingRank(RHS);
5100 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5101 /// routine will assert if passed a built-in type that isn't an integer or enum,
5102 /// or if it is not canonicalized.
5103 unsigned ASTContext::getIntegerRank(const Type *T) const {
5104 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
5106 switch (cast<BuiltinType>(T)->getKind()) {
5107 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
5108 case BuiltinType::Bool:
5109 return 1 + (getIntWidth(BoolTy) << 3);
5110 case BuiltinType::Char_S:
5111 case BuiltinType::Char_U:
5112 case BuiltinType::SChar:
5113 case BuiltinType::UChar:
5114 return 2 + (getIntWidth(CharTy) << 3);
5115 case BuiltinType::Short:
5116 case BuiltinType::UShort:
5117 return 3 + (getIntWidth(ShortTy) << 3);
5118 case BuiltinType::Int:
5119 case BuiltinType::UInt:
5120 return 4 + (getIntWidth(IntTy) << 3);
5121 case BuiltinType::Long:
5122 case BuiltinType::ULong:
5123 return 5 + (getIntWidth(LongTy) << 3);
5124 case BuiltinType::LongLong:
5125 case BuiltinType::ULongLong:
5126 return 6 + (getIntWidth(LongLongTy) << 3);
5127 case BuiltinType::Int128:
5128 case BuiltinType::UInt128:
5129 return 7 + (getIntWidth(Int128Ty) << 3);
5133 /// \brief Whether this is a promotable bitfield reference according
5134 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5136 /// \returns the type this bit-field will promote to, or NULL if no
5137 /// promotion occurs.
5138 QualType ASTContext::isPromotableBitField(Expr *E) const {
5139 if (E->isTypeDependent() || E->isValueDependent())
5142 // FIXME: We should not do this unless E->refersToBitField() is true. This
5143 // matters in C where getSourceBitField() will find bit-fields for various
5144 // cases where the source expression is not a bit-field designator.
5146 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
5150 QualType FT = Field->getType();
5152 uint64_t BitWidth = Field->getBitWidthValue(*this);
5153 uint64_t IntSize = getTypeSize(IntTy);
5154 // C++ [conv.prom]p5:
5155 // A prvalue for an integral bit-field can be converted to a prvalue of type
5156 // int if int can represent all the values of the bit-field; otherwise, it
5157 // can be converted to unsigned int if unsigned int can represent all the
5158 // values of the bit-field. If the bit-field is larger yet, no integral
5159 // promotion applies to it.
5161 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5162 // If an int can represent all values of the original type (as restricted by
5163 // the width, for a bit-field), the value is converted to an int; otherwise,
5164 // it is converted to an unsigned int.
5166 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5167 // We perform that promotion here to match GCC and C++.
5168 if (BitWidth < IntSize)
5171 if (BitWidth == IntSize)
5172 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5174 // Types bigger than int are not subject to promotions, and therefore act
5175 // like the base type. GCC has some weird bugs in this area that we
5176 // deliberately do not follow (GCC follows a pre-standard resolution to
5177 // C's DR315 which treats bit-width as being part of the type, and this leaks
5178 // into their semantics in some cases).
5182 /// getPromotedIntegerType - Returns the type that Promotable will
5183 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5185 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
5186 assert(!Promotable.isNull());
5187 assert(Promotable->isPromotableIntegerType());
5188 if (const EnumType *ET = Promotable->getAs<EnumType>())
5189 return ET->getDecl()->getPromotionType();
5191 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5192 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5193 // (3.9.1) can be converted to a prvalue of the first of the following
5194 // types that can represent all the values of its underlying type:
5195 // int, unsigned int, long int, unsigned long int, long long int, or
5196 // unsigned long long int [...]
5197 // FIXME: Is there some better way to compute this?
5198 if (BT->getKind() == BuiltinType::WChar_S ||
5199 BT->getKind() == BuiltinType::WChar_U ||
5200 BT->getKind() == BuiltinType::Char16 ||
5201 BT->getKind() == BuiltinType::Char32) {
5202 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5203 uint64_t FromSize = getTypeSize(BT);
5204 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5205 LongLongTy, UnsignedLongLongTy };
5206 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5207 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5208 if (FromSize < ToSize ||
5209 (FromSize == ToSize &&
5210 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5211 return PromoteTypes[Idx];
5213 llvm_unreachable("char type should fit into long long");
5217 // At this point, we should have a signed or unsigned integer type.
5218 if (Promotable->isSignedIntegerType())
5220 uint64_t PromotableSize = getIntWidth(Promotable);
5221 uint64_t IntSize = getIntWidth(IntTy);
5222 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5223 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5226 /// \brief Recurses in pointer/array types until it finds an objc retainable
5227 /// type and returns its ownership.
5228 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5229 while (!T.isNull()) {
5230 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5231 return T.getObjCLifetime();
5232 if (T->isArrayType())
5233 T = getBaseElementType(T);
5234 else if (const PointerType *PT = T->getAs<PointerType>())
5235 T = PT->getPointeeType();
5236 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
5237 T = RT->getPointeeType();
5242 return Qualifiers::OCL_None;
5245 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5246 // Incomplete enum types are not treated as integer types.
5247 // FIXME: In C++, enum types are never integer types.
5248 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5249 return ET->getDecl()->getIntegerType().getTypePtr();
5253 /// getIntegerTypeOrder - Returns the highest ranked integer type:
5254 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
5255 /// LHS < RHS, return -1.
5256 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
5257 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5258 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
5260 // Unwrap enums to their underlying type.
5261 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5262 LHSC = getIntegerTypeForEnum(ET);
5263 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5264 RHSC = getIntegerTypeForEnum(ET);
5266 if (LHSC == RHSC) return 0;
5268 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5269 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
5271 unsigned LHSRank = getIntegerRank(LHSC);
5272 unsigned RHSRank = getIntegerRank(RHSC);
5274 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5275 if (LHSRank == RHSRank) return 0;
5276 return LHSRank > RHSRank ? 1 : -1;
5279 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5281 // If the unsigned [LHS] type is larger, return it.
5282 if (LHSRank >= RHSRank)
5285 // If the signed type can represent all values of the unsigned type, it
5286 // wins. Because we are dealing with 2's complement and types that are
5287 // powers of two larger than each other, this is always safe.
5291 // If the unsigned [RHS] type is larger, return it.
5292 if (RHSRank >= LHSRank)
5295 // If the signed type can represent all values of the unsigned type, it
5296 // wins. Because we are dealing with 2's complement and types that are
5297 // powers of two larger than each other, this is always safe.
5301 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
5302 if (!CFConstantStringTypeDecl) {
5303 assert(!CFConstantStringTagDecl &&
5304 "tag and typedef should be initialized together");
5305 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5306 CFConstantStringTagDecl->startDefinition();
5308 QualType FieldTypes[4];
5309 const char *FieldNames[4];
5312 FieldTypes[0] = getPointerType(IntTy.withConst());
5313 FieldNames[0] = "isa";
5315 FieldTypes[1] = IntTy;
5316 FieldNames[1] = "flags";
5318 FieldTypes[2] = getPointerType(CharTy.withConst());
5319 FieldNames[2] = "str";
5321 FieldTypes[3] = LongTy;
5322 FieldNames[3] = "length";
5325 for (unsigned i = 0; i < 4; ++i) {
5326 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
5329 &Idents.get(FieldNames[i]),
5330 FieldTypes[i], /*TInfo=*/nullptr,
5331 /*BitWidth=*/nullptr,
5334 Field->setAccess(AS_public);
5335 CFConstantStringTagDecl->addDecl(Field);
5338 CFConstantStringTagDecl->completeDefinition();
5339 // This type is designed to be compatible with NSConstantString, but cannot
5340 // use the same name, since NSConstantString is an interface.
5341 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5342 CFConstantStringTypeDecl =
5343 buildImplicitTypedef(tagType, "__NSConstantString");
5346 return CFConstantStringTypeDecl;
5349 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5350 if (!CFConstantStringTagDecl)
5351 getCFConstantStringDecl(); // Build the tag and the typedef.
5352 return CFConstantStringTagDecl;
5355 // getCFConstantStringType - Return the type used for constant CFStrings.
5356 QualType ASTContext::getCFConstantStringType() const {
5357 return getTypedefType(getCFConstantStringDecl());
5360 QualType ASTContext::getObjCSuperType() const {
5361 if (ObjCSuperType.isNull()) {
5362 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
5363 TUDecl->addDecl(ObjCSuperTypeDecl);
5364 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5366 return ObjCSuperType;
5369 void ASTContext::setCFConstantStringType(QualType T) {
5370 const TypedefType *TD = T->getAs<TypedefType>();
5371 assert(TD && "Invalid CFConstantStringType");
5372 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5374 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5375 assert(TagType && "Invalid CFConstantStringType");
5376 CFConstantStringTagDecl = TagType->getDecl();
5379 QualType ASTContext::getBlockDescriptorType() const {
5380 if (BlockDescriptorType)
5381 return getTagDeclType(BlockDescriptorType);
5384 // FIXME: Needs the FlagAppleBlock bit.
5385 RD = buildImplicitRecord("__block_descriptor");
5386 RD->startDefinition();
5388 QualType FieldTypes[] = {
5393 static const char *const FieldNames[] = {
5398 for (size_t i = 0; i < 2; ++i) {
5399 FieldDecl *Field = FieldDecl::Create(
5400 *this, RD, SourceLocation(), SourceLocation(),
5401 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5402 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
5403 Field->setAccess(AS_public);
5407 RD->completeDefinition();
5409 BlockDescriptorType = RD;
5411 return getTagDeclType(BlockDescriptorType);
5414 QualType ASTContext::getBlockDescriptorExtendedType() const {
5415 if (BlockDescriptorExtendedType)
5416 return getTagDeclType(BlockDescriptorExtendedType);
5419 // FIXME: Needs the FlagAppleBlock bit.
5420 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5421 RD->startDefinition();
5423 QualType FieldTypes[] = {
5426 getPointerType(VoidPtrTy),
5427 getPointerType(VoidPtrTy)
5430 static const char *const FieldNames[] = {
5437 for (size_t i = 0; i < 4; ++i) {
5438 FieldDecl *Field = FieldDecl::Create(
5439 *this, RD, SourceLocation(), SourceLocation(),
5440 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5441 /*BitWidth=*/nullptr,
5442 /*Mutable=*/false, ICIS_NoInit);
5443 Field->setAccess(AS_public);
5447 RD->completeDefinition();
5449 BlockDescriptorExtendedType = RD;
5450 return getTagDeclType(BlockDescriptorExtendedType);
5453 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5454 /// requires copy/dispose. Note that this must match the logic
5455 /// in buildByrefHelpers.
5456 bool ASTContext::BlockRequiresCopying(QualType Ty,
5458 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5459 const Expr *copyExpr = getBlockVarCopyInits(D);
5460 if (!copyExpr && record->hasTrivialDestructor()) return false;
5465 if (!Ty->isObjCRetainableType()) return false;
5467 Qualifiers qs = Ty.getQualifiers();
5469 // If we have lifetime, that dominates.
5470 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
5472 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5474 // These are just bits as far as the runtime is concerned.
5475 case Qualifiers::OCL_ExplicitNone:
5476 case Qualifiers::OCL_Autoreleasing:
5479 // Tell the runtime that this is ARC __weak, called by the
5481 case Qualifiers::OCL_Weak:
5482 // ARC __strong __block variables need to be retained.
5483 case Qualifiers::OCL_Strong:
5486 llvm_unreachable("fell out of lifetime switch!");
5488 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5489 Ty->isObjCObjectPointerType());
5492 bool ASTContext::getByrefLifetime(QualType Ty,
5493 Qualifiers::ObjCLifetime &LifeTime,
5494 bool &HasByrefExtendedLayout) const {
5496 if (!getLangOpts().ObjC1 ||
5497 getLangOpts().getGC() != LangOptions::NonGC)
5500 HasByrefExtendedLayout = false;
5501 if (Ty->isRecordType()) {
5502 HasByrefExtendedLayout = true;
5503 LifeTime = Qualifiers::OCL_None;
5504 } else if ((LifeTime = Ty.getObjCLifetime())) {
5505 // Honor the ARC qualifiers.
5506 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5508 LifeTime = Qualifiers::OCL_ExplicitNone;
5510 LifeTime = Qualifiers::OCL_None;
5515 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5516 if (!ObjCInstanceTypeDecl)
5517 ObjCInstanceTypeDecl =
5518 buildImplicitTypedef(getObjCIdType(), "instancetype");
5519 return ObjCInstanceTypeDecl;
5522 // This returns true if a type has been typedefed to BOOL:
5523 // typedef <type> BOOL;
5524 static bool isTypeTypedefedAsBOOL(QualType T) {
5525 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
5526 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5527 return II->isStr("BOOL");
5532 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
5534 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
5535 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5536 return CharUnits::Zero();
5538 CharUnits sz = getTypeSizeInChars(type);
5540 // Make all integer and enum types at least as large as an int
5541 if (sz.isPositive() && type->isIntegralOrEnumerationType())
5542 sz = std::max(sz, getTypeSizeInChars(IntTy));
5543 // Treat arrays as pointers, since that's how they're passed in.
5544 else if (type->isArrayType())
5545 sz = getTypeSizeInChars(VoidPtrTy);
5549 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
5550 return getTargetInfo().getCXXABI().isMicrosoft() &&
5551 VD->isStaticDataMember() &&
5552 VD->getType()->isIntegralOrEnumerationType() &&
5553 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
5556 ASTContext::InlineVariableDefinitionKind
5557 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5558 if (!VD->isInline())
5559 return InlineVariableDefinitionKind::None;
5561 // In almost all cases, it's a weak definition.
5562 auto *First = VD->getFirstDecl();
5563 if (!First->isConstexpr() || First->isInlineSpecified() ||
5564 !VD->isStaticDataMember())
5565 return InlineVariableDefinitionKind::Weak;
5567 // If there's a file-context declaration in this translation unit, it's a
5568 // non-discardable definition.
5569 for (auto *D : VD->redecls())
5570 if (D->getLexicalDeclContext()->isFileContext())
5571 return InlineVariableDefinitionKind::Strong;
5573 // If we've not seen one yet, we don't know.
5574 return InlineVariableDefinitionKind::WeakUnknown;
5578 std::string charUnitsToString(const CharUnits &CU) {
5579 return llvm::itostr(CU.getQuantity());
5582 /// getObjCEncodingForBlock - Return the encoded type for this block
5584 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5587 const BlockDecl *Decl = Expr->getBlockDecl();
5589 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5590 // Encode result type.
5591 if (getLangOpts().EncodeExtendedBlockSig)
5592 getObjCEncodingForMethodParameter(
5593 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5596 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
5597 // Compute size of all parameters.
5598 // Start with computing size of a pointer in number of bytes.
5599 // FIXME: There might(should) be a better way of doing this computation!
5601 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5602 CharUnits ParmOffset = PtrSize;
5603 for (auto PI : Decl->parameters()) {
5604 QualType PType = PI->getType();
5605 CharUnits sz = getObjCEncodingTypeSize(PType);
5608 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
5611 // Size of the argument frame
5612 S += charUnitsToString(ParmOffset);
5613 // Block pointer and offset.
5617 ParmOffset = PtrSize;
5618 for (auto PVDecl : Decl->parameters()) {
5619 QualType PType = PVDecl->getOriginalType();
5620 if (const ArrayType *AT =
5621 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5622 // Use array's original type only if it has known number of
5624 if (!isa<ConstantArrayType>(AT))
5625 PType = PVDecl->getType();
5626 } else if (PType->isFunctionType())
5627 PType = PVDecl->getType();
5628 if (getLangOpts().EncodeExtendedBlockSig)
5629 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5630 S, true /*Extended*/);
5632 getObjCEncodingForType(PType, S);
5633 S += charUnitsToString(ParmOffset);
5634 ParmOffset += getObjCEncodingTypeSize(PType);
5641 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5643 // Encode result type.
5644 getObjCEncodingForType(Decl->getReturnType(), S);
5645 CharUnits ParmOffset;
5646 // Compute size of all parameters.
5647 for (auto PI : Decl->parameters()) {
5648 QualType PType = PI->getType();
5649 CharUnits sz = getObjCEncodingTypeSize(PType);
5653 assert(sz.isPositive() &&
5654 "getObjCEncodingForFunctionDecl - Incomplete param type");
5657 S += charUnitsToString(ParmOffset);
5658 ParmOffset = CharUnits::Zero();
5661 for (auto PVDecl : Decl->parameters()) {
5662 QualType PType = PVDecl->getOriginalType();
5663 if (const ArrayType *AT =
5664 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5665 // Use array's original type only if it has known number of
5667 if (!isa<ConstantArrayType>(AT))
5668 PType = PVDecl->getType();
5669 } else if (PType->isFunctionType())
5670 PType = PVDecl->getType();
5671 getObjCEncodingForType(PType, S);
5672 S += charUnitsToString(ParmOffset);
5673 ParmOffset += getObjCEncodingTypeSize(PType);
5679 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
5680 /// method parameter or return type. If Extended, include class names and
5681 /// block object types.
5682 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5683 QualType T, std::string& S,
5684 bool Extended) const {
5685 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5686 getObjCEncodingForTypeQualifier(QT, S);
5687 // Encode parameter type.
5688 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5689 true /*OutermostType*/,
5690 false /*EncodingProperty*/,
5691 false /*StructField*/,
5692 Extended /*EncodeBlockParameters*/,
5693 Extended /*EncodeClassNames*/);
5696 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
5698 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5699 bool Extended) const {
5700 // FIXME: This is not very efficient.
5701 // Encode return type.
5703 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5704 Decl->getReturnType(), S, Extended);
5705 // Compute size of all parameters.
5706 // Start with computing size of a pointer in number of bytes.
5707 // FIXME: There might(should) be a better way of doing this computation!
5709 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5710 // The first two arguments (self and _cmd) are pointers; account for
5712 CharUnits ParmOffset = 2 * PtrSize;
5713 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5714 E = Decl->sel_param_end(); PI != E; ++PI) {
5715 QualType PType = (*PI)->getType();
5716 CharUnits sz = getObjCEncodingTypeSize(PType);
5720 assert (sz.isPositive() &&
5721 "getObjCEncodingForMethodDecl - Incomplete param type");
5724 S += charUnitsToString(ParmOffset);
5726 S += charUnitsToString(PtrSize);
5729 ParmOffset = 2 * PtrSize;
5730 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5731 E = Decl->sel_param_end(); PI != E; ++PI) {
5732 const ParmVarDecl *PVDecl = *PI;
5733 QualType PType = PVDecl->getOriginalType();
5734 if (const ArrayType *AT =
5735 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5736 // Use array's original type only if it has known number of
5738 if (!isa<ConstantArrayType>(AT))
5739 PType = PVDecl->getType();
5740 } else if (PType->isFunctionType())
5741 PType = PVDecl->getType();
5742 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5743 PType, S, Extended);
5744 S += charUnitsToString(ParmOffset);
5745 ParmOffset += getObjCEncodingTypeSize(PType);
5751 ObjCPropertyImplDecl *
5752 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5753 const ObjCPropertyDecl *PD,
5754 const Decl *Container) const {
5757 if (const ObjCCategoryImplDecl *CID =
5758 dyn_cast<ObjCCategoryImplDecl>(Container)) {
5759 for (auto *PID : CID->property_impls())
5760 if (PID->getPropertyDecl() == PD)
5763 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5764 for (auto *PID : OID->property_impls())
5765 if (PID->getPropertyDecl() == PD)
5771 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
5772 /// property declaration. If non-NULL, Container must be either an
5773 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5774 /// NULL when getting encodings for protocol properties.
5775 /// Property attributes are stored as a comma-delimited C string. The simple
5776 /// attributes readonly and bycopy are encoded as single characters. The
5777 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
5778 /// encoded as single characters, followed by an identifier. Property types
5779 /// are also encoded as a parametrized attribute. The characters used to encode
5780 /// these attributes are defined by the following enumeration:
5782 /// enum PropertyAttributes {
5783 /// kPropertyReadOnly = 'R', // property is read-only.
5784 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5785 /// kPropertyByref = '&', // property is a reference to the value last assigned
5786 /// kPropertyDynamic = 'D', // property is dynamic
5787 /// kPropertyGetter = 'G', // followed by getter selector name
5788 /// kPropertySetter = 'S', // followed by setter selector name
5789 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
5790 /// kPropertyType = 'T' // followed by old-style type encoding.
5791 /// kPropertyWeak = 'W' // 'weak' property
5792 /// kPropertyStrong = 'P' // property GC'able
5793 /// kPropertyNonAtomic = 'N' // property non-atomic
5797 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5798 const Decl *Container) const {
5799 // Collect information from the property implementation decl(s).
5800 bool Dynamic = false;
5801 ObjCPropertyImplDecl *SynthesizePID = nullptr;
5803 if (ObjCPropertyImplDecl *PropertyImpDecl =
5804 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5805 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5808 SynthesizePID = PropertyImpDecl;
5811 // FIXME: This is not very efficient.
5812 std::string S = "T";
5814 // Encode result type.
5815 // GCC has some special rules regarding encoding of properties which
5816 // closely resembles encoding of ivars.
5817 getObjCEncodingForPropertyType(PD->getType(), S);
5819 if (PD->isReadOnly()) {
5821 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5823 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5825 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5828 switch (PD->getSetterKind()) {
5829 case ObjCPropertyDecl::Assign: break;
5830 case ObjCPropertyDecl::Copy: S += ",C"; break;
5831 case ObjCPropertyDecl::Retain: S += ",&"; break;
5832 case ObjCPropertyDecl::Weak: S += ",W"; break;
5836 // It really isn't clear at all what this means, since properties
5837 // are "dynamic by default".
5841 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5844 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5846 S += PD->getGetterName().getAsString();
5849 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5851 S += PD->getSetterName().getAsString();
5854 if (SynthesizePID) {
5855 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5857 S += OID->getNameAsString();
5860 // FIXME: OBJCGC: weak & strong
5864 /// getLegacyIntegralTypeEncoding -
5865 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5866 /// 'l' or 'L' , but not always. For typedefs, we need to use
5867 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5869 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5870 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5871 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5872 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5873 PointeeTy = UnsignedIntTy;
5875 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5881 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5882 const FieldDecl *Field,
5883 QualType *NotEncodedT) const {
5884 // We follow the behavior of gcc, expanding structures which are
5885 // directly pointed to, and expanding embedded structures. Note that
5886 // these rules are sufficient to prevent recursive encoding of the
5888 getObjCEncodingForTypeImpl(T, S, true, true, Field,
5889 true /* outermost type */, false, false,
5890 false, false, false, NotEncodedT);
5893 void ASTContext::getObjCEncodingForPropertyType(QualType T,
5894 std::string& S) const {
5895 // Encode result type.
5896 // GCC has some special rules regarding encoding of properties which
5897 // closely resembles encoding of ivars.
5898 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5899 true /* outermost type */,
5900 true /* encoding property */);
5903 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5904 BuiltinType::Kind kind) {
5906 case BuiltinType::Void: return 'v';
5907 case BuiltinType::Bool: return 'B';
5908 case BuiltinType::Char_U:
5909 case BuiltinType::UChar: return 'C';
5910 case BuiltinType::Char16:
5911 case BuiltinType::UShort: return 'S';
5912 case BuiltinType::Char32:
5913 case BuiltinType::UInt: return 'I';
5914 case BuiltinType::ULong:
5915 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5916 case BuiltinType::UInt128: return 'T';
5917 case BuiltinType::ULongLong: return 'Q';
5918 case BuiltinType::Char_S:
5919 case BuiltinType::SChar: return 'c';
5920 case BuiltinType::Short: return 's';
5921 case BuiltinType::WChar_S:
5922 case BuiltinType::WChar_U:
5923 case BuiltinType::Int: return 'i';
5924 case BuiltinType::Long:
5925 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5926 case BuiltinType::LongLong: return 'q';
5927 case BuiltinType::Int128: return 't';
5928 case BuiltinType::Float: return 'f';
5929 case BuiltinType::Double: return 'd';
5930 case BuiltinType::LongDouble: return 'D';
5931 case BuiltinType::NullPtr: return '*'; // like char*
5933 case BuiltinType::Float128:
5934 case BuiltinType::Half:
5935 // FIXME: potentially need @encodes for these!
5938 case BuiltinType::ObjCId:
5939 case BuiltinType::ObjCClass:
5940 case BuiltinType::ObjCSel:
5941 llvm_unreachable("@encoding ObjC primitive type");
5943 // OpenCL and placeholder types don't need @encodings.
5944 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5945 case BuiltinType::Id:
5946 #include "clang/Basic/OpenCLImageTypes.def"
5947 case BuiltinType::OCLEvent:
5948 case BuiltinType::OCLClkEvent:
5949 case BuiltinType::OCLQueue:
5950 case BuiltinType::OCLReserveID:
5951 case BuiltinType::OCLSampler:
5952 case BuiltinType::Dependent:
5953 #define BUILTIN_TYPE(KIND, ID)
5954 #define PLACEHOLDER_TYPE(KIND, ID) \
5955 case BuiltinType::KIND:
5956 #include "clang/AST/BuiltinTypes.def"
5957 llvm_unreachable("invalid builtin type for @encode");
5959 llvm_unreachable("invalid BuiltinType::Kind value");
5962 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5963 EnumDecl *Enum = ET->getDecl();
5965 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5966 if (!Enum->isFixed())
5969 // The encoding of a fixed enum type matches its fixed underlying type.
5970 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5971 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5974 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5975 QualType T, const FieldDecl *FD) {
5976 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5978 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5979 // The GNU runtime requires more information; bitfields are encoded as b,
5980 // then the offset (in bits) of the first element, then the type of the
5981 // bitfield, then the size in bits. For example, in this structure:
5988 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5989 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5990 // information is not especially sensible, but we're stuck with it for
5991 // compatibility with GCC, although providing it breaks anything that
5992 // actually uses runtime introspection and wants to work on both runtimes...
5993 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5994 const RecordDecl *RD = FD->getParent();
5995 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5996 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5997 if (const EnumType *ET = T->getAs<EnumType>())
5998 S += ObjCEncodingForEnumType(Ctx, ET);
6000 const BuiltinType *BT = T->castAs<BuiltinType>();
6001 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6004 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
6007 // FIXME: Use SmallString for accumulating string.
6008 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6009 bool ExpandPointedToStructures,
6010 bool ExpandStructures,
6011 const FieldDecl *FD,
6013 bool EncodingProperty,
6015 bool EncodeBlockParameters,
6016 bool EncodeClassNames,
6017 bool EncodePointerToObjCTypedef,
6018 QualType *NotEncodedT) const {
6019 CanQualType CT = getCanonicalType(T);
6020 switch (CT->getTypeClass()) {
6023 if (FD && FD->isBitField())
6024 return EncodeBitField(this, S, T, FD);
6025 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
6026 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6028 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
6031 case Type::Complex: {
6032 const ComplexType *CT = T->castAs<ComplexType>();
6034 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
6038 case Type::Atomic: {
6039 const AtomicType *AT = T->castAs<AtomicType>();
6041 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
6045 // encoding for pointer or reference types.
6047 case Type::LValueReference:
6048 case Type::RValueReference: {
6050 if (isa<PointerType>(CT)) {
6051 const PointerType *PT = T->castAs<PointerType>();
6052 if (PT->isObjCSelType()) {
6056 PointeeTy = PT->getPointeeType();
6058 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6061 bool isReadOnly = false;
6062 // For historical/compatibility reasons, the read-only qualifier of the
6063 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6064 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
6065 // Also, do not emit the 'r' for anything but the outermost type!
6066 if (isa<TypedefType>(T.getTypePtr())) {
6067 if (OutermostType && T.isConstQualified()) {
6071 } else if (OutermostType) {
6072 QualType P = PointeeTy;
6073 while (P->getAs<PointerType>())
6074 P = P->getAs<PointerType>()->getPointeeType();
6075 if (P.isConstQualified()) {
6081 // Another legacy compatibility encoding. Some ObjC qualifier and type
6082 // combinations need to be rearranged.
6083 // Rewrite "in const" from "nr" to "rn"
6084 if (StringRef(S).endswith("nr"))
6085 S.replace(S.end()-2, S.end(), "rn");
6088 if (PointeeTy->isCharType()) {
6089 // char pointer types should be encoded as '*' unless it is a
6090 // type that has been typedef'd to 'BOOL'.
6091 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
6095 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
6096 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6097 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6101 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6102 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6109 getLegacyIntegralTypeEncoding(PointeeTy);
6111 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
6112 nullptr, false, false, false, false, false, false,
6117 case Type::ConstantArray:
6118 case Type::IncompleteArray:
6119 case Type::VariableArray: {
6120 const ArrayType *AT = cast<ArrayType>(CT);
6122 if (isa<IncompleteArrayType>(AT) && !StructField) {
6123 // Incomplete arrays are encoded as a pointer to the array element.
6126 getObjCEncodingForTypeImpl(AT->getElementType(), S,
6127 false, ExpandStructures, FD);
6131 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6132 S += llvm::utostr(CAT->getSize().getZExtValue());
6134 //Variable length arrays are encoded as a regular array with 0 elements.
6135 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6136 "Unknown array type!");
6140 getObjCEncodingForTypeImpl(AT->getElementType(), S,
6141 false, ExpandStructures, FD,
6142 false, false, false, false, false, false,
6149 case Type::FunctionNoProto:
6150 case Type::FunctionProto:
6154 case Type::Record: {
6155 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
6156 S += RDecl->isUnion() ? '(' : '{';
6157 // Anonymous structures print as '?'
6158 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6160 if (ClassTemplateSpecializationDecl *Spec
6161 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6162 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
6163 llvm::raw_string_ostream OS(S);
6164 TemplateSpecializationType::PrintTemplateArgumentList(OS,
6165 TemplateArgs.asArray(),
6166 (*this).getPrintingPolicy());
6171 if (ExpandStructures) {
6173 if (!RDecl->isUnion()) {
6174 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
6176 for (const auto *Field : RDecl->fields()) {
6179 S += Field->getNameAsString();
6183 // Special case bit-fields.
6184 if (Field->isBitField()) {
6185 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
6188 QualType qt = Field->getType();
6189 getLegacyIntegralTypeEncoding(qt);
6190 getObjCEncodingForTypeImpl(qt, S, false, true,
6191 FD, /*OutermostType*/false,
6192 /*EncodingProperty*/false,
6193 /*StructField*/true,
6194 false, false, false, NotEncodedT);
6199 S += RDecl->isUnion() ? ')' : '}';
6203 case Type::BlockPointer: {
6204 const BlockPointerType *BT = T->castAs<BlockPointerType>();
6205 S += "@?"; // Unlike a pointer-to-function, which is "^?".
6206 if (EncodeBlockParameters) {
6207 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
6210 // Block return type
6211 getObjCEncodingForTypeImpl(
6212 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6213 FD, false /* OutermostType */, EncodingProperty,
6214 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6219 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
6220 for (const auto &I : FPT->param_types())
6221 getObjCEncodingForTypeImpl(
6222 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6223 false /* OutermostType */, EncodingProperty,
6224 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6225 false, NotEncodedT);
6232 case Type::ObjCObject: {
6233 // hack to match legacy encoding of *id and *Class
6234 QualType Ty = getObjCObjectPointerType(CT);
6235 if (Ty->isObjCIdType()) {
6236 S += "{objc_object=}";
6239 else if (Ty->isObjCClassType()) {
6240 S += "{objc_class=}";
6245 case Type::ObjCInterface: {
6246 // Ignore protocol qualifiers when mangling at this level.
6247 // @encode(class_name)
6248 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
6250 S += OI->getObjCRuntimeNameAsString();
6251 if (ExpandStructures) {
6253 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6254 DeepCollectObjCIvars(OI, true, Ivars);
6255 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6256 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6257 if (Field->isBitField())
6258 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6260 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6261 false, false, false, false, false,
6262 EncodePointerToObjCTypedef,
6270 case Type::ObjCObjectPointer: {
6271 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
6272 if (OPT->isObjCIdType()) {
6277 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6278 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6279 // Since this is a binary compatibility issue, need to consult with runtime
6280 // folks. Fortunately, this is a *very* obsure construct.
6285 if (OPT->isObjCQualifiedIdType()) {
6286 getObjCEncodingForTypeImpl(getObjCIdType(), S,
6287 ExpandPointedToStructures,
6288 ExpandStructures, FD);
6289 if (FD || EncodingProperty || EncodeClassNames) {
6290 // Note that we do extended encoding of protocol qualifer list
6291 // Only when doing ivar or property encoding.
6293 for (const auto *I : OPT->quals()) {
6295 S += I->getObjCRuntimeNameAsString();
6303 QualType PointeeTy = OPT->getPointeeType();
6304 if (!EncodingProperty &&
6305 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6306 !EncodePointerToObjCTypedef) {
6307 // Another historical/compatibility reason.
6308 // We encode the underlying type which comes out as
6311 if (FD && OPT->getInterfaceDecl()) {
6312 // Prevent recursive encoding of fields in some rare cases.
6313 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6314 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6315 DeepCollectObjCIvars(OI, true, Ivars);
6316 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6317 if (cast<FieldDecl>(Ivars[i]) == FD) {
6319 S += OI->getObjCRuntimeNameAsString();
6325 getObjCEncodingForTypeImpl(PointeeTy, S,
6326 false, ExpandPointedToStructures,
6328 false, false, false, false, false,
6329 /*EncodePointerToObjCTypedef*/true);
6334 if (OPT->getInterfaceDecl() &&
6335 (FD || EncodingProperty || EncodeClassNames)) {
6337 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
6338 for (const auto *I : OPT->quals()) {
6340 S += I->getObjCRuntimeNameAsString();
6348 // gcc just blithely ignores member pointers.
6349 // FIXME: we shoul do better than that. 'M' is available.
6350 case Type::MemberPointer:
6351 // This matches gcc's encoding, even though technically it is insufficient.
6352 //FIXME. We should do a better job than gcc.
6354 case Type::ExtVector:
6355 // Until we have a coherent encoding of these three types, issue warning.
6361 // We could see an undeduced auto type here during error recovery.
6364 case Type::DeducedTemplateSpecialization:
6368 #define ABSTRACT_TYPE(KIND, BASE)
6369 #define TYPE(KIND, BASE)
6370 #define DEPENDENT_TYPE(KIND, BASE) \
6372 #define NON_CANONICAL_TYPE(KIND, BASE) \
6374 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6376 #include "clang/AST/TypeNodes.def"
6377 llvm_unreachable("@encode for dependent type!");
6379 llvm_unreachable("bad type kind!");
6382 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6384 const FieldDecl *FD,
6386 QualType *NotEncodedT) const {
6387 assert(RDecl && "Expected non-null RecordDecl");
6388 assert(!RDecl->isUnion() && "Should not be called for unions");
6389 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
6392 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6393 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6394 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6397 for (const auto &BI : CXXRec->bases()) {
6398 if (!BI.isVirtual()) {
6399 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
6400 if (base->isEmpty())
6402 uint64_t offs = toBits(layout.getBaseClassOffset(base));
6403 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6404 std::make_pair(offs, base));
6410 for (auto *Field : RDecl->fields()) {
6411 uint64_t offs = layout.getFieldOffset(i);
6412 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6413 std::make_pair(offs, Field));
6417 if (CXXRec && includeVBases) {
6418 for (const auto &BI : CXXRec->vbases()) {
6419 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
6420 if (base->isEmpty())
6422 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
6423 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6424 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
6425 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6426 std::make_pair(offs, base));
6432 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6434 size = layout.getSize();
6438 uint64_t CurOffs = 0;
6440 std::multimap<uint64_t, NamedDecl *>::iterator
6441 CurLayObj = FieldOrBaseOffsets.begin();
6443 if (CXXRec && CXXRec->isDynamicClass() &&
6444 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
6447 std::string recname = CXXRec->getNameAsString();
6448 if (recname.empty()) recname = "?";
6454 CurOffs += getTypeSize(VoidPtrTy);
6458 if (!RDecl->hasFlexibleArrayMember()) {
6459 // Mark the end of the structure.
6460 uint64_t offs = toBits(size);
6461 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6462 std::make_pair(offs, nullptr));
6465 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
6467 assert(CurOffs <= CurLayObj->first);
6468 if (CurOffs < CurLayObj->first) {
6469 uint64_t padding = CurLayObj->first - CurOffs;
6470 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6471 // packing/alignment of members is different that normal, in which case
6472 // the encoding will be out-of-sync with the real layout.
6473 // If the runtime switches to just consider the size of types without
6474 // taking into account alignment, we could make padding explicit in the
6475 // encoding (e.g. using arrays of chars). The encoding strings would be
6476 // longer then though.
6481 NamedDecl *dcl = CurLayObj->second;
6483 break; // reached end of structure.
6485 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6486 // We expand the bases without their virtual bases since those are going
6487 // in the initial structure. Note that this differs from gcc which
6488 // expands virtual bases each time one is encountered in the hierarchy,
6489 // making the encoding type bigger than it really is.
6490 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6492 assert(!base->isEmpty());
6494 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
6497 FieldDecl *field = cast<FieldDecl>(dcl);
6500 S += field->getNameAsString();
6504 if (field->isBitField()) {
6505 EncodeBitField(this, S, field->getType(), field);
6507 CurOffs += field->getBitWidthValue(*this);
6510 QualType qt = field->getType();
6511 getLegacyIntegralTypeEncoding(qt);
6512 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6513 /*OutermostType*/false,
6514 /*EncodingProperty*/false,
6515 /*StructField*/true,
6516 false, false, false, NotEncodedT);
6518 CurOffs += getTypeSize(field->getType());
6525 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
6526 std::string& S) const {
6527 if (QT & Decl::OBJC_TQ_In)
6529 if (QT & Decl::OBJC_TQ_Inout)
6531 if (QT & Decl::OBJC_TQ_Out)
6533 if (QT & Decl::OBJC_TQ_Bycopy)
6535 if (QT & Decl::OBJC_TQ_Byref)
6537 if (QT & Decl::OBJC_TQ_Oneway)
6541 TypedefDecl *ASTContext::getObjCIdDecl() const {
6543 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
6544 T = getObjCObjectPointerType(T);
6545 ObjCIdDecl = buildImplicitTypedef(T, "id");
6550 TypedefDecl *ASTContext::getObjCSelDecl() const {
6552 QualType T = getPointerType(ObjCBuiltinSelTy);
6553 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
6558 TypedefDecl *ASTContext::getObjCClassDecl() const {
6559 if (!ObjCClassDecl) {
6560 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
6561 T = getObjCObjectPointerType(T);
6562 ObjCClassDecl = buildImplicitTypedef(T, "Class");
6564 return ObjCClassDecl;
6567 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6568 if (!ObjCProtocolClassDecl) {
6569 ObjCProtocolClassDecl
6570 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6572 &Idents.get("Protocol"),
6573 /*typeParamList=*/nullptr,
6574 /*PrevDecl=*/nullptr,
6575 SourceLocation(), true);
6578 return ObjCProtocolClassDecl;
6581 //===----------------------------------------------------------------------===//
6582 // __builtin_va_list Construction Functions
6583 //===----------------------------------------------------------------------===//
6585 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6587 // typedef char* __builtin[_ms]_va_list;
6588 QualType T = Context->getPointerType(Context->CharTy);
6589 return Context->buildImplicitTypedef(T, Name);
6592 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6593 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6596 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6597 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
6600 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6601 // typedef void* __builtin_va_list;
6602 QualType T = Context->getPointerType(Context->VoidTy);
6603 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6606 static TypedefDecl *
6607 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
6609 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
6610 if (Context->getLangOpts().CPlusPlus) {
6611 // namespace std { struct __va_list {
6613 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6614 Context->getTranslationUnitDecl(),
6615 /*Inline*/ false, SourceLocation(),
6616 SourceLocation(), &Context->Idents.get("std"),
6617 /*PrevDecl*/ nullptr);
6619 VaListTagDecl->setDeclContext(NS);
6622 VaListTagDecl->startDefinition();
6624 const size_t NumFields = 5;
6625 QualType FieldTypes[NumFields];
6626 const char *FieldNames[NumFields];
6629 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6630 FieldNames[0] = "__stack";
6633 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6634 FieldNames[1] = "__gr_top";
6637 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6638 FieldNames[2] = "__vr_top";
6641 FieldTypes[3] = Context->IntTy;
6642 FieldNames[3] = "__gr_offs";
6645 FieldTypes[4] = Context->IntTy;
6646 FieldNames[4] = "__vr_offs";
6649 for (unsigned i = 0; i < NumFields; ++i) {
6650 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6654 &Context->Idents.get(FieldNames[i]),
6655 FieldTypes[i], /*TInfo=*/nullptr,
6656 /*BitWidth=*/nullptr,
6659 Field->setAccess(AS_public);
6660 VaListTagDecl->addDecl(Field);
6662 VaListTagDecl->completeDefinition();
6663 Context->VaListTagDecl = VaListTagDecl;
6664 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6666 // } __builtin_va_list;
6667 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
6670 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6671 // typedef struct __va_list_tag {
6672 RecordDecl *VaListTagDecl;
6674 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6675 VaListTagDecl->startDefinition();
6677 const size_t NumFields = 5;
6678 QualType FieldTypes[NumFields];
6679 const char *FieldNames[NumFields];
6681 // unsigned char gpr;
6682 FieldTypes[0] = Context->UnsignedCharTy;
6683 FieldNames[0] = "gpr";
6685 // unsigned char fpr;
6686 FieldTypes[1] = Context->UnsignedCharTy;
6687 FieldNames[1] = "fpr";
6689 // unsigned short reserved;
6690 FieldTypes[2] = Context->UnsignedShortTy;
6691 FieldNames[2] = "reserved";
6693 // void* overflow_arg_area;
6694 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6695 FieldNames[3] = "overflow_arg_area";
6697 // void* reg_save_area;
6698 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6699 FieldNames[4] = "reg_save_area";
6702 for (unsigned i = 0; i < NumFields; ++i) {
6703 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6706 &Context->Idents.get(FieldNames[i]),
6707 FieldTypes[i], /*TInfo=*/nullptr,
6708 /*BitWidth=*/nullptr,
6711 Field->setAccess(AS_public);
6712 VaListTagDecl->addDecl(Field);
6714 VaListTagDecl->completeDefinition();
6715 Context->VaListTagDecl = VaListTagDecl;
6716 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6719 TypedefDecl *VaListTagTypedefDecl =
6720 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6722 QualType VaListTagTypedefType =
6723 Context->getTypedefType(VaListTagTypedefDecl);
6725 // typedef __va_list_tag __builtin_va_list[1];
6726 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6727 QualType VaListTagArrayType
6728 = Context->getConstantArrayType(VaListTagTypedefType,
6729 Size, ArrayType::Normal, 0);
6730 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6733 static TypedefDecl *
6734 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6735 // struct __va_list_tag {
6736 RecordDecl *VaListTagDecl;
6737 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6738 VaListTagDecl->startDefinition();
6740 const size_t NumFields = 4;
6741 QualType FieldTypes[NumFields];
6742 const char *FieldNames[NumFields];
6744 // unsigned gp_offset;
6745 FieldTypes[0] = Context->UnsignedIntTy;
6746 FieldNames[0] = "gp_offset";
6748 // unsigned fp_offset;
6749 FieldTypes[1] = Context->UnsignedIntTy;
6750 FieldNames[1] = "fp_offset";
6752 // void* overflow_arg_area;
6753 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6754 FieldNames[2] = "overflow_arg_area";
6756 // void* reg_save_area;
6757 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6758 FieldNames[3] = "reg_save_area";
6761 for (unsigned i = 0; i < NumFields; ++i) {
6762 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6766 &Context->Idents.get(FieldNames[i]),
6767 FieldTypes[i], /*TInfo=*/nullptr,
6768 /*BitWidth=*/nullptr,
6771 Field->setAccess(AS_public);
6772 VaListTagDecl->addDecl(Field);
6774 VaListTagDecl->completeDefinition();
6775 Context->VaListTagDecl = VaListTagDecl;
6776 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6780 // typedef struct __va_list_tag __builtin_va_list[1];
6781 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6782 QualType VaListTagArrayType =
6783 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6784 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6787 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6788 // typedef int __builtin_va_list[4];
6789 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6790 QualType IntArrayType =
6791 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
6792 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6795 static TypedefDecl *
6796 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6798 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6799 if (Context->getLangOpts().CPlusPlus) {
6800 // namespace std { struct __va_list {
6802 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6803 Context->getTranslationUnitDecl(),
6804 /*Inline*/false, SourceLocation(),
6805 SourceLocation(), &Context->Idents.get("std"),
6806 /*PrevDecl*/ nullptr);
6808 VaListDecl->setDeclContext(NS);
6811 VaListDecl->startDefinition();
6814 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6818 &Context->Idents.get("__ap"),
6819 Context->getPointerType(Context->VoidTy),
6821 /*BitWidth=*/nullptr,
6824 Field->setAccess(AS_public);
6825 VaListDecl->addDecl(Field);
6828 VaListDecl->completeDefinition();
6829 Context->VaListTagDecl = VaListDecl;
6831 // typedef struct __va_list __builtin_va_list;
6832 QualType T = Context->getRecordType(VaListDecl);
6833 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6836 static TypedefDecl *
6837 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6838 // struct __va_list_tag {
6839 RecordDecl *VaListTagDecl;
6840 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6841 VaListTagDecl->startDefinition();
6843 const size_t NumFields = 4;
6844 QualType FieldTypes[NumFields];
6845 const char *FieldNames[NumFields];
6848 FieldTypes[0] = Context->LongTy;
6849 FieldNames[0] = "__gpr";
6852 FieldTypes[1] = Context->LongTy;
6853 FieldNames[1] = "__fpr";
6855 // void *__overflow_arg_area;
6856 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6857 FieldNames[2] = "__overflow_arg_area";
6859 // void *__reg_save_area;
6860 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6861 FieldNames[3] = "__reg_save_area";
6864 for (unsigned i = 0; i < NumFields; ++i) {
6865 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6869 &Context->Idents.get(FieldNames[i]),
6870 FieldTypes[i], /*TInfo=*/nullptr,
6871 /*BitWidth=*/nullptr,
6874 Field->setAccess(AS_public);
6875 VaListTagDecl->addDecl(Field);
6877 VaListTagDecl->completeDefinition();
6878 Context->VaListTagDecl = VaListTagDecl;
6879 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6883 // typedef __va_list_tag __builtin_va_list[1];
6884 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6885 QualType VaListTagArrayType =
6886 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6888 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6891 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6892 TargetInfo::BuiltinVaListKind Kind) {
6894 case TargetInfo::CharPtrBuiltinVaList:
6895 return CreateCharPtrBuiltinVaListDecl(Context);
6896 case TargetInfo::VoidPtrBuiltinVaList:
6897 return CreateVoidPtrBuiltinVaListDecl(Context);
6898 case TargetInfo::AArch64ABIBuiltinVaList:
6899 return CreateAArch64ABIBuiltinVaListDecl(Context);
6900 case TargetInfo::PowerABIBuiltinVaList:
6901 return CreatePowerABIBuiltinVaListDecl(Context);
6902 case TargetInfo::X86_64ABIBuiltinVaList:
6903 return CreateX86_64ABIBuiltinVaListDecl(Context);
6904 case TargetInfo::PNaClABIBuiltinVaList:
6905 return CreatePNaClABIBuiltinVaListDecl(Context);
6906 case TargetInfo::AAPCSABIBuiltinVaList:
6907 return CreateAAPCSABIBuiltinVaListDecl(Context);
6908 case TargetInfo::SystemZBuiltinVaList:
6909 return CreateSystemZBuiltinVaListDecl(Context);
6912 llvm_unreachable("Unhandled __builtin_va_list type kind");
6915 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6916 if (!BuiltinVaListDecl) {
6917 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6918 assert(BuiltinVaListDecl->isImplicit());
6921 return BuiltinVaListDecl;
6924 Decl *ASTContext::getVaListTagDecl() const {
6925 // Force the creation of VaListTagDecl by building the __builtin_va_list
6928 (void)getBuiltinVaListDecl();
6930 return VaListTagDecl;
6933 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6934 if (!BuiltinMSVaListDecl)
6935 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6937 return BuiltinMSVaListDecl;
6940 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6941 assert(ObjCConstantStringType.isNull() &&
6942 "'NSConstantString' type already set!");
6944 ObjCConstantStringType = getObjCInterfaceType(Decl);
6947 /// \brief Retrieve the template name that corresponds to a non-empty
6950 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6951 UnresolvedSetIterator End) const {
6952 unsigned size = End - Begin;
6953 assert(size > 1 && "set is not overloaded!");
6955 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6956 size * sizeof(FunctionTemplateDecl*));
6957 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6959 NamedDecl **Storage = OT->getStorage();
6960 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6962 assert(isa<FunctionTemplateDecl>(D) ||
6963 (isa<UsingShadowDecl>(D) &&
6964 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6968 return TemplateName(OT);
6971 /// \brief Retrieve the template name that represents a qualified
6972 /// template name such as \c std::vector.
6974 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6975 bool TemplateKeyword,
6976 TemplateDecl *Template) const {
6977 assert(NNS && "Missing nested-name-specifier in qualified template name");
6979 // FIXME: Canonicalization?
6980 llvm::FoldingSetNodeID ID;
6981 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6983 void *InsertPos = nullptr;
6984 QualifiedTemplateName *QTN =
6985 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6987 QTN = new (*this, alignof(QualifiedTemplateName))
6988 QualifiedTemplateName(NNS, TemplateKeyword, Template);
6989 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6992 return TemplateName(QTN);
6995 /// \brief Retrieve the template name that represents a dependent
6996 /// template name such as \c MetaFun::template apply.
6998 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6999 const IdentifierInfo *Name) const {
7000 assert((!NNS || NNS->isDependent()) &&
7001 "Nested name specifier must be dependent");
7003 llvm::FoldingSetNodeID ID;
7004 DependentTemplateName::Profile(ID, NNS, Name);
7006 void *InsertPos = nullptr;
7007 DependentTemplateName *QTN =
7008 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7011 return TemplateName(QTN);
7013 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7014 if (CanonNNS == NNS) {
7015 QTN = new (*this, alignof(DependentTemplateName))
7016 DependentTemplateName(NNS, Name);
7018 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
7019 QTN = new (*this, alignof(DependentTemplateName))
7020 DependentTemplateName(NNS, Name, Canon);
7021 DependentTemplateName *CheckQTN =
7022 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7023 assert(!CheckQTN && "Dependent type name canonicalization broken");
7027 DependentTemplateNames.InsertNode(QTN, InsertPos);
7028 return TemplateName(QTN);
7031 /// \brief Retrieve the template name that represents a dependent
7032 /// template name such as \c MetaFun::template operator+.
7034 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7035 OverloadedOperatorKind Operator) const {
7036 assert((!NNS || NNS->isDependent()) &&
7037 "Nested name specifier must be dependent");
7039 llvm::FoldingSetNodeID ID;
7040 DependentTemplateName::Profile(ID, NNS, Operator);
7042 void *InsertPos = nullptr;
7043 DependentTemplateName *QTN
7044 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7047 return TemplateName(QTN);
7049 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7050 if (CanonNNS == NNS) {
7051 QTN = new (*this, alignof(DependentTemplateName))
7052 DependentTemplateName(NNS, Operator);
7054 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
7055 QTN = new (*this, alignof(DependentTemplateName))
7056 DependentTemplateName(NNS, Operator, Canon);
7058 DependentTemplateName *CheckQTN
7059 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7060 assert(!CheckQTN && "Dependent template name canonicalization broken");
7064 DependentTemplateNames.InsertNode(QTN, InsertPos);
7065 return TemplateName(QTN);
7069 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7070 TemplateName replacement) const {
7071 llvm::FoldingSetNodeID ID;
7072 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
7074 void *insertPos = nullptr;
7075 SubstTemplateTemplateParmStorage *subst
7076 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7079 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7080 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7083 return TemplateName(subst);
7087 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7088 const TemplateArgument &ArgPack) const {
7089 ASTContext &Self = const_cast<ASTContext &>(*this);
7090 llvm::FoldingSetNodeID ID;
7091 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
7093 void *InsertPos = nullptr;
7094 SubstTemplateTemplateParmPackStorage *Subst
7095 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7098 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
7099 ArgPack.pack_size(),
7100 ArgPack.pack_begin());
7101 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7104 return TemplateName(Subst);
7107 /// getFromTargetType - Given one of the integer types provided by
7108 /// TargetInfo, produce the corresponding type. The unsigned @p Type
7109 /// is actually a value of type @c TargetInfo::IntType.
7110 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
7112 case TargetInfo::NoInt: return CanQualType();
7113 case TargetInfo::SignedChar: return SignedCharTy;
7114 case TargetInfo::UnsignedChar: return UnsignedCharTy;
7115 case TargetInfo::SignedShort: return ShortTy;
7116 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7117 case TargetInfo::SignedInt: return IntTy;
7118 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7119 case TargetInfo::SignedLong: return LongTy;
7120 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7121 case TargetInfo::SignedLongLong: return LongLongTy;
7122 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7125 llvm_unreachable("Unhandled TargetInfo::IntType value");
7128 //===----------------------------------------------------------------------===//
7130 //===----------------------------------------------------------------------===//
7132 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7133 /// garbage collection attribute.
7135 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
7136 if (getLangOpts().getGC() == LangOptions::NonGC)
7137 return Qualifiers::GCNone;
7139 assert(getLangOpts().ObjC1);
7140 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7142 // Default behaviour under objective-C's gc is for ObjC pointers
7143 // (or pointers to them) be treated as though they were declared
7145 if (GCAttrs == Qualifiers::GCNone) {
7146 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7147 return Qualifiers::Strong;
7148 else if (Ty->isPointerType())
7149 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7151 // It's not valid to set GC attributes on anything that isn't a
7154 QualType CT = Ty->getCanonicalTypeInternal();
7155 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7156 CT = AT->getElementType();
7157 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7163 //===----------------------------------------------------------------------===//
7164 // Type Compatibility Testing
7165 //===----------------------------------------------------------------------===//
7167 /// areCompatVectorTypes - Return true if the two specified vector types are
7169 static bool areCompatVectorTypes(const VectorType *LHS,
7170 const VectorType *RHS) {
7171 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
7172 return LHS->getElementType() == RHS->getElementType() &&
7173 LHS->getNumElements() == RHS->getNumElements();
7176 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7177 QualType SecondVec) {
7178 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7179 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7181 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7184 // Treat Neon vector types and most AltiVec vector types as if they are the
7185 // equivalent GCC vector types.
7186 const VectorType *First = FirstVec->getAs<VectorType>();
7187 const VectorType *Second = SecondVec->getAs<VectorType>();
7188 if (First->getNumElements() == Second->getNumElements() &&
7189 hasSameType(First->getElementType(), Second->getElementType()) &&
7190 First->getVectorKind() != VectorType::AltiVecPixel &&
7191 First->getVectorKind() != VectorType::AltiVecBool &&
7192 Second->getVectorKind() != VectorType::AltiVecPixel &&
7193 Second->getVectorKind() != VectorType::AltiVecBool)
7199 //===----------------------------------------------------------------------===//
7200 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7201 //===----------------------------------------------------------------------===//
7203 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7204 /// inheritance hierarchy of 'rProto'.
7206 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7207 ObjCProtocolDecl *rProto) const {
7208 if (declaresSameEntity(lProto, rProto))
7210 for (auto *PI : rProto->protocols())
7211 if (ProtocolCompatibleWithProtocol(lProto, PI))
7216 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7217 /// Class<pr1, ...>.
7218 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7220 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7221 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7222 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7224 for (auto *lhsProto : lhsQID->quals()) {
7226 for (auto *rhsProto : rhsOPT->quals()) {
7227 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7238 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7239 /// ObjCQualifiedIDType.
7240 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7242 // Allow id<P..> and an 'id' or void* type in all cases.
7243 if (lhs->isVoidPointerType() ||
7244 lhs->isObjCIdType() || lhs->isObjCClassType())
7246 else if (rhs->isVoidPointerType() ||
7247 rhs->isObjCIdType() || rhs->isObjCClassType())
7250 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
7251 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7253 if (!rhsOPT) return false;
7255 if (rhsOPT->qual_empty()) {
7256 // If the RHS is a unqualified interface pointer "NSString*",
7257 // make sure we check the class hierarchy.
7258 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7259 for (auto *I : lhsQID->quals()) {
7260 // when comparing an id<P> on lhs with a static type on rhs,
7261 // see if static class implements all of id's protocols, directly or
7262 // through its super class and categories.
7263 if (!rhsID->ClassImplementsProtocol(I, true))
7267 // If there are no qualifiers and no interface, we have an 'id'.
7270 // Both the right and left sides have qualifiers.
7271 for (auto *lhsProto : lhsQID->quals()) {
7274 // when comparing an id<P> on lhs with a static type on rhs,
7275 // see if static class implements all of id's protocols, directly or
7276 // through its super class and categories.
7277 for (auto *rhsProto : rhsOPT->quals()) {
7278 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7279 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7284 // If the RHS is a qualified interface pointer "NSString<P>*",
7285 // make sure we check the class hierarchy.
7286 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
7287 for (auto *I : lhsQID->quals()) {
7288 // when comparing an id<P> on lhs with a static type on rhs,
7289 // see if static class implements all of id's protocols, directly or
7290 // through its super class and categories.
7291 if (rhsID->ClassImplementsProtocol(I, true)) {
7304 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7305 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7307 if (const ObjCObjectPointerType *lhsOPT =
7308 lhs->getAsObjCInterfacePointerType()) {
7309 // If both the right and left sides have qualifiers.
7310 for (auto *lhsProto : lhsOPT->quals()) {
7313 // when comparing an id<P> on rhs with a static type on lhs,
7314 // see if static class implements all of id's protocols, directly or
7315 // through its super class and categories.
7316 // First, lhs protocols in the qualifier list must be found, direct
7317 // or indirect in rhs's qualifier list or it is a mismatch.
7318 for (auto *rhsProto : rhsQID->quals()) {
7319 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7320 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7329 // Static class's protocols, or its super class or category protocols
7330 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7331 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7332 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7333 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7334 // This is rather dubious but matches gcc's behavior. If lhs has
7335 // no type qualifier and its class has no static protocol(s)
7336 // assume that it is mismatch.
7337 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7339 for (auto *lhsProto : LHSInheritedProtocols) {
7341 for (auto *rhsProto : rhsQID->quals()) {
7342 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7343 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7357 /// canAssignObjCInterfaces - Return true if the two interface types are
7358 /// compatible for assignment from RHS to LHS. This handles validation of any
7359 /// protocol qualifiers on the LHS or RHS.
7361 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7362 const ObjCObjectPointerType *RHSOPT) {
7363 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7364 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7366 // If either type represents the built-in 'id' or 'Class' types, return true.
7367 if (LHS->isObjCUnqualifiedIdOrClass() ||
7368 RHS->isObjCUnqualifiedIdOrClass())
7371 // Function object that propagates a successful result or handles
7373 auto finish = [&](bool succeeded) -> bool {
7377 if (!RHS->isKindOfType())
7380 // Strip off __kindof and protocol qualifiers, then check whether
7381 // we can assign the other way.
7382 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7383 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7386 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7387 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7392 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7393 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7394 QualType(RHSOPT,0)));
7397 // If we have 2 user-defined types, fall into that path.
7398 if (LHS->getInterface() && RHS->getInterface()) {
7399 return finish(canAssignObjCInterfaces(LHS, RHS));
7405 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
7406 /// for providing type-safety for objective-c pointers used to pass/return
7407 /// arguments in block literals. When passed as arguments, passing 'A*' where
7408 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7409 /// not OK. For the return type, the opposite is not OK.
7410 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7411 const ObjCObjectPointerType *LHSOPT,
7412 const ObjCObjectPointerType *RHSOPT,
7413 bool BlockReturnType) {
7415 // Function object that propagates a successful result or handles
7417 auto finish = [&](bool succeeded) -> bool {
7421 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7422 if (!Expected->isKindOfType())
7425 // Strip off __kindof and protocol qualifiers, then check whether
7426 // we can assign the other way.
7427 return canAssignObjCInterfacesInBlockPointer(
7428 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7429 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7433 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
7436 if (LHSOPT->isObjCBuiltinType()) {
7437 return finish(RHSOPT->isObjCBuiltinType() ||
7438 RHSOPT->isObjCQualifiedIdType());
7441 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
7442 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7446 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7447 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7448 if (LHS && RHS) { // We have 2 user-defined types.
7450 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
7451 return finish(BlockReturnType);
7452 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
7453 return finish(!BlockReturnType);
7461 /// Comparison routine for Objective-C protocols to be used with
7462 /// llvm::array_pod_sort.
7463 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7464 ObjCProtocolDecl * const *rhs) {
7465 return (*lhs)->getName().compare((*rhs)->getName());
7469 /// getIntersectionOfProtocols - This routine finds the intersection of set
7470 /// of protocols inherited from two distinct objective-c pointer objects with
7471 /// the given common base.
7472 /// It is used to build composite qualifier list of the composite type of
7473 /// the conditional expression involving two objective-c pointer objects.
7475 void getIntersectionOfProtocols(ASTContext &Context,
7476 const ObjCInterfaceDecl *CommonBase,
7477 const ObjCObjectPointerType *LHSOPT,
7478 const ObjCObjectPointerType *RHSOPT,
7479 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
7481 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7482 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7483 assert(LHS->getInterface() && "LHS must have an interface base");
7484 assert(RHS->getInterface() && "RHS must have an interface base");
7486 // Add all of the protocols for the LHS.
7487 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7489 // Start with the protocol qualifiers.
7490 for (auto proto : LHS->quals()) {
7491 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
7494 // Also add the protocols associated with the LHS interface.
7495 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7497 // Add all of the protocls for the RHS.
7498 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7500 // Start with the protocol qualifiers.
7501 for (auto proto : RHS->quals()) {
7502 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
7505 // Also add the protocols associated with the RHS interface.
7506 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7508 // Compute the intersection of the collected protocol sets.
7509 for (auto proto : LHSProtocolSet) {
7510 if (RHSProtocolSet.count(proto))
7511 IntersectionSet.push_back(proto);
7514 // Compute the set of protocols that is implied by either the common type or
7515 // the protocols within the intersection.
7516 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7517 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7519 // Remove any implied protocols from the list of inherited protocols.
7520 if (!ImpliedProtocols.empty()) {
7521 IntersectionSet.erase(
7522 std::remove_if(IntersectionSet.begin(),
7523 IntersectionSet.end(),
7524 [&](ObjCProtocolDecl *proto) -> bool {
7525 return ImpliedProtocols.count(proto) > 0;
7527 IntersectionSet.end());
7530 // Sort the remaining protocols by name.
7531 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7532 compareObjCProtocolsByName);
7535 /// Determine whether the first type is a subtype of the second.
7536 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7538 // Common case: two object pointers.
7539 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7540 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7541 if (lhsOPT && rhsOPT)
7542 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7544 // Two block pointers.
7545 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7546 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7547 if (lhsBlock && rhsBlock)
7548 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7550 // If either is an unqualified 'id' and the other is a block, it's
7552 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7553 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7559 // Check that the given Objective-C type argument lists are equivalent.
7560 static bool sameObjCTypeArgs(ASTContext &ctx,
7561 const ObjCInterfaceDecl *iface,
7562 ArrayRef<QualType> lhsArgs,
7563 ArrayRef<QualType> rhsArgs,
7565 if (lhsArgs.size() != rhsArgs.size())
7568 ObjCTypeParamList *typeParams = iface->getTypeParamList();
7569 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
7570 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7573 switch (typeParams->begin()[i]->getVariance()) {
7574 case ObjCTypeParamVariance::Invariant:
7576 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7577 rhsArgs[i].stripObjCKindOfType(ctx))) {
7582 case ObjCTypeParamVariance::Covariant:
7583 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7587 case ObjCTypeParamVariance::Contravariant:
7588 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7597 QualType ASTContext::areCommonBaseCompatible(
7598 const ObjCObjectPointerType *Lptr,
7599 const ObjCObjectPointerType *Rptr) {
7600 const ObjCObjectType *LHS = Lptr->getObjectType();
7601 const ObjCObjectType *RHS = Rptr->getObjectType();
7602 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7603 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
7605 if (!LDecl || !RDecl)
7608 // When either LHS or RHS is a kindof type, we should return a kindof type.
7609 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7611 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7613 // Follow the left-hand side up the class hierarchy until we either hit a
7614 // root or find the RHS. Record the ancestors in case we don't find it.
7615 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7618 // Record this ancestor. We'll need this if the common type isn't in the
7619 // path from the LHS to the root.
7620 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
7622 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7623 // Get the type arguments.
7624 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7625 bool anyChanges = false;
7626 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7627 // Both have type arguments, compare them.
7628 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7629 LHS->getTypeArgs(), RHS->getTypeArgs(),
7630 /*stripKindOf=*/true))
7632 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7633 // If only one has type arguments, the result will not have type
7639 // Compute the intersection of protocols.
7640 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7641 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7643 if (!Protocols.empty())
7646 // If anything in the LHS will have changed, build a new result type.
7647 // If we need to return a kindof type but LHS is not a kindof type, we
7648 // build a new result type.
7649 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
7650 QualType Result = getObjCInterfaceType(LHS->getInterface());
7651 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7652 anyKindOf || LHS->isKindOfType());
7653 return getObjCObjectPointerType(Result);
7656 return getObjCObjectPointerType(QualType(LHS, 0));
7659 // Find the superclass.
7660 QualType LHSSuperType = LHS->getSuperClassType();
7661 if (LHSSuperType.isNull())
7664 LHS = LHSSuperType->castAs<ObjCObjectType>();
7667 // We didn't find anything by following the LHS to its root; now check
7668 // the RHS against the cached set of ancestors.
7670 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7671 if (KnownLHS != LHSAncestors.end()) {
7672 LHS = KnownLHS->second;
7674 // Get the type arguments.
7675 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7676 bool anyChanges = false;
7677 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7678 // Both have type arguments, compare them.
7679 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7680 LHS->getTypeArgs(), RHS->getTypeArgs(),
7681 /*stripKindOf=*/true))
7683 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7684 // If only one has type arguments, the result will not have type
7690 // Compute the intersection of protocols.
7691 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7692 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7694 if (!Protocols.empty())
7697 // If we need to return a kindof type but RHS is not a kindof type, we
7698 // build a new result type.
7699 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
7700 QualType Result = getObjCInterfaceType(RHS->getInterface());
7701 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7702 anyKindOf || RHS->isKindOfType());
7703 return getObjCObjectPointerType(Result);
7706 return getObjCObjectPointerType(QualType(RHS, 0));
7709 // Find the superclass of the RHS.
7710 QualType RHSSuperType = RHS->getSuperClassType();
7711 if (RHSSuperType.isNull())
7714 RHS = RHSSuperType->castAs<ObjCObjectType>();
7720 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7721 const ObjCObjectType *RHS) {
7722 assert(LHS->getInterface() && "LHS is not an interface type");
7723 assert(RHS->getInterface() && "RHS is not an interface type");
7725 // Verify that the base decls are compatible: the RHS must be a subclass of
7727 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7728 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7732 // If the LHS has protocol qualifiers, determine whether all of them are
7733 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7735 if (LHS->getNumProtocols() > 0) {
7736 // OK if conversion of LHS to SuperClass results in narrowing of types
7737 // ; i.e., SuperClass may implement at least one of the protocols
7738 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7739 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7740 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7741 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7742 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7744 for (auto *RHSPI : RHS->quals())
7745 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
7746 // If there is no protocols associated with RHS, it is not a match.
7747 if (SuperClassInheritedProtocols.empty())
7750 for (const auto *LHSProto : LHS->quals()) {
7751 bool SuperImplementsProtocol = false;
7752 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7753 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7754 SuperImplementsProtocol = true;
7757 if (!SuperImplementsProtocol)
7762 // If the LHS is specialized, we may need to check type arguments.
7763 if (LHS->isSpecialized()) {
7764 // Follow the superclass chain until we've matched the LHS class in the
7765 // hierarchy. This substitutes type arguments through.
7766 const ObjCObjectType *RHSSuper = RHS;
7767 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7768 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7770 // If the RHS is specializd, compare type arguments.
7771 if (RHSSuper->isSpecialized() &&
7772 !sameObjCTypeArgs(*this, LHS->getInterface(),
7773 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
7774 /*stripKindOf=*/true)) {
7782 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7783 // get the "pointed to" types
7784 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7785 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
7787 if (!LHSOPT || !RHSOPT)
7790 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7791 canAssignObjCInterfaces(RHSOPT, LHSOPT);
7794 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7795 return canAssignObjCInterfaces(
7796 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7797 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7800 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
7801 /// both shall have the identically qualified version of a compatible type.
7802 /// C99 6.2.7p1: Two types have compatible types if their types are the
7803 /// same. See 6.7.[2,3,5] for additional rules.
7804 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7805 bool CompareUnqualified) {
7806 if (getLangOpts().CPlusPlus)
7807 return hasSameType(LHS, RHS);
7809 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
7812 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
7813 return typesAreCompatible(LHS, RHS);
7816 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7817 return !mergeTypes(LHS, RHS, true).isNull();
7820 /// mergeTransparentUnionType - if T is a transparent union type and a member
7821 /// of T is compatible with SubType, return the merged type, else return
7823 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7824 bool OfBlockPointer,
7826 if (const RecordType *UT = T->getAsUnionType()) {
7827 RecordDecl *UD = UT->getDecl();
7828 if (UD->hasAttr<TransparentUnionAttr>()) {
7829 for (const auto *I : UD->fields()) {
7830 QualType ET = I->getType().getUnqualifiedType();
7831 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7841 /// mergeFunctionParameterTypes - merge two types which appear as function
7843 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7844 bool OfBlockPointer,
7846 // GNU extension: two types are compatible if they appear as a function
7847 // argument, one of the types is a transparent union type and the other
7848 // type is compatible with a union member
7849 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7851 if (!lmerge.isNull())
7854 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7856 if (!rmerge.isNull())
7859 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7862 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
7863 bool OfBlockPointer,
7865 const FunctionType *lbase = lhs->getAs<FunctionType>();
7866 const FunctionType *rbase = rhs->getAs<FunctionType>();
7867 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7868 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
7869 bool allLTypes = true;
7870 bool allRTypes = true;
7872 // Check return type
7874 if (OfBlockPointer) {
7875 QualType RHS = rbase->getReturnType();
7876 QualType LHS = lbase->getReturnType();
7877 bool UnqualifiedResult = Unqualified;
7878 if (!UnqualifiedResult)
7879 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
7880 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
7883 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
7885 if (retType.isNull()) return QualType();
7888 retType = retType.getUnqualifiedType();
7890 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7891 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
7893 LRetType = LRetType.getUnqualifiedType();
7894 RRetType = RRetType.getUnqualifiedType();
7897 if (getCanonicalType(retType) != LRetType)
7899 if (getCanonicalType(retType) != RRetType)
7902 // FIXME: double check this
7903 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7904 // rbase->getRegParmAttr() != 0 &&
7905 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
7906 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7907 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
7909 // Compatible functions must have compatible calling conventions
7910 if (lbaseInfo.getCC() != rbaseInfo.getCC())
7913 // Regparm is part of the calling convention.
7914 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7916 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7919 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7922 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7923 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
7925 if (lbaseInfo.getNoReturn() != NoReturn)
7927 if (rbaseInfo.getNoReturn() != NoReturn)
7930 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
7932 if (lproto && rproto) { // two C99 style function prototypes
7933 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7934 "C++ shouldn't be here");
7935 // Compatible functions must have the same number of parameters
7936 if (lproto->getNumParams() != rproto->getNumParams())
7939 // Variadic and non-variadic functions aren't compatible
7940 if (lproto->isVariadic() != rproto->isVariadic())
7943 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7946 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
7949 // Check parameter type compatibility
7950 SmallVector<QualType, 10> types;
7951 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7952 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7953 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7954 QualType paramType = mergeFunctionParameterTypes(
7955 lParamType, rParamType, OfBlockPointer, Unqualified);
7956 if (paramType.isNull())
7960 paramType = paramType.getUnqualifiedType();
7962 types.push_back(paramType);
7964 lParamType = lParamType.getUnqualifiedType();
7965 rParamType = rParamType.getUnqualifiedType();
7968 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
7970 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
7974 if (allLTypes) return lhs;
7975 if (allRTypes) return rhs;
7977 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7978 EPI.ExtInfo = einfo;
7979 return getFunctionType(retType, types, EPI);
7982 if (lproto) allRTypes = false;
7983 if (rproto) allLTypes = false;
7985 const FunctionProtoType *proto = lproto ? lproto : rproto;
7987 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7988 if (proto->isVariadic()) return QualType();
7989 // Check that the types are compatible with the types that
7990 // would result from default argument promotions (C99 6.7.5.3p15).
7991 // The only types actually affected are promotable integer
7992 // types and floats, which would be passed as a different
7993 // type depending on whether the prototype is visible.
7994 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7995 QualType paramTy = proto->getParamType(i);
7997 // Look at the converted type of enum types, since that is the type used
7998 // to pass enum values.
7999 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
8000 paramTy = Enum->getDecl()->getIntegerType();
8001 if (paramTy.isNull())
8005 if (paramTy->isPromotableIntegerType() ||
8006 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
8010 if (allLTypes) return lhs;
8011 if (allRTypes) return rhs;
8013 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8014 EPI.ExtInfo = einfo;
8015 return getFunctionType(retType, proto->getParamTypes(), EPI);
8018 if (allLTypes) return lhs;
8019 if (allRTypes) return rhs;
8020 return getFunctionNoProtoType(retType, einfo);
8023 /// Given that we have an enum type and a non-enum type, try to merge them.
8024 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8025 QualType other, bool isBlockReturnType) {
8026 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8027 // a signed integer type, or an unsigned integer type.
8028 // Compatibility is based on the underlying type, not the promotion
8030 QualType underlyingType = ET->getDecl()->getIntegerType();
8031 if (underlyingType.isNull()) return QualType();
8032 if (Context.hasSameType(underlyingType, other))
8035 // In block return types, we're more permissive and accept any
8036 // integral type of the same size.
8037 if (isBlockReturnType && other->isIntegerType() &&
8038 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8044 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
8045 bool OfBlockPointer,
8046 bool Unqualified, bool BlockReturnType) {
8047 // C++ [expr]: If an expression initially has the type "reference to T", the
8048 // type is adjusted to "T" prior to any further analysis, the expression
8049 // designates the object or function denoted by the reference, and the
8050 // expression is an lvalue unless the reference is an rvalue reference and
8051 // the expression is a function call (possibly inside parentheses).
8052 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8053 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
8056 LHS = LHS.getUnqualifiedType();
8057 RHS = RHS.getUnqualifiedType();
8060 QualType LHSCan = getCanonicalType(LHS),
8061 RHSCan = getCanonicalType(RHS);
8063 // If two types are identical, they are compatible.
8064 if (LHSCan == RHSCan)
8067 // If the qualifiers are different, the types aren't compatible... mostly.
8068 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8069 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8070 if (LQuals != RQuals) {
8071 // If any of these qualifiers are different, we have a type
8073 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8074 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
8075 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8076 LQuals.hasUnaligned() != RQuals.hasUnaligned())
8079 // Exactly one GC qualifier difference is allowed: __strong is
8080 // okay if the other type has no GC qualifier but is an Objective
8081 // C object pointer (i.e. implicitly strong by default). We fix
8082 // this by pretending that the unqualified type was actually
8083 // qualified __strong.
8084 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8085 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8086 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8088 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8091 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8092 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8094 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8095 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8100 // Okay, qualifiers are equal.
8102 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8103 Type::TypeClass RHSClass = RHSCan->getTypeClass();
8105 // We want to consider the two function types to be the same for these
8106 // comparisons, just force one to the other.
8107 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8108 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
8110 // Same as above for arrays
8111 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8112 LHSClass = Type::ConstantArray;
8113 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8114 RHSClass = Type::ConstantArray;
8116 // ObjCInterfaces are just specialized ObjCObjects.
8117 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8118 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8120 // Canonicalize ExtVector -> Vector.
8121 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8122 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
8124 // If the canonical type classes don't match.
8125 if (LHSClass != RHSClass) {
8126 // Note that we only have special rules for turning block enum
8127 // returns into block int returns, not vice-versa.
8128 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
8129 return mergeEnumWithInteger(*this, ETy, RHS, false);
8131 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
8132 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
8134 // allow block pointer type to match an 'id' type.
8135 if (OfBlockPointer && !BlockReturnType) {
8136 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8138 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8145 // The canonical type classes match.
8147 #define TYPE(Class, Base)
8148 #define ABSTRACT_TYPE(Class, Base)
8149 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
8150 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8151 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
8152 #include "clang/AST/TypeNodes.def"
8153 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
8156 case Type::DeducedTemplateSpecialization:
8157 case Type::LValueReference:
8158 case Type::RValueReference:
8159 case Type::MemberPointer:
8160 llvm_unreachable("C++ should never be in mergeTypes");
8162 case Type::ObjCInterface:
8163 case Type::IncompleteArray:
8164 case Type::VariableArray:
8165 case Type::FunctionProto:
8166 case Type::ExtVector:
8167 llvm_unreachable("Types are eliminated above");
8171 // Merge two pointer types, while trying to preserve typedef info
8172 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8173 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
8175 LHSPointee = LHSPointee.getUnqualifiedType();
8176 RHSPointee = RHSPointee.getUnqualifiedType();
8178 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8180 if (ResultType.isNull()) return QualType();
8181 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8183 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8185 return getPointerType(ResultType);
8187 case Type::BlockPointer:
8189 // Merge two block pointer types, while trying to preserve typedef info
8190 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8191 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
8193 LHSPointee = LHSPointee.getUnqualifiedType();
8194 RHSPointee = RHSPointee.getUnqualifiedType();
8196 if (getLangOpts().OpenCL) {
8197 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8198 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8199 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8200 // 6.12.5) thus the following check is asymmetric.
8201 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
8203 LHSPteeQual.removeAddressSpace();
8204 RHSPteeQual.removeAddressSpace();
8206 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8208 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8210 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8212 if (ResultType.isNull()) return QualType();
8213 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8215 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8217 return getBlockPointerType(ResultType);
8221 // Merge two pointer types, while trying to preserve typedef info
8222 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8223 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8225 LHSValue = LHSValue.getUnqualifiedType();
8226 RHSValue = RHSValue.getUnqualifiedType();
8228 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8230 if (ResultType.isNull()) return QualType();
8231 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8233 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8235 return getAtomicType(ResultType);
8237 case Type::ConstantArray:
8239 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8240 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8241 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8244 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8245 QualType RHSElem = getAsArrayType(RHS)->getElementType();
8247 LHSElem = LHSElem.getUnqualifiedType();
8248 RHSElem = RHSElem.getUnqualifiedType();
8251 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
8252 if (ResultType.isNull()) return QualType();
8253 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8255 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8257 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8258 ArrayType::ArraySizeModifier(), 0);
8259 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8260 ArrayType::ArraySizeModifier(), 0);
8261 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8262 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8263 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8265 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8268 // FIXME: This isn't correct! But tricky to implement because
8269 // the array's size has to be the size of LHS, but the type
8270 // has to be different.
8274 // FIXME: This isn't correct! But tricky to implement because
8275 // the array's size has to be the size of RHS, but the type
8276 // has to be different.
8279 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8280 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
8281 return getIncompleteArrayType(ResultType,
8282 ArrayType::ArraySizeModifier(), 0);
8284 case Type::FunctionNoProto:
8285 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
8290 // Only exactly equal builtin types are compatible, which is tested above.
8293 // Distinct complex types are incompatible.
8296 // FIXME: The merged type should be an ExtVector!
8297 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8298 RHSCan->getAs<VectorType>()))
8301 case Type::ObjCObject: {
8302 // Check if the types are assignment compatible.
8303 // FIXME: This should be type compatibility, e.g. whether
8304 // "LHS x; RHS x;" at global scope is legal.
8305 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8306 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8307 if (canAssignObjCInterfaces(LHSIface, RHSIface))
8312 case Type::ObjCObjectPointer: {
8313 if (OfBlockPointer) {
8314 if (canAssignObjCInterfacesInBlockPointer(
8315 LHS->getAs<ObjCObjectPointerType>(),
8316 RHS->getAs<ObjCObjectPointerType>(),
8321 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8322 RHS->getAs<ObjCObjectPointerType>()))
8329 assert(LHS != RHS &&
8330 "Equivalent pipe types should have already been handled!");
8335 llvm_unreachable("Invalid Type::Class!");
8338 bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
8339 const FunctionProtoType *firstFnType,
8340 const FunctionProtoType *secondFnType) {
8341 // Fast path: if the first type doesn't have ext parameter infos,
8342 // we match if and only if they second type also doesn't have them.
8343 if (!firstFnType->hasExtParameterInfos())
8344 return !secondFnType->hasExtParameterInfos();
8346 // Otherwise, we can only match if the second type has them.
8347 if (!secondFnType->hasExtParameterInfos())
8350 auto firstEPI = firstFnType->getExtParameterInfos();
8351 auto secondEPI = secondFnType->getExtParameterInfos();
8352 assert(firstEPI.size() == secondEPI.size());
8354 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8355 if (firstEPI[i] != secondEPI[i])
8361 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8362 ObjCLayouts[CD] = nullptr;
8365 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8366 /// 'RHS' attributes and returns the merged version; including for function
8368 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8369 QualType LHSCan = getCanonicalType(LHS),
8370 RHSCan = getCanonicalType(RHS);
8371 // If two types are identical, they are compatible.
8372 if (LHSCan == RHSCan)
8374 if (RHSCan->isFunctionType()) {
8375 if (!LHSCan->isFunctionType())
8377 QualType OldReturnType =
8378 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
8379 QualType NewReturnType =
8380 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
8381 QualType ResReturnType =
8382 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8383 if (ResReturnType.isNull())
8385 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8386 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8387 // In either case, use OldReturnType to build the new function type.
8388 const FunctionType *F = LHS->getAs<FunctionType>();
8389 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
8390 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8391 EPI.ExtInfo = getFunctionExtInfo(LHS);
8392 QualType ResultType =
8393 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
8400 // If the qualifiers are different, the types can still be merged.
8401 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8402 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8403 if (LQuals != RQuals) {
8404 // If any of these qualifiers are different, we have a type mismatch.
8405 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8406 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8409 // Exactly one GC qualifier difference is allowed: __strong is
8410 // okay if the other type has no GC qualifier but is an Objective
8411 // C object pointer (i.e. implicitly strong by default). We fix
8412 // this by pretending that the unqualified type was actually
8413 // qualified __strong.
8414 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8415 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8416 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8418 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8421 if (GC_L == Qualifiers::Strong)
8423 if (GC_R == Qualifiers::Strong)
8428 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8429 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8430 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8431 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8432 if (ResQT == LHSBaseQT)
8434 if (ResQT == RHSBaseQT)
8440 //===----------------------------------------------------------------------===//
8441 // Integer Predicates
8442 //===----------------------------------------------------------------------===//
8444 unsigned ASTContext::getIntWidth(QualType T) const {
8445 if (const EnumType *ET = T->getAs<EnumType>())
8446 T = ET->getDecl()->getIntegerType();
8447 if (T->isBooleanType())
8449 // For builtin types, just use the standard type sizing method
8450 return (unsigned)getTypeSize(T);
8453 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
8454 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
8456 // Turn <4 x signed int> -> <4 x unsigned int>
8457 if (const VectorType *VTy = T->getAs<VectorType>())
8458 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
8459 VTy->getNumElements(), VTy->getVectorKind());
8461 // For enums, we return the unsigned version of the base type.
8462 if (const EnumType *ETy = T->getAs<EnumType>())
8463 T = ETy->getDecl()->getIntegerType();
8465 const BuiltinType *BTy = T->getAs<BuiltinType>();
8466 assert(BTy && "Unexpected signed integer type");
8467 switch (BTy->getKind()) {
8468 case BuiltinType::Char_S:
8469 case BuiltinType::SChar:
8470 return UnsignedCharTy;
8471 case BuiltinType::Short:
8472 return UnsignedShortTy;
8473 case BuiltinType::Int:
8474 return UnsignedIntTy;
8475 case BuiltinType::Long:
8476 return UnsignedLongTy;
8477 case BuiltinType::LongLong:
8478 return UnsignedLongLongTy;
8479 case BuiltinType::Int128:
8480 return UnsignedInt128Ty;
8482 llvm_unreachable("Unexpected signed integer type");
8486 ASTMutationListener::~ASTMutationListener() { }
8488 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8489 QualType ReturnType) {}
8491 //===----------------------------------------------------------------------===//
8492 // Builtin Type Computation
8493 //===----------------------------------------------------------------------===//
8495 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
8496 /// pointer over the consumed characters. This returns the resultant type. If
8497 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8498 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8499 /// a vector of "i*".
8501 /// RequiresICE is filled in on return to indicate whether the value is required
8502 /// to be an Integer Constant Expression.
8503 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
8504 ASTContext::GetBuiltinTypeError &Error,
8506 bool AllowTypeModifiers) {
8509 bool Signed = false, Unsigned = false;
8510 RequiresICE = false;
8512 // Read the prefixed modifiers first.
8516 default: Done = true; --Str; break;
8521 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8522 assert(!Signed && "Can't use 'S' modifier multiple times!");
8526 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
8527 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
8531 assert(HowLong <= 2 && "Can't have LLLL modifier");
8535 // This modifier represents int64 type.
8536 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8537 switch (Context.getTargetInfo().getInt64Type()) {
8539 llvm_unreachable("Unexpected integer type");
8540 case TargetInfo::SignedLong:
8543 case TargetInfo::SignedLongLong:
8552 // Read the base type.
8554 default: llvm_unreachable("Unknown builtin type letter!");
8556 assert(HowLong == 0 && !Signed && !Unsigned &&
8557 "Bad modifiers used with 'v'!");
8558 Type = Context.VoidTy;
8561 assert(HowLong == 0 && !Signed && !Unsigned &&
8562 "Bad modifiers used with 'h'!");
8563 Type = Context.HalfTy;
8566 assert(HowLong == 0 && !Signed && !Unsigned &&
8567 "Bad modifiers used with 'f'!");
8568 Type = Context.FloatTy;
8571 assert(HowLong < 2 && !Signed && !Unsigned &&
8572 "Bad modifiers used with 'd'!");
8574 Type = Context.LongDoubleTy;
8576 Type = Context.DoubleTy;
8579 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8581 Type = Context.UnsignedShortTy;
8583 Type = Context.ShortTy;
8587 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8588 else if (HowLong == 2)
8589 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8590 else if (HowLong == 1)
8591 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8593 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8596 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8598 Type = Context.SignedCharTy;
8600 Type = Context.UnsignedCharTy;
8602 Type = Context.CharTy;
8604 case 'b': // boolean
8605 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8606 Type = Context.BoolTy;
8608 case 'z': // size_t.
8609 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8610 Type = Context.getSizeType();
8612 case 'w': // wchar_t.
8613 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8614 Type = Context.getWideCharType();
8617 Type = Context.getCFConstantStringType();
8620 Type = Context.getObjCIdType();
8623 Type = Context.getObjCSelType();
8626 Type = Context.getObjCSuperType();
8629 Type = Context.getBuiltinVaListType();
8630 assert(!Type.isNull() && "builtin va list type not initialized!");
8633 // This is a "reference" to a va_list; however, what exactly
8634 // this means depends on how va_list is defined. There are two
8635 // different kinds of va_list: ones passed by value, and ones
8636 // passed by reference. An example of a by-value va_list is
8637 // x86, where va_list is a char*. An example of by-ref va_list
8638 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8639 // we want this argument to be a char*&; for x86-64, we want
8640 // it to be a __va_list_tag*.
8641 Type = Context.getBuiltinVaListType();
8642 assert(!Type.isNull() && "builtin va list type not initialized!");
8643 if (Type->isArrayType())
8644 Type = Context.getArrayDecayedType(Type);
8646 Type = Context.getLValueReferenceType(Type);
8650 unsigned NumElements = strtoul(Str, &End, 10);
8651 assert(End != Str && "Missing vector size");
8654 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8655 RequiresICE, false);
8656 assert(!RequiresICE && "Can't require vector ICE");
8658 // TODO: No way to make AltiVec vectors in builtins yet.
8659 Type = Context.getVectorType(ElementType, NumElements,
8660 VectorType::GenericVector);
8666 unsigned NumElements = strtoul(Str, &End, 10);
8667 assert(End != Str && "Missing vector size");
8671 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8673 Type = Context.getExtVectorType(ElementType, NumElements);
8677 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8679 assert(!RequiresICE && "Can't require complex ICE");
8680 Type = Context.getComplexType(ElementType);
8684 Type = Context.getPointerDiffType();
8688 Type = Context.getFILEType();
8689 if (Type.isNull()) {
8690 Error = ASTContext::GE_Missing_stdio;
8696 Type = Context.getsigjmp_bufType();
8698 Type = Context.getjmp_bufType();
8700 if (Type.isNull()) {
8701 Error = ASTContext::GE_Missing_setjmp;
8706 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8707 Type = Context.getucontext_tType();
8709 if (Type.isNull()) {
8710 Error = ASTContext::GE_Missing_ucontext;
8715 Type = Context.getProcessIDType();
8719 // If there are modifiers and if we're allowed to parse them, go for it.
8720 Done = !AllowTypeModifiers;
8722 switch (char c = *Str++) {
8723 default: Done = true; --Str; break;
8726 // Both pointers and references can have their pointee types
8727 // qualified with an address space.
8729 unsigned AddrSpace = strtoul(Str, &End, 10);
8730 if (End != Str && AddrSpace != 0) {
8731 Type = Context.getAddrSpaceQualType(Type, AddrSpace +
8736 Type = Context.getPointerType(Type);
8738 Type = Context.getLValueReferenceType(Type);
8741 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8743 Type = Type.withConst();
8746 Type = Context.getVolatileType(Type);
8749 Type = Type.withRestrict();
8754 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
8755 "Integer constant 'I' type must be an integer");
8760 /// GetBuiltinType - Return the type for the specified builtin.
8761 QualType ASTContext::GetBuiltinType(unsigned Id,
8762 GetBuiltinTypeError &Error,
8763 unsigned *IntegerConstantArgs) const {
8764 const char *TypeStr = BuiltinInfo.getTypeString(Id);
8766 SmallVector<QualType, 8> ArgTypes;
8768 bool RequiresICE = false;
8770 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8772 if (Error != GE_None)
8775 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8777 while (TypeStr[0] && TypeStr[0] != '.') {
8778 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
8779 if (Error != GE_None)
8782 // If this argument is required to be an IntegerConstantExpression and the
8783 // caller cares, fill in the bitmask we return.
8784 if (RequiresICE && IntegerConstantArgs)
8785 *IntegerConstantArgs |= 1 << ArgTypes.size();
8787 // Do array -> pointer decay. The builtin should use the decayed type.
8788 if (Ty->isArrayType())
8789 Ty = getArrayDecayedType(Ty);
8791 ArgTypes.push_back(Ty);
8794 if (Id == Builtin::BI__GetExceptionInfo)
8797 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8798 "'.' should only occur at end of builtin type list!");
8800 FunctionType::ExtInfo EI(CC_C);
8801 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8803 bool Variadic = (TypeStr[0] == '.');
8805 // We really shouldn't be making a no-proto type here.
8806 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
8807 return getFunctionNoProtoType(ResType, EI);
8809 FunctionProtoType::ExtProtoInfo EPI;
8811 EPI.Variadic = Variadic;
8812 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
8813 EPI.ExceptionSpec.Type =
8814 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
8816 return getFunctionType(ResType, ArgTypes, EPI);
8819 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8820 const FunctionDecl *FD) {
8821 if (!FD->isExternallyVisible())
8822 return GVA_Internal;
8824 GVALinkage External;
8825 switch (FD->getTemplateSpecializationKind()) {
8826 case TSK_Undeclared:
8827 case TSK_ExplicitSpecialization:
8828 External = GVA_StrongExternal;
8831 case TSK_ExplicitInstantiationDefinition:
8832 return GVA_StrongODR;
8834 // C++11 [temp.explicit]p10:
8835 // [ Note: The intent is that an inline function that is the subject of
8836 // an explicit instantiation declaration will still be implicitly
8837 // instantiated when used so that the body can be considered for
8838 // inlining, but that no out-of-line copy of the inline function would be
8839 // generated in the translation unit. -- end note ]
8840 case TSK_ExplicitInstantiationDeclaration:
8841 return GVA_AvailableExternally;
8843 case TSK_ImplicitInstantiation:
8844 External = GVA_DiscardableODR;
8848 if (!FD->isInlined())
8851 if ((!Context.getLangOpts().CPlusPlus &&
8852 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8853 !FD->hasAttr<DLLExportAttr>()) ||
8854 FD->hasAttr<GNUInlineAttr>()) {
8855 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8857 // GNU or C99 inline semantics. Determine whether this symbol should be
8858 // externally visible.
8859 if (FD->isInlineDefinitionExternallyVisible())
8862 // C99 inline semantics, where the symbol is not externally visible.
8863 return GVA_AvailableExternally;
8866 // Functions specified with extern and inline in -fms-compatibility mode
8867 // forcibly get emitted. While the body of the function cannot be later
8868 // replaced, the function definition cannot be discarded.
8869 if (FD->isMSExternInline())
8870 return GVA_StrongODR;
8872 return GVA_DiscardableODR;
8875 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8876 GVALinkage L, const Decl *D) {
8877 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8878 // dllexport/dllimport on inline functions.
8879 if (D->hasAttr<DLLImportAttr>()) {
8880 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8881 return GVA_AvailableExternally;
8882 } else if (D->hasAttr<DLLExportAttr>()) {
8883 if (L == GVA_DiscardableODR)
8884 return GVA_StrongODR;
8885 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8886 D->hasAttr<CUDAGlobalAttr>()) {
8887 // Device-side functions with __global__ attribute must always be
8888 // visible externally so they can be launched from host.
8889 if (L == GVA_DiscardableODR || L == GVA_Internal)
8890 return GVA_StrongODR;
8895 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8896 auto L = adjustGVALinkageForAttributes(
8897 *this, basicGVALinkageForFunction(*this, FD), FD);
8898 auto EK = ExternalASTSource::EK_ReplyHazy;
8899 if (auto *Ext = getExternalSource())
8900 EK = Ext->hasExternalDefinitions(FD);
8902 case ExternalASTSource::EK_Never:
8903 if (L == GVA_DiscardableODR)
8904 return GVA_StrongODR;
8906 case ExternalASTSource::EK_Always:
8907 return GVA_AvailableExternally;
8908 case ExternalASTSource::EK_ReplyHazy:
8914 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8915 const VarDecl *VD) {
8916 if (!VD->isExternallyVisible())
8917 return GVA_Internal;
8919 if (VD->isStaticLocal()) {
8920 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8921 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8922 LexicalContext = LexicalContext->getLexicalParent();
8924 // ObjC Blocks can create local variables that don't have a FunctionDecl
8926 if (!LexicalContext)
8927 return GVA_DiscardableODR;
8929 // Otherwise, let the static local variable inherit its linkage from the
8930 // nearest enclosing function.
8931 auto StaticLocalLinkage =
8932 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8934 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
8935 // be emitted in any object with references to the symbol for the object it
8936 // contains, whether inline or out-of-line."
8937 // Similar behavior is observed with MSVC. An alternative ABI could use
8938 // StrongODR/AvailableExternally to match the function, but none are
8939 // known/supported currently.
8940 if (StaticLocalLinkage == GVA_StrongODR ||
8941 StaticLocalLinkage == GVA_AvailableExternally)
8942 return GVA_DiscardableODR;
8943 return StaticLocalLinkage;
8946 // MSVC treats in-class initialized static data members as definitions.
8947 // By giving them non-strong linkage, out-of-line definitions won't
8948 // cause link errors.
8949 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8950 return GVA_DiscardableODR;
8952 // Most non-template variables have strong linkage; inline variables are
8953 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8954 GVALinkage StrongLinkage;
8955 switch (Context.getInlineVariableDefinitionKind(VD)) {
8956 case ASTContext::InlineVariableDefinitionKind::None:
8957 StrongLinkage = GVA_StrongExternal;
8959 case ASTContext::InlineVariableDefinitionKind::Weak:
8960 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
8961 StrongLinkage = GVA_DiscardableODR;
8963 case ASTContext::InlineVariableDefinitionKind::Strong:
8964 StrongLinkage = GVA_StrongODR;
8968 switch (VD->getTemplateSpecializationKind()) {
8969 case TSK_Undeclared:
8970 return StrongLinkage;
8972 case TSK_ExplicitSpecialization:
8973 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8974 VD->isStaticDataMember()
8978 case TSK_ExplicitInstantiationDefinition:
8979 return GVA_StrongODR;
8981 case TSK_ExplicitInstantiationDeclaration:
8982 return GVA_AvailableExternally;
8984 case TSK_ImplicitInstantiation:
8985 return GVA_DiscardableODR;
8988 llvm_unreachable("Invalid Linkage!");
8991 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8992 return adjustGVALinkageForAttributes(
8993 *this, basicGVALinkageForVariable(*this, VD), VD);
8996 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
8997 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8998 if (!VD->isFileVarDecl())
9000 // Global named register variables (GNU extension) are never emitted.
9001 if (VD->getStorageClass() == SC_Register)
9003 if (VD->getDescribedVarTemplate() ||
9004 isa<VarTemplatePartialSpecializationDecl>(VD))
9006 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9007 // We never need to emit an uninstantiated function template.
9008 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9010 } else if (isa<PragmaCommentDecl>(D))
9012 else if (isa<OMPThreadPrivateDecl>(D) ||
9013 D->hasAttr<OMPDeclareTargetDeclAttr>())
9015 else if (isa<PragmaDetectMismatchDecl>(D))
9017 else if (isa<OMPThreadPrivateDecl>(D))
9018 return !D->getDeclContext()->isDependentContext();
9019 else if (isa<OMPDeclareReductionDecl>(D))
9020 return !D->getDeclContext()->isDependentContext();
9021 else if (isa<ImportDecl>(D))
9026 // If this is a member of a class template, we do not need to emit it.
9027 if (D->getDeclContext()->isDependentContext())
9030 // Weak references don't produce any output by themselves.
9031 if (D->hasAttr<WeakRefAttr>())
9034 // Aliases and used decls are required.
9035 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9038 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9039 // Forward declarations aren't required.
9040 if (!FD->doesThisDeclarationHaveABody())
9041 return FD->doesDeclarationForceExternallyVisibleDefinition();
9043 // Constructors and destructors are required.
9044 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9047 // The key function for a class is required. This rule only comes
9048 // into play when inline functions can be key functions, though.
9049 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
9050 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9051 const CXXRecordDecl *RD = MD->getParent();
9052 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9053 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9054 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9060 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9062 // static, static inline, always_inline, and extern inline functions can
9063 // always be deferred. Normal inline functions can be deferred in C99/C++.
9064 // Implicit template instantiations can also be deferred in C++.
9065 return !isDiscardableGVALinkage(Linkage);
9068 const VarDecl *VD = cast<VarDecl>(D);
9069 assert(VD->isFileVarDecl() && "Expected file scoped var");
9071 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9072 !isMSStaticDataMemberInlineDefinition(VD))
9075 // Variables that can be needed in other TUs are required.
9076 if (!isDiscardableGVALinkage(GetGVALinkageForVariable(VD)))
9079 // Variables that have destruction with side-effects are required.
9080 if (VD->getType().isDestructedType())
9083 // Variables that have initialization with side-effects are required.
9084 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
9085 // We can get a value-dependent initializer during error recovery.
9086 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
9089 // Likewise, variables with tuple-like bindings are required if their
9090 // bindings have side-effects.
9091 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
9092 for (auto *BD : DD->bindings())
9093 if (auto *BindingVD = BD->getHoldingVar())
9094 if (DeclMustBeEmitted(BindingVD))
9100 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9101 bool IsCXXMethod) const {
9102 // Pass through to the C++ ABI object
9104 return ABI->getDefaultMethodCallConv(IsVariadic);
9106 switch (LangOpts.getDefaultCallingConv()) {
9107 case LangOptions::DCC_None:
9109 case LangOptions::DCC_CDecl:
9111 case LangOptions::DCC_FastCall:
9112 if (getTargetInfo().hasFeature("sse2"))
9113 return CC_X86FastCall;
9115 case LangOptions::DCC_StdCall:
9117 return CC_X86StdCall;
9119 case LangOptions::DCC_VectorCall:
9120 // __vectorcall cannot be applied to variadic functions.
9122 return CC_X86VectorCall;
9125 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
9128 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
9129 // Pass through to the C++ ABI object
9130 return ABI->isNearlyEmpty(RD);
9133 VTableContextBase *ASTContext::getVTableContext() {
9134 if (!VTContext.get()) {
9135 if (Target->getCXXABI().isMicrosoft())
9136 VTContext.reset(new MicrosoftVTableContext(*this));
9138 VTContext.reset(new ItaniumVTableContext(*this));
9140 return VTContext.get();
9143 MangleContext *ASTContext::createMangleContext() {
9144 switch (Target->getCXXABI().getKind()) {
9145 case TargetCXXABI::GenericAArch64:
9146 case TargetCXXABI::GenericItanium:
9147 case TargetCXXABI::GenericARM:
9148 case TargetCXXABI::GenericMIPS:
9149 case TargetCXXABI::iOS:
9150 case TargetCXXABI::iOS64:
9151 case TargetCXXABI::WebAssembly:
9152 case TargetCXXABI::WatchOS:
9153 return ItaniumMangleContext::create(*this, getDiagnostics());
9154 case TargetCXXABI::Microsoft:
9155 return MicrosoftMangleContext::create(*this, getDiagnostics());
9157 llvm_unreachable("Unsupported ABI");
9160 CXXABI::~CXXABI() {}
9162 size_t ASTContext::getSideTableAllocatedMemory() const {
9163 return ASTRecordLayouts.getMemorySize() +
9164 llvm::capacity_in_bytes(ObjCLayouts) +
9165 llvm::capacity_in_bytes(KeyFunctions) +
9166 llvm::capacity_in_bytes(ObjCImpls) +
9167 llvm::capacity_in_bytes(BlockVarCopyInits) +
9168 llvm::capacity_in_bytes(DeclAttrs) +
9169 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9170 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9171 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9172 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9173 llvm::capacity_in_bytes(OverriddenMethods) +
9174 llvm::capacity_in_bytes(Types) +
9175 llvm::capacity_in_bytes(VariableArrayTypes) +
9176 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
9179 /// getIntTypeForBitwidth -
9180 /// sets integer QualTy according to specified details:
9181 /// bitwidth, signed/unsigned.
9182 /// Returns empty type if there is no appropriate target types.
9183 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9184 unsigned Signed) const {
9185 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9186 CanQualType QualTy = getFromTargetType(Ty);
9187 if (!QualTy && DestWidth == 128)
9188 return Signed ? Int128Ty : UnsignedInt128Ty;
9192 /// getRealTypeForBitwidth -
9193 /// sets floating point QualTy according to specified bitwidth.
9194 /// Returns empty type if there is no appropriate target types.
9195 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9196 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9198 case TargetInfo::Float:
9200 case TargetInfo::Double:
9202 case TargetInfo::LongDouble:
9203 return LongDoubleTy;
9204 case TargetInfo::Float128:
9206 case TargetInfo::NoFloat:
9210 llvm_unreachable("Unhandled TargetInfo::RealType value");
9213 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9215 MangleNumbers[ND] = Number;
9218 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
9219 auto I = MangleNumbers.find(ND);
9220 return I != MangleNumbers.end() ? I->second : 1;
9223 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9225 StaticLocalNumbers[VD] = Number;
9228 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
9229 auto I = StaticLocalNumbers.find(VD);
9230 return I != StaticLocalNumbers.end() ? I->second : 1;
9233 MangleNumberingContext &
9234 ASTContext::getManglingNumberContext(const DeclContext *DC) {
9235 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
9236 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
9238 MCtx = createMangleNumberingContext();
9242 std::unique_ptr<MangleNumberingContext>
9243 ASTContext::createMangleNumberingContext() const {
9244 return ABI->createMangleNumberingContext();
9247 const CXXConstructorDecl *
9248 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9249 return ABI->getCopyConstructorForExceptionObject(
9250 cast<CXXRecordDecl>(RD->getFirstDecl()));
9253 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9254 CXXConstructorDecl *CD) {
9255 return ABI->addCopyConstructorForExceptionObject(
9256 cast<CXXRecordDecl>(RD->getFirstDecl()),
9257 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9260 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9261 TypedefNameDecl *DD) {
9262 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9266 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9267 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9270 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9271 DeclaratorDecl *DD) {
9272 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9275 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9276 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9279 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9280 ParamIndices[D] = index;
9283 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9284 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9285 assert(I != ParamIndices.end() &&
9286 "ParmIndices lacks entry set by ParmVarDecl");
9291 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9293 assert(E && E->getStorageDuration() == SD_Static &&
9294 "don't need to cache the computed value for this temporary");
9296 APValue *&MTVI = MaterializedTemporaryValues[E];
9298 MTVI = new (*this) APValue;
9302 return MaterializedTemporaryValues.lookup(E);
9305 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9306 const llvm::Triple &T = getTargetInfo().getTriple();
9307 if (!T.isOSDarwin())
9310 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9311 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9314 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9315 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9316 uint64_t Size = sizeChars.getQuantity();
9317 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9318 unsigned Align = alignChars.getQuantity();
9319 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9320 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9325 ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
9326 ASTContext::ParentMapPointers::mapped_type U) {
9327 if (const auto *D = U.dyn_cast<const Decl *>())
9328 return ast_type_traits::DynTypedNode::create(*D);
9329 if (const auto *S = U.dyn_cast<const Stmt *>())
9330 return ast_type_traits::DynTypedNode::create(*S);
9331 return *U.get<ast_type_traits::DynTypedNode *>();
9334 /// Template specializations to abstract away from pointers and TypeLocs.
9336 template <typename T>
9337 ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9338 return ast_type_traits::DynTypedNode::create(*Node);
9341 ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9342 return ast_type_traits::DynTypedNode::create(Node);
9345 ast_type_traits::DynTypedNode
9346 createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9347 return ast_type_traits::DynTypedNode::create(Node);
9351 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9352 /// parents as defined by the \c RecursiveASTVisitor.
9354 /// Note that the relationship described here is purely in terms of AST
9355 /// traversal - there are other relationships (for example declaration context)
9356 /// in the AST that are better modeled by special matchers.
9358 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
9359 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
9361 /// \brief Builds and returns the translation unit's parent map.
9363 /// The caller takes ownership of the returned \c ParentMap.
9364 static std::pair<ASTContext::ParentMapPointers *,
9365 ASTContext::ParentMapOtherNodes *>
9366 buildMap(TranslationUnitDecl &TU) {
9367 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9368 new ASTContext::ParentMapOtherNodes);
9369 Visitor.TraverseDecl(&TU);
9370 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
9374 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9376 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9377 ASTContext::ParentMapOtherNodes *OtherParents)
9378 : Parents(Parents), OtherParents(OtherParents) {}
9380 bool shouldVisitTemplateInstantiations() const {
9383 bool shouldVisitImplicitCode() const {
9387 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9389 bool TraverseNode(T Node, MapNodeTy MapNode,
9390 BaseTraverseFn BaseTraverse, MapTy *Parents) {
9393 if (ParentStack.size() > 0) {
9394 // FIXME: Currently we add the same parent multiple times, but only
9395 // when no memoization data is available for the type.
9396 // For example when we visit all subexpressions of template
9397 // instantiations; this is suboptimal, but benign: the only way to
9398 // visit those is with hasAncestor / hasParent, and those do not create
9400 // The plan is to enable DynTypedNode to be storable in a map or hash
9401 // map. The main problem there is to implement hash functions /
9402 // comparison operators for all types that DynTypedNode supports that
9403 // do not have pointer identity.
9404 auto &NodeOrVector = (*Parents)[MapNode];
9405 if (NodeOrVector.isNull()) {
9406 if (const auto *D = ParentStack.back().get<Decl>())
9408 else if (const auto *S = ParentStack.back().get<Stmt>())
9412 new ast_type_traits::DynTypedNode(ParentStack.back());
9414 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9415 auto *Vector = new ASTContext::ParentVector(
9416 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
9418 .template dyn_cast<ast_type_traits::DynTypedNode *>();
9419 NodeOrVector = Vector;
9423 NodeOrVector.template get<ASTContext::ParentVector *>();
9424 // Skip duplicates for types that have memoization data.
9425 // We must check that the type has memoization data before calling
9426 // std::find() because DynTypedNode::operator== can't compare all
9428 bool Found = ParentStack.back().getMemoizationData() &&
9429 std::find(Vector->begin(), Vector->end(),
9430 ParentStack.back()) != Vector->end();
9432 Vector->push_back(ParentStack.back());
9435 ParentStack.push_back(createDynTypedNode(Node));
9436 bool Result = BaseTraverse();
9437 ParentStack.pop_back();
9441 bool TraverseDecl(Decl *DeclNode) {
9442 return TraverseNode(DeclNode, DeclNode,
9443 [&] { return VisitorBase::TraverseDecl(DeclNode); },
9447 bool TraverseStmt(Stmt *StmtNode) {
9448 return TraverseNode(StmtNode, StmtNode,
9449 [&] { return VisitorBase::TraverseStmt(StmtNode); },
9453 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
9454 return TraverseNode(
9455 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9456 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9460 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9461 return TraverseNode(
9462 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
9464 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9469 ASTContext::ParentMapPointers *Parents;
9470 ASTContext::ParentMapOtherNodes *OtherParents;
9471 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9473 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9476 } // anonymous namespace
9478 template <typename NodeTy, typename MapTy>
9479 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9481 auto I = Map.find(Node);
9482 if (I == Map.end()) {
9483 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
9485 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
9486 return llvm::makeArrayRef(*V);
9488 return getSingleDynTypedNodeFromParentMap(I->second);
9491 ASTContext::DynTypedNodeList
9492 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9493 if (!PointerParents) {
9494 // We always need to run over the whole translation unit, as
9495 // hasAncestor can escape any subtree.
9496 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9497 PointerParents.reset(Maps.first);
9498 OtherParents.reset(Maps.second);
9500 if (Node.getNodeKind().hasPointerIdentity())
9501 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9502 return getDynNodeFromMap(Node, *OtherParents);
9506 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9507 const ObjCMethodDecl *MethodImpl) {
9508 // No point trying to match an unavailable/deprecated mothod.
9509 if (MethodDecl->hasAttr<UnavailableAttr>()
9510 || MethodDecl->hasAttr<DeprecatedAttr>())
9512 if (MethodDecl->getObjCDeclQualifier() !=
9513 MethodImpl->getObjCDeclQualifier())
9515 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
9518 if (MethodDecl->param_size() != MethodImpl->param_size())
9521 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9522 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9523 EF = MethodDecl->param_end();
9524 IM != EM && IF != EF; ++IM, ++IF) {
9525 const ParmVarDecl *DeclVar = (*IF);
9526 const ParmVarDecl *ImplVar = (*IM);
9527 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9529 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9532 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9536 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
9538 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
9541 AS = QT->getPointeeType().getAddressSpace();
9543 return getTargetInfo().getNullPointerValue(AS);
9546 unsigned ASTContext::getTargetAddressSpace(unsigned AS) const {
9547 // For OpenCL, only function local variables are not explicitly marked with
9548 // an address space in the AST, and these need to be the address space of
9550 if (!AS && LangOpts.OpenCL)
9551 return getTargetInfo().getDataLayout().getAllocaAddrSpace();
9552 if (AS >= LangAS::Count)
9553 return AS - LangAS::Count;
9555 return (*AddrSpaceMap)[AS];
9558 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9559 // doesn't include ASTContext.h
9561 clang::LazyGenerationalUpdatePtr<
9562 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9563 clang::LazyGenerationalUpdatePtr<
9564 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9565 const clang::ASTContext &Ctx, Decl *Value);