1 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ASTContext interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Comment.h"
20 #include "clang/AST/CommentCommandTraits.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclContextInternals.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExternalASTSource.h"
28 #include "clang/AST/Mangle.h"
29 #include "clang/AST/MangleNumberingContext.h"
30 #include "clang/AST/RecordLayout.h"
31 #include "clang/AST/RecursiveASTVisitor.h"
32 #include "clang/AST/TypeLoc.h"
33 #include "clang/AST/VTableBuilder.h"
34 #include "clang/Basic/Builtins.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/Support/Capacity.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/raw_ostream.h"
45 using namespace clang;
47 unsigned ASTContext::NumImplicitDefaultConstructors;
48 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
49 unsigned ASTContext::NumImplicitCopyConstructors;
50 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
51 unsigned ASTContext::NumImplicitMoveConstructors;
52 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
53 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
54 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
55 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
56 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
57 unsigned ASTContext::NumImplicitDestructors;
58 unsigned ASTContext::NumImplicitDestructorsDeclared;
61 HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
64 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
65 if (!CommentsLoaded && ExternalSource) {
66 ExternalSource->ReadComments();
69 ArrayRef<RawComment *> RawComments = Comments.getComments();
70 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
71 BeforeThanCompare<RawComment>(SourceMgr)));
74 CommentsLoaded = true;
79 // User can not attach documentation to implicit declarations.
83 // User can not attach documentation to implicit instantiations.
84 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
85 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
89 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
90 if (VD->isStaticDataMember() &&
91 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
95 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
96 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
100 if (const ClassTemplateSpecializationDecl *CTSD =
101 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
102 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
103 if (TSK == TSK_ImplicitInstantiation ||
104 TSK == TSK_Undeclared)
108 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
109 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
112 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
113 // When tag declaration (but not definition!) is part of the
114 // decl-specifier-seq of some other declaration, it doesn't get comment
115 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
118 // TODO: handle comments for function parameters properly.
119 if (isa<ParmVarDecl>(D))
122 // TODO: we could look up template parameter documentation in the template
124 if (isa<TemplateTypeParmDecl>(D) ||
125 isa<NonTypeTemplateParmDecl>(D) ||
126 isa<TemplateTemplateParmDecl>(D))
129 ArrayRef<RawComment *> RawComments = Comments.getComments();
131 // If there are no comments anywhere, we won't find anything.
132 if (RawComments.empty())
135 // Find declaration location.
136 // For Objective-C declarations we generally don't expect to have multiple
137 // declarators, thus use declaration starting location as the "declaration
139 // For all other declarations multiple declarators are used quite frequently,
140 // so we use the location of the identifier as the "declaration location".
141 SourceLocation DeclLoc;
142 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
143 isa<ObjCPropertyDecl>(D) ||
144 isa<RedeclarableTemplateDecl>(D) ||
145 isa<ClassTemplateSpecializationDecl>(D))
146 DeclLoc = D->getLocStart();
148 DeclLoc = D->getLocation();
149 if (DeclLoc.isMacroID()) {
150 if (isa<TypedefDecl>(D)) {
151 // If location of the typedef name is in a macro, it is because being
152 // declared via a macro. Try using declaration's starting location as
153 // the "declaration location".
154 DeclLoc = D->getLocStart();
155 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
156 // If location of the tag decl is inside a macro, but the spelling of
157 // the tag name comes from a macro argument, it looks like a special
158 // macro like NS_ENUM is being used to define the tag decl. In that
159 // case, adjust the source location to the expansion loc so that we can
160 // attach the comment to the tag decl.
161 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
162 TD->isCompleteDefinition())
163 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
168 // If the declaration doesn't map directly to a location in a file, we
169 // can't find the comment.
170 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
173 // Find the comment that occurs just after this declaration.
174 ArrayRef<RawComment *>::iterator Comment;
176 // When searching for comments during parsing, the comment we are looking
177 // for is usually among the last two comments we parsed -- check them
179 RawComment CommentAtDeclLoc(
180 SourceMgr, SourceRange(DeclLoc), false,
181 LangOpts.CommentOpts.ParseAllComments);
182 BeforeThanCompare<RawComment> Compare(SourceMgr);
183 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
184 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
185 if (!Found && RawComments.size() >= 2) {
187 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
191 Comment = MaybeBeforeDecl + 1;
192 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
193 &CommentAtDeclLoc, Compare));
196 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
197 &CommentAtDeclLoc, Compare);
201 // Decompose the location for the declaration and find the beginning of the
203 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
205 // First check whether we have a trailing comment.
206 if (Comment != RawComments.end() &&
207 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
208 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
209 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
210 std::pair<FileID, unsigned> CommentBeginDecomp
211 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
212 // Check that Doxygen trailing comment comes after the declaration, starts
213 // on the same line and in the same file as the declaration.
214 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
215 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
216 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
217 CommentBeginDecomp.second)) {
222 // The comment just after the declaration was not a trailing comment.
223 // Let's look at the previous comment.
224 if (Comment == RawComments.begin())
228 // Check that we actually have a non-member Doxygen comment.
229 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
232 // Decompose the end of the comment.
233 std::pair<FileID, unsigned> CommentEndDecomp
234 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
236 // If the comment and the declaration aren't in the same file, then they
238 if (DeclLocDecomp.first != CommentEndDecomp.first)
241 // Get the corresponding buffer.
242 bool Invalid = false;
243 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
248 // Extract text between the comment and declaration.
249 StringRef Text(Buffer + CommentEndDecomp.second,
250 DeclLocDecomp.second - CommentEndDecomp.second);
252 // There should be no other declarations or preprocessor directives between
253 // comment and declaration.
254 if (Text.find_first_of(";{}#@") != StringRef::npos)
261 /// If we have a 'templated' declaration for a template, adjust 'D' to
262 /// refer to the actual template.
263 /// If we have an implicit instantiation, adjust 'D' to refer to template.
264 const Decl *adjustDeclToTemplate(const Decl *D) {
265 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
266 // Is this function declaration part of a function template?
267 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
270 // Nothing to do if function is not an implicit instantiation.
271 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
274 // Function is an implicit instantiation of a function template?
275 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
278 // Function is instantiated from a member definition of a class template?
279 if (const FunctionDecl *MemberDecl =
280 FD->getInstantiatedFromMemberFunction())
285 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
286 // Static data member is instantiated from a member definition of a class
288 if (VD->isStaticDataMember())
289 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
294 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
295 // Is this class declaration part of a class template?
296 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
299 // Class is an implicit instantiation of a class template or partial
301 if (const ClassTemplateSpecializationDecl *CTSD =
302 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
303 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
305 llvm::PointerUnion<ClassTemplateDecl *,
306 ClassTemplatePartialSpecializationDecl *>
307 PU = CTSD->getSpecializedTemplateOrPartial();
308 return PU.is<ClassTemplateDecl*>() ?
309 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
310 static_cast<const Decl*>(
311 PU.get<ClassTemplatePartialSpecializationDecl *>());
314 // Class is instantiated from a member definition of a class template?
315 if (const MemberSpecializationInfo *Info =
316 CRD->getMemberSpecializationInfo())
317 return Info->getInstantiatedFrom();
321 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
322 // Enum is instantiated from a member definition of a class template?
323 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
328 // FIXME: Adjust alias templates?
331 } // anonymous namespace
333 const RawComment *ASTContext::getRawCommentForAnyRedecl(
335 const Decl **OriginalDecl) const {
336 D = adjustDeclToTemplate(D);
338 // Check whether we have cached a comment for this declaration already.
340 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
341 RedeclComments.find(D);
342 if (Pos != RedeclComments.end()) {
343 const RawCommentAndCacheFlags &Raw = Pos->second;
344 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
346 *OriginalDecl = Raw.getOriginalDecl();
352 // Search for comments attached to declarations in the redeclaration chain.
353 const RawComment *RC = nullptr;
354 const Decl *OriginalDeclForRC = nullptr;
355 for (auto I : D->redecls()) {
356 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
357 RedeclComments.find(I);
358 if (Pos != RedeclComments.end()) {
359 const RawCommentAndCacheFlags &Raw = Pos->second;
360 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
362 OriginalDeclForRC = Raw.getOriginalDecl();
366 RC = getRawCommentForDeclNoCache(I);
367 OriginalDeclForRC = I;
368 RawCommentAndCacheFlags Raw;
370 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
371 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
372 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
375 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
376 Raw.setOriginalDecl(I);
377 RedeclComments[I] = Raw;
383 // If we found a comment, it should be a documentation comment.
384 assert(!RC || RC->isDocumentation());
387 *OriginalDecl = OriginalDeclForRC;
389 // Update cache for every declaration in the redeclaration chain.
390 RawCommentAndCacheFlags Raw;
392 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
393 Raw.setOriginalDecl(OriginalDeclForRC);
395 for (auto I : D->redecls()) {
396 RawCommentAndCacheFlags &R = RedeclComments[I];
397 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
404 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
405 SmallVectorImpl<const NamedDecl *> &Redeclared) {
406 const DeclContext *DC = ObjCMethod->getDeclContext();
407 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
408 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
411 // Add redeclared method here.
412 for (const auto *Ext : ID->known_extensions()) {
413 if (ObjCMethodDecl *RedeclaredMethod =
414 Ext->getMethod(ObjCMethod->getSelector(),
415 ObjCMethod->isInstanceMethod()))
416 Redeclared.push_back(RedeclaredMethod);
421 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
422 const Decl *D) const {
423 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
424 ThisDeclInfo->CommentDecl = D;
425 ThisDeclInfo->IsFilled = false;
426 ThisDeclInfo->fill();
427 ThisDeclInfo->CommentDecl = FC->getDecl();
428 if (!ThisDeclInfo->TemplateParameters)
429 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
430 comments::FullComment *CFC =
431 new (*this) comments::FullComment(FC->getBlocks(),
436 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
437 const RawComment *RC = getRawCommentForDeclNoCache(D);
438 return RC ? RC->parse(*this, nullptr, D) : nullptr;
441 comments::FullComment *ASTContext::getCommentForDecl(
443 const Preprocessor *PP) const {
444 if (D->isInvalidDecl())
446 D = adjustDeclToTemplate(D);
448 const Decl *Canonical = D->getCanonicalDecl();
449 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
450 ParsedComments.find(Canonical);
452 if (Pos != ParsedComments.end()) {
453 if (Canonical != D) {
454 comments::FullComment *FC = Pos->second;
455 comments::FullComment *CFC = cloneFullComment(FC, D);
461 const Decl *OriginalDecl;
463 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
465 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
466 SmallVector<const NamedDecl*, 8> Overridden;
467 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
468 if (OMD && OMD->isPropertyAccessor())
469 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
470 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
471 return cloneFullComment(FC, D);
473 addRedeclaredMethods(OMD, Overridden);
474 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
475 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
476 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
477 return cloneFullComment(FC, D);
479 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
480 // Attach any tag type's documentation to its typedef if latter
481 // does not have one of its own.
482 QualType QT = TD->getUnderlyingType();
483 if (const TagType *TT = QT->getAs<TagType>())
484 if (const Decl *TD = TT->getDecl())
485 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
486 return cloneFullComment(FC, D);
488 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
489 while (IC->getSuperClass()) {
490 IC = IC->getSuperClass();
491 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
492 return cloneFullComment(FC, D);
495 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
496 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
497 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
498 return cloneFullComment(FC, D);
500 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
501 if (!(RD = RD->getDefinition()))
503 // Check non-virtual bases.
504 for (const auto &I : RD->bases()) {
505 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
507 QualType Ty = I.getType();
510 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
511 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
514 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
515 return cloneFullComment(FC, D);
518 // Check virtual bases.
519 for (const auto &I : RD->vbases()) {
520 if (I.getAccessSpecifier() != AS_public)
522 QualType Ty = I.getType();
525 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
526 if (!(VirtualBase= VirtualBase->getDefinition()))
528 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
529 return cloneFullComment(FC, D);
536 // If the RawComment was attached to other redeclaration of this Decl, we
537 // should parse the comment in context of that other Decl. This is important
538 // because comments can contain references to parameter names which can be
539 // different across redeclarations.
540 if (D != OriginalDecl)
541 return getCommentForDecl(OriginalDecl, PP);
543 comments::FullComment *FC = RC->parse(*this, PP, D);
544 ParsedComments[Canonical] = FC;
549 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
550 TemplateTemplateParmDecl *Parm) {
551 ID.AddInteger(Parm->getDepth());
552 ID.AddInteger(Parm->getPosition());
553 ID.AddBoolean(Parm->isParameterPack());
555 TemplateParameterList *Params = Parm->getTemplateParameters();
556 ID.AddInteger(Params->size());
557 for (TemplateParameterList::const_iterator P = Params->begin(),
558 PEnd = Params->end();
560 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
562 ID.AddBoolean(TTP->isParameterPack());
566 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
568 ID.AddBoolean(NTTP->isParameterPack());
569 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
570 if (NTTP->isExpandedParameterPack()) {
572 ID.AddInteger(NTTP->getNumExpansionTypes());
573 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
574 QualType T = NTTP->getExpansionType(I);
575 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
578 ID.AddBoolean(false);
582 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
588 TemplateTemplateParmDecl *
589 ASTContext::getCanonicalTemplateTemplateParmDecl(
590 TemplateTemplateParmDecl *TTP) const {
591 // Check if we already have a canonical template template parameter.
592 llvm::FoldingSetNodeID ID;
593 CanonicalTemplateTemplateParm::Profile(ID, TTP);
594 void *InsertPos = nullptr;
595 CanonicalTemplateTemplateParm *Canonical
596 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
598 return Canonical->getParam();
600 // Build a canonical template parameter list.
601 TemplateParameterList *Params = TTP->getTemplateParameters();
602 SmallVector<NamedDecl *, 4> CanonParams;
603 CanonParams.reserve(Params->size());
604 for (TemplateParameterList::const_iterator P = Params->begin(),
605 PEnd = Params->end();
607 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
608 CanonParams.push_back(
609 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
613 TTP->getIndex(), nullptr, false,
614 TTP->isParameterPack()));
615 else if (NonTypeTemplateParmDecl *NTTP
616 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
617 QualType T = getCanonicalType(NTTP->getType());
618 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
619 NonTypeTemplateParmDecl *Param;
620 if (NTTP->isExpandedParameterPack()) {
621 SmallVector<QualType, 2> ExpandedTypes;
622 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
623 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
624 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
625 ExpandedTInfos.push_back(
626 getTrivialTypeSourceInfo(ExpandedTypes.back()));
629 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
633 NTTP->getPosition(), nullptr,
639 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
643 NTTP->getPosition(), nullptr,
645 NTTP->isParameterPack(),
648 CanonParams.push_back(Param);
651 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
652 cast<TemplateTemplateParmDecl>(*P)));
655 TemplateTemplateParmDecl *CanonTTP
656 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
657 SourceLocation(), TTP->getDepth(),
659 TTP->isParameterPack(),
661 TemplateParameterList::Create(*this, SourceLocation(),
666 // Get the new insert position for the node we care about.
667 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
668 assert(!Canonical && "Shouldn't be in the map!");
671 // Create the canonical template template parameter entry.
672 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
673 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
677 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
678 if (!LangOpts.CPlusPlus) return nullptr;
680 switch (T.getCXXABI().getKind()) {
681 case TargetCXXABI::GenericARM: // Same as Itanium at this level
682 case TargetCXXABI::iOS:
683 case TargetCXXABI::iOS64:
684 case TargetCXXABI::WatchOS:
685 case TargetCXXABI::GenericAArch64:
686 case TargetCXXABI::GenericMIPS:
687 case TargetCXXABI::GenericItanium:
688 case TargetCXXABI::WebAssembly:
689 return CreateItaniumCXXABI(*this);
690 case TargetCXXABI::Microsoft:
691 return CreateMicrosoftCXXABI(*this);
693 llvm_unreachable("Invalid CXXABI type!");
696 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
697 const LangOptions &LOpts) {
698 if (LOpts.FakeAddressSpaceMap) {
699 // The fake address space map must have a distinct entry for each
700 // language-specific address space.
701 static const unsigned FakeAddrSpaceMap[] = {
704 3, // opencl_constant
710 return &FakeAddrSpaceMap;
712 return &T.getAddressSpaceMap();
716 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
717 const LangOptions &LangOpts) {
718 switch (LangOpts.getAddressSpaceMapMangling()) {
719 case LangOptions::ASMM_Target:
720 return TI.useAddressSpaceMapMangling();
721 case LangOptions::ASMM_On:
723 case LangOptions::ASMM_Off:
726 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
729 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
730 IdentifierTable &idents, SelectorTable &sels,
731 Builtin::Context &builtins)
732 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
733 DependentTemplateSpecializationTypes(this_()),
734 SubstTemplateTemplateParmPacks(this_()),
735 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
736 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
737 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
738 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
739 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
740 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
741 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
742 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
743 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
744 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
745 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
746 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
747 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
748 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
749 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
750 Listener(nullptr), Comments(SM), CommentsLoaded(false),
751 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
752 TUDecl = TranslationUnitDecl::Create(*this);
755 ASTContext::~ASTContext() {
756 ReleaseParentMapEntries();
758 // Release the DenseMaps associated with DeclContext objects.
759 // FIXME: Is this the ideal solution?
760 ReleaseDeclContextMaps();
762 // Call all of the deallocation functions on all of their targets.
763 for (auto &Pair : Deallocations)
764 (Pair.first)(Pair.second);
766 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
767 // because they can contain DenseMaps.
768 for (llvm::DenseMap<const ObjCContainerDecl*,
769 const ASTRecordLayout*>::iterator
770 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
771 // Increment in loop to prevent using deallocated memory.
772 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
775 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
776 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
777 // Increment in loop to prevent using deallocated memory.
778 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
782 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
783 AEnd = DeclAttrs.end();
785 A->second->~AttrVec();
787 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
788 MaterializedTemporaryValues)
789 MTVPair.second->~APValue();
791 llvm::DeleteContainerSeconds(MangleNumberingContexts);
794 void ASTContext::ReleaseParentMapEntries() {
795 if (!PointerParents) return;
796 for (const auto &Entry : *PointerParents) {
797 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
798 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
799 } else if (Entry.second.is<ParentVector *>()) {
800 delete Entry.second.get<ParentVector *>();
803 for (const auto &Entry : *OtherParents) {
804 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
805 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
806 } else if (Entry.second.is<ParentVector *>()) {
807 delete Entry.second.get<ParentVector *>();
812 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
813 Deallocations.push_back({Callback, Data});
817 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
818 ExternalSource = std::move(Source);
821 void ASTContext::PrintStats() const {
822 llvm::errs() << "\n*** AST Context Stats:\n";
823 llvm::errs() << " " << Types.size() << " types total.\n";
825 unsigned counts[] = {
826 #define TYPE(Name, Parent) 0,
827 #define ABSTRACT_TYPE(Name, Parent)
828 #include "clang/AST/TypeNodes.def"
832 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
834 counts[(unsigned)T->getTypeClass()]++;
838 unsigned TotalBytes = 0;
839 #define TYPE(Name, Parent) \
841 llvm::errs() << " " << counts[Idx] << " " << #Name \
843 TotalBytes += counts[Idx] * sizeof(Name##Type); \
845 #define ABSTRACT_TYPE(Name, Parent)
846 #include "clang/AST/TypeNodes.def"
848 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
850 // Implicit special member functions.
851 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
852 << NumImplicitDefaultConstructors
853 << " implicit default constructors created\n";
854 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
855 << NumImplicitCopyConstructors
856 << " implicit copy constructors created\n";
857 if (getLangOpts().CPlusPlus)
858 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
859 << NumImplicitMoveConstructors
860 << " implicit move constructors created\n";
861 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
862 << NumImplicitCopyAssignmentOperators
863 << " implicit copy assignment operators created\n";
864 if (getLangOpts().CPlusPlus)
865 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
866 << NumImplicitMoveAssignmentOperators
867 << " implicit move assignment operators created\n";
868 llvm::errs() << NumImplicitDestructorsDeclared << "/"
869 << NumImplicitDestructors
870 << " implicit destructors created\n";
872 if (ExternalSource) {
873 llvm::errs() << "\n";
874 ExternalSource->PrintStats();
877 BumpAlloc.PrintStats();
880 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
881 bool NotifyListeners) {
883 if (auto *Listener = getASTMutationListener())
884 Listener->RedefinedHiddenDefinition(ND, M);
886 if (getLangOpts().ModulesLocalVisibility)
887 MergedDefModules[ND].push_back(M);
889 ND->setHidden(false);
892 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
893 auto It = MergedDefModules.find(ND);
894 if (It == MergedDefModules.end())
897 auto &Merged = It->second;
898 llvm::DenseSet<Module*> Found;
899 for (Module *&M : Merged)
900 if (!Found.insert(M).second)
902 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
905 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
907 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
909 return ExternCContext;
912 BuiltinTemplateDecl *
913 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
914 const IdentifierInfo *II) const {
915 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
916 BuiltinTemplate->setImplicit();
917 TUDecl->addDecl(BuiltinTemplate);
919 return BuiltinTemplate;
922 BuiltinTemplateDecl *
923 ASTContext::getMakeIntegerSeqDecl() const {
924 if (!MakeIntegerSeqDecl)
925 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
926 getMakeIntegerSeqName());
927 return MakeIntegerSeqDecl;
930 BuiltinTemplateDecl *
931 ASTContext::getTypePackElementDecl() const {
932 if (!TypePackElementDecl)
933 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
934 getTypePackElementName());
935 return TypePackElementDecl;
938 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
939 RecordDecl::TagKind TK) const {
942 if (getLangOpts().CPlusPlus)
943 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
944 Loc, &Idents.get(Name));
946 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
948 NewDecl->setImplicit();
949 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
950 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
954 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
955 StringRef Name) const {
956 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
957 TypedefDecl *NewDecl = TypedefDecl::Create(
958 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
959 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
960 NewDecl->setImplicit();
964 TypedefDecl *ASTContext::getInt128Decl() const {
966 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
970 TypedefDecl *ASTContext::getUInt128Decl() const {
972 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
976 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
977 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
978 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
982 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
983 const TargetInfo *AuxTarget) {
984 assert((!this->Target || this->Target == &Target) &&
985 "Incorrect target reinitialization");
986 assert(VoidTy.isNull() && "Context reinitialized?");
988 this->Target = &Target;
989 this->AuxTarget = AuxTarget;
991 ABI.reset(createCXXABI(Target));
992 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
993 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
996 InitBuiltinType(VoidTy, BuiltinType::Void);
999 InitBuiltinType(BoolTy, BuiltinType::Bool);
1001 if (LangOpts.CharIsSigned)
1002 InitBuiltinType(CharTy, BuiltinType::Char_S);
1004 InitBuiltinType(CharTy, BuiltinType::Char_U);
1006 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1007 InitBuiltinType(ShortTy, BuiltinType::Short);
1008 InitBuiltinType(IntTy, BuiltinType::Int);
1009 InitBuiltinType(LongTy, BuiltinType::Long);
1010 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1013 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1014 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1015 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1016 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1017 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1020 InitBuiltinType(FloatTy, BuiltinType::Float);
1021 InitBuiltinType(DoubleTy, BuiltinType::Double);
1022 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1024 // GNU extension, __float128 for IEEE quadruple precision
1025 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1027 // GNU extension, 128-bit integers.
1028 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1029 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1032 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1033 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1034 else // -fshort-wchar makes wchar_t be unsigned.
1035 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1036 if (LangOpts.CPlusPlus && LangOpts.WChar)
1037 WideCharTy = WCharTy;
1039 // C99 (or C++ using -fno-wchar).
1040 WideCharTy = getFromTargetType(Target.getWCharType());
1043 WIntTy = getFromTargetType(Target.getWIntType());
1045 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1046 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1048 Char16Ty = getFromTargetType(Target.getChar16Type());
1050 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1051 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1053 Char32Ty = getFromTargetType(Target.getChar32Type());
1055 // Placeholder type for type-dependent expressions whose type is
1056 // completely unknown. No code should ever check a type against
1057 // DependentTy and users should never see it; however, it is here to
1058 // help diagnose failures to properly check for type-dependent
1060 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1062 // Placeholder type for functions.
1063 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1065 // Placeholder type for bound members.
1066 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1068 // Placeholder type for pseudo-objects.
1069 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1071 // "any" type; useful for debugger-like clients.
1072 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1074 // Placeholder type for unbridged ARC casts.
1075 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1077 // Placeholder type for builtin functions.
1078 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1080 // Placeholder type for OMP array sections.
1081 if (LangOpts.OpenMP)
1082 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1085 FloatComplexTy = getComplexType(FloatTy);
1086 DoubleComplexTy = getComplexType(DoubleTy);
1087 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1088 Float128ComplexTy = getComplexType(Float128Ty);
1090 // Builtin types for 'id', 'Class', and 'SEL'.
1091 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1092 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1093 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1095 if (LangOpts.OpenCL) {
1096 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1097 InitBuiltinType(SingletonId, BuiltinType::Id);
1098 #include "clang/Basic/OpenCLImageTypes.def"
1100 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1101 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1102 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1103 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1104 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1105 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1108 // Builtin type for __objc_yes and __objc_no
1109 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1110 SignedCharTy : BoolTy);
1112 ObjCConstantStringType = QualType();
1114 ObjCSuperType = QualType();
1117 VoidPtrTy = getPointerType(VoidTy);
1119 // nullptr type (C++0x 2.14.7)
1120 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1122 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1123 InitBuiltinType(HalfTy, BuiltinType::Half);
1125 // Builtin type used to help define __builtin_va_list.
1126 VaListTagDecl = nullptr;
1129 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1130 return SourceMgr.getDiagnostics();
1133 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1134 AttrVec *&Result = DeclAttrs[D];
1136 void *Mem = Allocate(sizeof(AttrVec));
1137 Result = new (Mem) AttrVec;
1143 /// \brief Erase the attributes corresponding to the given declaration.
1144 void ASTContext::eraseDeclAttrs(const Decl *D) {
1145 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1146 if (Pos != DeclAttrs.end()) {
1147 Pos->second->~AttrVec();
1148 DeclAttrs.erase(Pos);
1153 MemberSpecializationInfo *
1154 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1155 assert(Var->isStaticDataMember() && "Not a static data member");
1156 return getTemplateOrSpecializationInfo(Var)
1157 .dyn_cast<MemberSpecializationInfo *>();
1160 ASTContext::TemplateOrSpecializationInfo
1161 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1162 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1163 TemplateOrInstantiation.find(Var);
1164 if (Pos == TemplateOrInstantiation.end())
1165 return TemplateOrSpecializationInfo();
1171 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1172 TemplateSpecializationKind TSK,
1173 SourceLocation PointOfInstantiation) {
1174 assert(Inst->isStaticDataMember() && "Not a static data member");
1175 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1176 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1177 Tmpl, TSK, PointOfInstantiation));
1181 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1182 TemplateOrSpecializationInfo TSI) {
1183 assert(!TemplateOrInstantiation[Inst] &&
1184 "Already noted what the variable was instantiated from");
1185 TemplateOrInstantiation[Inst] = TSI;
1188 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1189 const FunctionDecl *FD){
1190 assert(FD && "Specialization is 0");
1191 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1192 = ClassScopeSpecializationPattern.find(FD);
1193 if (Pos == ClassScopeSpecializationPattern.end())
1199 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1200 FunctionDecl *Pattern) {
1201 assert(FD && "Specialization is 0");
1202 assert(Pattern && "Class scope specialization pattern is 0");
1203 ClassScopeSpecializationPattern[FD] = Pattern;
1207 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
1208 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
1209 = InstantiatedFromUsingDecl.find(UUD);
1210 if (Pos == InstantiatedFromUsingDecl.end())
1217 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1218 assert((isa<UsingDecl>(Pattern) ||
1219 isa<UnresolvedUsingValueDecl>(Pattern) ||
1220 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1221 "pattern decl is not a using decl");
1222 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1223 InstantiatedFromUsingDecl[Inst] = Pattern;
1227 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1228 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1229 = InstantiatedFromUsingShadowDecl.find(Inst);
1230 if (Pos == InstantiatedFromUsingShadowDecl.end())
1237 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1238 UsingShadowDecl *Pattern) {
1239 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1240 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1243 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1244 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1245 = InstantiatedFromUnnamedFieldDecl.find(Field);
1246 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1252 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1254 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1255 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1256 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1257 "Already noted what unnamed field was instantiated from");
1259 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1262 ASTContext::overridden_cxx_method_iterator
1263 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1264 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1265 OverriddenMethods.find(Method->getCanonicalDecl());
1266 if (Pos == OverriddenMethods.end())
1268 return Pos->second.begin();
1271 ASTContext::overridden_cxx_method_iterator
1272 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1273 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1274 OverriddenMethods.find(Method->getCanonicalDecl());
1275 if (Pos == OverriddenMethods.end())
1277 return Pos->second.end();
1281 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1282 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1283 OverriddenMethods.find(Method->getCanonicalDecl());
1284 if (Pos == OverriddenMethods.end())
1286 return Pos->second.size();
1289 ASTContext::overridden_method_range
1290 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1291 return overridden_method_range(overridden_methods_begin(Method),
1292 overridden_methods_end(Method));
1295 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1296 const CXXMethodDecl *Overridden) {
1297 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1298 OverriddenMethods[Method].push_back(Overridden);
1301 void ASTContext::getOverriddenMethods(
1303 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1306 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1307 Overridden.append(overridden_methods_begin(CXXMethod),
1308 overridden_methods_end(CXXMethod));
1312 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1316 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1317 Method->getOverriddenMethods(OverDecls);
1318 Overridden.append(OverDecls.begin(), OverDecls.end());
1321 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1322 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1323 assert(!Import->isFromASTFile() && "Non-local import declaration");
1324 if (!FirstLocalImport) {
1325 FirstLocalImport = Import;
1326 LastLocalImport = Import;
1330 LastLocalImport->NextLocalImport = Import;
1331 LastLocalImport = Import;
1334 //===----------------------------------------------------------------------===//
1335 // Type Sizing and Analysis
1336 //===----------------------------------------------------------------------===//
1338 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1339 /// scalar floating point type.
1340 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1341 const BuiltinType *BT = T->getAs<BuiltinType>();
1342 assert(BT && "Not a floating point type!");
1343 switch (BT->getKind()) {
1344 default: llvm_unreachable("Not a floating point type!");
1345 case BuiltinType::Half: return Target->getHalfFormat();
1346 case BuiltinType::Float: return Target->getFloatFormat();
1347 case BuiltinType::Double: return Target->getDoubleFormat();
1348 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1349 case BuiltinType::Float128: return Target->getFloat128Format();
1353 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1354 unsigned Align = Target->getCharWidth();
1356 bool UseAlignAttrOnly = false;
1357 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1358 Align = AlignFromAttr;
1360 // __attribute__((aligned)) can increase or decrease alignment
1361 // *except* on a struct or struct member, where it only increases
1362 // alignment unless 'packed' is also specified.
1364 // It is an error for alignas to decrease alignment, so we can
1365 // ignore that possibility; Sema should diagnose it.
1366 if (isa<FieldDecl>(D)) {
1367 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1368 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1370 UseAlignAttrOnly = true;
1373 else if (isa<FieldDecl>(D))
1375 D->hasAttr<PackedAttr>() ||
1376 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1378 // If we're using the align attribute only, just ignore everything
1379 // else about the declaration and its type.
1380 if (UseAlignAttrOnly) {
1383 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1384 QualType T = VD->getType();
1385 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
1387 T = RT->getPointeeType();
1389 T = getPointerType(RT->getPointeeType());
1391 QualType BaseT = getBaseElementType(T);
1392 if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
1393 // Adjust alignments of declarations with array type by the
1394 // large-array alignment on the target.
1395 if (const ArrayType *arrayType = getAsArrayType(T)) {
1396 unsigned MinWidth = Target->getLargeArrayMinWidth();
1397 if (!ForAlignof && MinWidth) {
1398 if (isa<VariableArrayType>(arrayType))
1399 Align = std::max(Align, Target->getLargeArrayAlign());
1400 else if (isa<ConstantArrayType>(arrayType) &&
1401 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1402 Align = std::max(Align, Target->getLargeArrayAlign());
1405 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1406 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1407 if (VD->hasGlobalStorage() && !ForAlignof)
1408 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1412 // Fields can be subject to extra alignment constraints, like if
1413 // the field is packed, the struct is packed, or the struct has a
1414 // a max-field-alignment constraint (#pragma pack). So calculate
1415 // the actual alignment of the field within the struct, and then
1416 // (as we're expected to) constrain that by the alignment of the type.
1417 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1418 const RecordDecl *Parent = Field->getParent();
1419 // We can only produce a sensible answer if the record is valid.
1420 if (!Parent->isInvalidDecl()) {
1421 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1423 // Start with the record's overall alignment.
1424 unsigned FieldAlign = toBits(Layout.getAlignment());
1426 // Use the GCD of that and the offset within the record.
1427 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1429 // Alignment is always a power of 2, so the GCD will be a power of 2,
1430 // which means we get to do this crazy thing instead of Euclid's.
1431 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1432 if (LowBitOfOffset < FieldAlign)
1433 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1436 Align = std::min(Align, FieldAlign);
1441 return toCharUnitsFromBits(Align);
1444 // getTypeInfoDataSizeInChars - Return the size of a type, in
1445 // chars. If the type is a record, its data size is returned. This is
1446 // the size of the memcpy that's performed when assigning this type
1447 // using a trivial copy/move assignment operator.
1448 std::pair<CharUnits, CharUnits>
1449 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1450 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1452 // In C++, objects can sometimes be allocated into the tail padding
1453 // of a base-class subobject. We decide whether that's possible
1454 // during class layout, so here we can just trust the layout results.
1455 if (getLangOpts().CPlusPlus) {
1456 if (const RecordType *RT = T->getAs<RecordType>()) {
1457 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1458 sizeAndAlign.first = layout.getDataSize();
1462 return sizeAndAlign;
1465 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1466 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1467 std::pair<CharUnits, CharUnits>
1468 static getConstantArrayInfoInChars(const ASTContext &Context,
1469 const ConstantArrayType *CAT) {
1470 std::pair<CharUnits, CharUnits> EltInfo =
1471 Context.getTypeInfoInChars(CAT->getElementType());
1472 uint64_t Size = CAT->getSize().getZExtValue();
1473 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1474 (uint64_t)(-1)/Size) &&
1475 "Overflow in array type char size evaluation");
1476 uint64_t Width = EltInfo.first.getQuantity() * Size;
1477 unsigned Align = EltInfo.second.getQuantity();
1478 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1479 Context.getTargetInfo().getPointerWidth(0) == 64)
1480 Width = llvm::alignTo(Width, Align);
1481 return std::make_pair(CharUnits::fromQuantity(Width),
1482 CharUnits::fromQuantity(Align));
1485 std::pair<CharUnits, CharUnits>
1486 ASTContext::getTypeInfoInChars(const Type *T) const {
1487 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1488 return getConstantArrayInfoInChars(*this, CAT);
1489 TypeInfo Info = getTypeInfo(T);
1490 return std::make_pair(toCharUnitsFromBits(Info.Width),
1491 toCharUnitsFromBits(Info.Align));
1494 std::pair<CharUnits, CharUnits>
1495 ASTContext::getTypeInfoInChars(QualType T) const {
1496 return getTypeInfoInChars(T.getTypePtr());
1499 bool ASTContext::isAlignmentRequired(const Type *T) const {
1500 return getTypeInfo(T).AlignIsRequired;
1503 bool ASTContext::isAlignmentRequired(QualType T) const {
1504 return isAlignmentRequired(T.getTypePtr());
1507 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1508 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1509 if (I != MemoizedTypeInfo.end())
1512 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1513 TypeInfo TI = getTypeInfoImpl(T);
1514 MemoizedTypeInfo[T] = TI;
1518 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1519 /// method does not work on incomplete types.
1521 /// FIXME: Pointers into different addr spaces could have different sizes and
1522 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1523 /// should take a QualType, &c.
1524 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1527 bool AlignIsRequired = false;
1528 switch (T->getTypeClass()) {
1529 #define TYPE(Class, Base)
1530 #define ABSTRACT_TYPE(Class, Base)
1531 #define NON_CANONICAL_TYPE(Class, Base)
1532 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1533 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1535 assert(!T->isDependentType() && "should not see dependent types here"); \
1536 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1537 #include "clang/AST/TypeNodes.def"
1538 llvm_unreachable("Should not see dependent types");
1540 case Type::FunctionNoProto:
1541 case Type::FunctionProto:
1542 // GCC extension: alignof(function) = 32 bits
1547 case Type::IncompleteArray:
1548 case Type::VariableArray:
1550 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1553 case Type::ConstantArray: {
1554 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1556 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1557 uint64_t Size = CAT->getSize().getZExtValue();
1558 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1559 "Overflow in array type bit size evaluation");
1560 Width = EltInfo.Width * Size;
1561 Align = EltInfo.Align;
1562 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1563 getTargetInfo().getPointerWidth(0) == 64)
1564 Width = llvm::alignTo(Width, Align);
1567 case Type::ExtVector:
1568 case Type::Vector: {
1569 const VectorType *VT = cast<VectorType>(T);
1570 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1571 Width = EltInfo.Width * VT->getNumElements();
1573 // If the alignment is not a power of 2, round up to the next power of 2.
1574 // This happens for non-power-of-2 length vectors.
1575 if (Align & (Align-1)) {
1576 Align = llvm::NextPowerOf2(Align);
1577 Width = llvm::alignTo(Width, Align);
1579 // Adjust the alignment based on the target max.
1580 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1581 if (TargetVectorAlign && TargetVectorAlign < Align)
1582 Align = TargetVectorAlign;
1587 switch (cast<BuiltinType>(T)->getKind()) {
1588 default: llvm_unreachable("Unknown builtin type!");
1589 case BuiltinType::Void:
1590 // GCC extension: alignof(void) = 8 bits.
1595 case BuiltinType::Bool:
1596 Width = Target->getBoolWidth();
1597 Align = Target->getBoolAlign();
1599 case BuiltinType::Char_S:
1600 case BuiltinType::Char_U:
1601 case BuiltinType::UChar:
1602 case BuiltinType::SChar:
1603 Width = Target->getCharWidth();
1604 Align = Target->getCharAlign();
1606 case BuiltinType::WChar_S:
1607 case BuiltinType::WChar_U:
1608 Width = Target->getWCharWidth();
1609 Align = Target->getWCharAlign();
1611 case BuiltinType::Char16:
1612 Width = Target->getChar16Width();
1613 Align = Target->getChar16Align();
1615 case BuiltinType::Char32:
1616 Width = Target->getChar32Width();
1617 Align = Target->getChar32Align();
1619 case BuiltinType::UShort:
1620 case BuiltinType::Short:
1621 Width = Target->getShortWidth();
1622 Align = Target->getShortAlign();
1624 case BuiltinType::UInt:
1625 case BuiltinType::Int:
1626 Width = Target->getIntWidth();
1627 Align = Target->getIntAlign();
1629 case BuiltinType::ULong:
1630 case BuiltinType::Long:
1631 Width = Target->getLongWidth();
1632 Align = Target->getLongAlign();
1634 case BuiltinType::ULongLong:
1635 case BuiltinType::LongLong:
1636 Width = Target->getLongLongWidth();
1637 Align = Target->getLongLongAlign();
1639 case BuiltinType::Int128:
1640 case BuiltinType::UInt128:
1642 Align = 128; // int128_t is 128-bit aligned on all targets.
1644 case BuiltinType::Half:
1645 Width = Target->getHalfWidth();
1646 Align = Target->getHalfAlign();
1648 case BuiltinType::Float:
1649 Width = Target->getFloatWidth();
1650 Align = Target->getFloatAlign();
1652 case BuiltinType::Double:
1653 Width = Target->getDoubleWidth();
1654 Align = Target->getDoubleAlign();
1656 case BuiltinType::LongDouble:
1657 Width = Target->getLongDoubleWidth();
1658 Align = Target->getLongDoubleAlign();
1660 case BuiltinType::Float128:
1661 Width = Target->getFloat128Width();
1662 Align = Target->getFloat128Align();
1664 case BuiltinType::NullPtr:
1665 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1666 Align = Target->getPointerAlign(0); // == sizeof(void*)
1668 case BuiltinType::ObjCId:
1669 case BuiltinType::ObjCClass:
1670 case BuiltinType::ObjCSel:
1671 Width = Target->getPointerWidth(0);
1672 Align = Target->getPointerAlign(0);
1674 case BuiltinType::OCLSampler:
1675 // Samplers are modeled as integers.
1676 Width = Target->getIntWidth();
1677 Align = Target->getIntAlign();
1679 case BuiltinType::OCLEvent:
1680 case BuiltinType::OCLClkEvent:
1681 case BuiltinType::OCLQueue:
1682 case BuiltinType::OCLNDRange:
1683 case BuiltinType::OCLReserveID:
1684 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1685 case BuiltinType::Id:
1686 #include "clang/Basic/OpenCLImageTypes.def"
1688 // Currently these types are pointers to opaque types.
1689 Width = Target->getPointerWidth(0);
1690 Align = Target->getPointerAlign(0);
1694 case Type::ObjCObjectPointer:
1695 Width = Target->getPointerWidth(0);
1696 Align = Target->getPointerAlign(0);
1698 case Type::BlockPointer: {
1699 unsigned AS = getTargetAddressSpace(
1700 cast<BlockPointerType>(T)->getPointeeType());
1701 Width = Target->getPointerWidth(AS);
1702 Align = Target->getPointerAlign(AS);
1705 case Type::LValueReference:
1706 case Type::RValueReference: {
1707 // alignof and sizeof should never enter this code path here, so we go
1708 // the pointer route.
1709 unsigned AS = getTargetAddressSpace(
1710 cast<ReferenceType>(T)->getPointeeType());
1711 Width = Target->getPointerWidth(AS);
1712 Align = Target->getPointerAlign(AS);
1715 case Type::Pointer: {
1716 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1717 Width = Target->getPointerWidth(AS);
1718 Align = Target->getPointerAlign(AS);
1721 case Type::MemberPointer: {
1722 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1723 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1726 case Type::Complex: {
1727 // Complex types have the same alignment as their elements, but twice the
1729 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1730 Width = EltInfo.Width * 2;
1731 Align = EltInfo.Align;
1734 case Type::ObjCObject:
1735 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1736 case Type::Adjusted:
1738 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1739 case Type::ObjCInterface: {
1740 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1741 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1742 Width = toBits(Layout.getSize());
1743 Align = toBits(Layout.getAlignment());
1748 const TagType *TT = cast<TagType>(T);
1750 if (TT->getDecl()->isInvalidDecl()) {
1756 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1757 const EnumDecl *ED = ET->getDecl();
1759 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1760 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1761 Info.Align = AttrAlign;
1762 Info.AlignIsRequired = true;
1767 const RecordType *RT = cast<RecordType>(TT);
1768 const RecordDecl *RD = RT->getDecl();
1769 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
1770 Width = toBits(Layout.getSize());
1771 Align = toBits(Layout.getAlignment());
1772 AlignIsRequired = RD->hasAttr<AlignedAttr>();
1776 case Type::SubstTemplateTypeParm:
1777 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1778 getReplacementType().getTypePtr());
1781 const AutoType *A = cast<AutoType>(T);
1782 assert(!A->getDeducedType().isNull() &&
1783 "cannot request the size of an undeduced or dependent auto type");
1784 return getTypeInfo(A->getDeducedType().getTypePtr());
1788 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1790 case Type::Typedef: {
1791 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1792 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1793 // If the typedef has an aligned attribute on it, it overrides any computed
1794 // alignment we have. This violates the GCC documentation (which says that
1795 // attribute(aligned) can only round up) but matches its implementation.
1796 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
1798 AlignIsRequired = true;
1801 AlignIsRequired = Info.AlignIsRequired;
1807 case Type::Elaborated:
1808 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1810 case Type::Attributed:
1812 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1814 case Type::Atomic: {
1815 // Start with the base type information.
1816 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1820 // If the size of the type doesn't exceed the platform's max
1821 // atomic promotion width, make the size and alignment more
1822 // favorable to atomic operations:
1823 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1824 // Round the size up to a power of 2.
1825 if (!llvm::isPowerOf2_64(Width))
1826 Width = llvm::NextPowerOf2(Width);
1828 // Set the alignment equal to the size.
1829 Align = static_cast<unsigned>(Width);
1835 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1842 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1843 return TypeInfo(Width, Align, AlignIsRequired);
1846 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1847 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1848 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1849 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1850 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1851 getTargetInfo().getABI() == "elfv1-qpx" &&
1852 T->isSpecificBuiltinType(BuiltinType::Double))
1857 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1858 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1859 return CharUnits::fromQuantity(BitSize / getCharWidth());
1862 /// toBits - Convert a size in characters to a size in characters.
1863 int64_t ASTContext::toBits(CharUnits CharSize) const {
1864 return CharSize.getQuantity() * getCharWidth();
1867 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1868 /// This method does not work on incomplete types.
1869 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1870 return getTypeInfoInChars(T).first;
1872 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1873 return getTypeInfoInChars(T).first;
1876 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1877 /// characters. This method does not work on incomplete types.
1878 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1879 return toCharUnitsFromBits(getTypeAlign(T));
1881 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1882 return toCharUnitsFromBits(getTypeAlign(T));
1885 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1886 /// type for the current target in bits. This can be different than the ABI
1887 /// alignment in cases where it is beneficial for performance to overalign
1889 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1890 TypeInfo TI = getTypeInfo(T);
1891 unsigned ABIAlign = TI.Align;
1893 T = T->getBaseElementTypeUnsafe();
1895 // The preferred alignment of member pointers is that of a pointer.
1896 if (T->isMemberPointerType())
1897 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1899 if (!Target->allowsLargerPreferedTypeAlignment())
1902 // Double and long long should be naturally aligned if possible.
1903 if (const ComplexType *CT = T->getAs<ComplexType>())
1904 T = CT->getElementType().getTypePtr();
1905 if (const EnumType *ET = T->getAs<EnumType>())
1906 T = ET->getDecl()->getIntegerType().getTypePtr();
1907 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1908 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1909 T->isSpecificBuiltinType(BuiltinType::ULongLong))
1910 // Don't increase the alignment if an alignment attribute was specified on a
1911 // typedef declaration.
1912 if (!TI.AlignIsRequired)
1913 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1918 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1919 /// for __attribute__((aligned)) on this target, to be used if no alignment
1920 /// value is specified.
1921 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
1922 return getTargetInfo().getDefaultAlignForAttributeAligned();
1925 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
1926 /// to a global variable of the specified type.
1927 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1928 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1931 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
1932 /// should be given to a global variable of the specified type.
1933 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1934 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1937 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1938 CharUnits Offset = CharUnits::Zero();
1939 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1940 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1941 Offset += Layout->getBaseClassOffset(Base);
1942 Layout = &getASTRecordLayout(Base);
1947 /// DeepCollectObjCIvars -
1948 /// This routine first collects all declared, but not synthesized, ivars in
1949 /// super class and then collects all ivars, including those synthesized for
1950 /// current class. This routine is used for implementation of current class
1951 /// when all ivars, declared and synthesized are known.
1953 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1955 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1956 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1957 DeepCollectObjCIvars(SuperClass, false, Ivars);
1959 for (const auto *I : OI->ivars())
1962 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1963 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1964 Iv= Iv->getNextIvar())
1965 Ivars.push_back(Iv);
1969 /// CollectInheritedProtocols - Collect all protocols in current class and
1970 /// those inherited by it.
1971 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1972 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1973 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1974 // We can use protocol_iterator here instead of
1975 // all_referenced_protocol_iterator since we are walking all categories.
1976 for (auto *Proto : OI->all_referenced_protocols()) {
1977 CollectInheritedProtocols(Proto, Protocols);
1980 // Categories of this Interface.
1981 for (const auto *Cat : OI->visible_categories())
1982 CollectInheritedProtocols(Cat, Protocols);
1984 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1986 CollectInheritedProtocols(SD, Protocols);
1987 SD = SD->getSuperClass();
1989 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1990 for (auto *Proto : OC->protocols()) {
1991 CollectInheritedProtocols(Proto, Protocols);
1993 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1994 // Insert the protocol.
1995 if (!Protocols.insert(
1996 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1999 for (auto *Proto : OP->protocols())
2000 CollectInheritedProtocols(Proto, Protocols);
2004 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2006 // Count ivars declared in class extension.
2007 for (const auto *Ext : OI->known_extensions())
2008 count += Ext->ivar_size();
2010 // Count ivar defined in this class's implementation. This
2011 // includes synthesized ivars.
2012 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2013 count += ImplDecl->ivar_size();
2018 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2022 // nullptr_t is always treated as null.
2023 if (E->getType()->isNullPtrType()) return true;
2025 if (E->getType()->isAnyPointerType() &&
2026 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2027 Expr::NPC_ValueDependentIsNull))
2030 // Unfortunately, __null has type 'int'.
2031 if (isa<GNUNullExpr>(E)) return true;
2036 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2037 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2038 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2039 I = ObjCImpls.find(D);
2040 if (I != ObjCImpls.end())
2041 return cast<ObjCImplementationDecl>(I->second);
2044 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2045 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2046 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2047 I = ObjCImpls.find(D);
2048 if (I != ObjCImpls.end())
2049 return cast<ObjCCategoryImplDecl>(I->second);
2053 /// \brief Set the implementation of ObjCInterfaceDecl.
2054 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2055 ObjCImplementationDecl *ImplD) {
2056 assert(IFaceD && ImplD && "Passed null params");
2057 ObjCImpls[IFaceD] = ImplD;
2059 /// \brief Set the implementation of ObjCCategoryDecl.
2060 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2061 ObjCCategoryImplDecl *ImplD) {
2062 assert(CatD && ImplD && "Passed null params");
2063 ObjCImpls[CatD] = ImplD;
2066 const ObjCMethodDecl *
2067 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2068 return ObjCMethodRedecls.lookup(MD);
2071 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2072 const ObjCMethodDecl *Redecl) {
2073 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2074 ObjCMethodRedecls[MD] = Redecl;
2077 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2078 const NamedDecl *ND) const {
2079 if (const ObjCInterfaceDecl *ID =
2080 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2082 if (const ObjCCategoryDecl *CD =
2083 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2084 return CD->getClassInterface();
2085 if (const ObjCImplDecl *IMD =
2086 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2087 return IMD->getClassInterface();
2092 /// \brief Get the copy initialization expression of VarDecl,or NULL if
2094 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
2095 assert(VD && "Passed null params");
2096 assert(VD->hasAttr<BlocksAttr>() &&
2097 "getBlockVarCopyInits - not __block var");
2098 llvm::DenseMap<const VarDecl*, Expr*>::iterator
2099 I = BlockVarCopyInits.find(VD);
2100 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
2103 /// \brief Set the copy inialization expression of a block var decl.
2104 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2105 assert(VD && Init && "Passed null params");
2106 assert(VD->hasAttr<BlocksAttr>() &&
2107 "setBlockVarCopyInits - not __block var");
2108 BlockVarCopyInits[VD] = Init;
2111 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2112 unsigned DataSize) const {
2114 DataSize = TypeLoc::getFullDataSizeForType(T);
2116 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2117 "incorrect data size provided to CreateTypeSourceInfo!");
2119 TypeSourceInfo *TInfo =
2120 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2121 new (TInfo) TypeSourceInfo(T);
2125 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2126 SourceLocation L) const {
2127 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2128 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2132 const ASTRecordLayout &
2133 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2134 return getObjCLayout(D, nullptr);
2137 const ASTRecordLayout &
2138 ASTContext::getASTObjCImplementationLayout(
2139 const ObjCImplementationDecl *D) const {
2140 return getObjCLayout(D->getClassInterface(), D);
2143 //===----------------------------------------------------------------------===//
2144 // Type creation/memoization methods
2145 //===----------------------------------------------------------------------===//
2148 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2149 unsigned fastQuals = quals.getFastQualifiers();
2150 quals.removeFastQualifiers();
2152 // Check if we've already instantiated this type.
2153 llvm::FoldingSetNodeID ID;
2154 ExtQuals::Profile(ID, baseType, quals);
2155 void *insertPos = nullptr;
2156 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2157 assert(eq->getQualifiers() == quals);
2158 return QualType(eq, fastQuals);
2161 // If the base type is not canonical, make the appropriate canonical type.
2163 if (!baseType->isCanonicalUnqualified()) {
2164 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2165 canonSplit.Quals.addConsistentQualifiers(quals);
2166 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2168 // Re-find the insert position.
2169 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2172 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2173 ExtQualNodes.InsertNode(eq, insertPos);
2174 return QualType(eq, fastQuals);
2178 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2179 QualType CanT = getCanonicalType(T);
2180 if (CanT.getAddressSpace() == AddressSpace)
2183 // If we are composing extended qualifiers together, merge together
2184 // into one ExtQuals node.
2185 QualifierCollector Quals;
2186 const Type *TypeNode = Quals.strip(T);
2188 // If this type already has an address space specified, it cannot get
2190 assert(!Quals.hasAddressSpace() &&
2191 "Type cannot be in multiple addr spaces!");
2192 Quals.addAddressSpace(AddressSpace);
2194 return getExtQualType(TypeNode, Quals);
2197 QualType ASTContext::getObjCGCQualType(QualType T,
2198 Qualifiers::GC GCAttr) const {
2199 QualType CanT = getCanonicalType(T);
2200 if (CanT.getObjCGCAttr() == GCAttr)
2203 if (const PointerType *ptr = T->getAs<PointerType>()) {
2204 QualType Pointee = ptr->getPointeeType();
2205 if (Pointee->isAnyPointerType()) {
2206 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2207 return getPointerType(ResultType);
2211 // If we are composing extended qualifiers together, merge together
2212 // into one ExtQuals node.
2213 QualifierCollector Quals;
2214 const Type *TypeNode = Quals.strip(T);
2216 // If this type already has an ObjCGC specified, it cannot get
2218 assert(!Quals.hasObjCGCAttr() &&
2219 "Type cannot have multiple ObjCGCs!");
2220 Quals.addObjCGCAttr(GCAttr);
2222 return getExtQualType(TypeNode, Quals);
2225 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2226 FunctionType::ExtInfo Info) {
2227 if (T->getExtInfo() == Info)
2231 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2232 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2234 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2235 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2237 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2240 return cast<FunctionType>(Result.getTypePtr());
2243 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2244 QualType ResultType) {
2245 FD = FD->getMostRecentDecl();
2247 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2248 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2249 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2250 if (FunctionDecl *Next = FD->getPreviousDecl())
2255 if (ASTMutationListener *L = getASTMutationListener())
2256 L->DeducedReturnType(FD, ResultType);
2259 /// Get a function type and produce the equivalent function type with the
2260 /// specified exception specification. Type sugar that can be present on a
2261 /// declaration of a function with an exception specification is permitted
2262 /// and preserved. Other type sugar (for instance, typedefs) is not.
2263 static QualType getFunctionTypeWithExceptionSpec(
2264 ASTContext &Context, QualType Orig,
2265 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2266 // Might have some parens.
2267 if (auto *PT = dyn_cast<ParenType>(Orig))
2268 return Context.getParenType(
2269 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2271 // Might have a calling-convention attribute.
2272 if (auto *AT = dyn_cast<AttributedType>(Orig))
2273 return Context.getAttributedType(
2275 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2276 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2279 // Anything else must be a function type. Rebuild it with the new exception
2281 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2282 return Context.getFunctionType(
2283 Proto->getReturnType(), Proto->getParamTypes(),
2284 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2287 void ASTContext::adjustExceptionSpec(
2288 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2292 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2293 FD->setType(Updated);
2298 // Update the type in the type source information too.
2299 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2300 // If the type and the type-as-written differ, we may need to update
2301 // the type-as-written too.
2302 if (TSInfo->getType() != FD->getType())
2303 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2305 // FIXME: When we get proper type location information for exceptions,
2306 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2307 // up the TypeSourceInfo;
2308 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2309 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2310 "TypeLoc size mismatch from updating exception specification");
2311 TSInfo->overrideType(Updated);
2315 /// getComplexType - Return the uniqued reference to the type for a complex
2316 /// number with the specified element type.
2317 QualType ASTContext::getComplexType(QualType T) const {
2318 // Unique pointers, to guarantee there is only one pointer of a particular
2320 llvm::FoldingSetNodeID ID;
2321 ComplexType::Profile(ID, T);
2323 void *InsertPos = nullptr;
2324 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2325 return QualType(CT, 0);
2327 // If the pointee type isn't canonical, this won't be a canonical type either,
2328 // so fill in the canonical type field.
2330 if (!T.isCanonical()) {
2331 Canonical = getComplexType(getCanonicalType(T));
2333 // Get the new insert position for the node we care about.
2334 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2335 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2337 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2338 Types.push_back(New);
2339 ComplexTypes.InsertNode(New, InsertPos);
2340 return QualType(New, 0);
2343 /// getPointerType - Return the uniqued reference to the type for a pointer to
2344 /// the specified type.
2345 QualType ASTContext::getPointerType(QualType T) const {
2346 // Unique pointers, to guarantee there is only one pointer of a particular
2348 llvm::FoldingSetNodeID ID;
2349 PointerType::Profile(ID, T);
2351 void *InsertPos = nullptr;
2352 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2353 return QualType(PT, 0);
2355 // If the pointee type isn't canonical, this won't be a canonical type either,
2356 // so fill in the canonical type field.
2358 if (!T.isCanonical()) {
2359 Canonical = getPointerType(getCanonicalType(T));
2361 // Get the new insert position for the node we care about.
2362 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2363 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2365 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2366 Types.push_back(New);
2367 PointerTypes.InsertNode(New, InsertPos);
2368 return QualType(New, 0);
2371 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2372 llvm::FoldingSetNodeID ID;
2373 AdjustedType::Profile(ID, Orig, New);
2374 void *InsertPos = nullptr;
2375 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2377 return QualType(AT, 0);
2379 QualType Canonical = getCanonicalType(New);
2381 // Get the new insert position for the node we care about.
2382 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2383 assert(!AT && "Shouldn't be in the map!");
2385 AT = new (*this, TypeAlignment)
2386 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2387 Types.push_back(AT);
2388 AdjustedTypes.InsertNode(AT, InsertPos);
2389 return QualType(AT, 0);
2392 QualType ASTContext::getDecayedType(QualType T) const {
2393 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2398 // A declaration of a parameter as "array of type" shall be
2399 // adjusted to "qualified pointer to type", where the type
2400 // qualifiers (if any) are those specified within the [ and ] of
2401 // the array type derivation.
2402 if (T->isArrayType())
2403 Decayed = getArrayDecayedType(T);
2406 // A declaration of a parameter as "function returning type"
2407 // shall be adjusted to "pointer to function returning type", as
2409 if (T->isFunctionType())
2410 Decayed = getPointerType(T);
2412 llvm::FoldingSetNodeID ID;
2413 AdjustedType::Profile(ID, T, Decayed);
2414 void *InsertPos = nullptr;
2415 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2417 return QualType(AT, 0);
2419 QualType Canonical = getCanonicalType(Decayed);
2421 // Get the new insert position for the node we care about.
2422 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2423 assert(!AT && "Shouldn't be in the map!");
2425 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2426 Types.push_back(AT);
2427 AdjustedTypes.InsertNode(AT, InsertPos);
2428 return QualType(AT, 0);
2431 /// getBlockPointerType - Return the uniqued reference to the type for
2432 /// a pointer to the specified block.
2433 QualType ASTContext::getBlockPointerType(QualType T) const {
2434 assert(T->isFunctionType() && "block of function types only");
2435 // Unique pointers, to guarantee there is only one block of a particular
2437 llvm::FoldingSetNodeID ID;
2438 BlockPointerType::Profile(ID, T);
2440 void *InsertPos = nullptr;
2441 if (BlockPointerType *PT =
2442 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2443 return QualType(PT, 0);
2445 // If the block pointee type isn't canonical, this won't be a canonical
2446 // type either so fill in the canonical type field.
2448 if (!T.isCanonical()) {
2449 Canonical = getBlockPointerType(getCanonicalType(T));
2451 // Get the new insert position for the node we care about.
2452 BlockPointerType *NewIP =
2453 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2454 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2456 BlockPointerType *New
2457 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2458 Types.push_back(New);
2459 BlockPointerTypes.InsertNode(New, InsertPos);
2460 return QualType(New, 0);
2463 /// getLValueReferenceType - Return the uniqued reference to the type for an
2464 /// lvalue reference to the specified type.
2466 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2467 assert(getCanonicalType(T) != OverloadTy &&
2468 "Unresolved overloaded function type");
2470 // Unique pointers, to guarantee there is only one pointer of a particular
2472 llvm::FoldingSetNodeID ID;
2473 ReferenceType::Profile(ID, T, SpelledAsLValue);
2475 void *InsertPos = nullptr;
2476 if (LValueReferenceType *RT =
2477 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2478 return QualType(RT, 0);
2480 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2482 // If the referencee type isn't canonical, this won't be a canonical type
2483 // either, so fill in the canonical type field.
2485 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2486 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2487 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2489 // Get the new insert position for the node we care about.
2490 LValueReferenceType *NewIP =
2491 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2492 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2495 LValueReferenceType *New
2496 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2498 Types.push_back(New);
2499 LValueReferenceTypes.InsertNode(New, InsertPos);
2501 return QualType(New, 0);
2504 /// getRValueReferenceType - Return the uniqued reference to the type for an
2505 /// rvalue reference to the specified type.
2506 QualType ASTContext::getRValueReferenceType(QualType T) const {
2507 // Unique pointers, to guarantee there is only one pointer of a particular
2509 llvm::FoldingSetNodeID ID;
2510 ReferenceType::Profile(ID, T, false);
2512 void *InsertPos = nullptr;
2513 if (RValueReferenceType *RT =
2514 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2515 return QualType(RT, 0);
2517 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2519 // If the referencee type isn't canonical, this won't be a canonical type
2520 // either, so fill in the canonical type field.
2522 if (InnerRef || !T.isCanonical()) {
2523 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2524 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2526 // Get the new insert position for the node we care about.
2527 RValueReferenceType *NewIP =
2528 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2529 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2532 RValueReferenceType *New
2533 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2534 Types.push_back(New);
2535 RValueReferenceTypes.InsertNode(New, InsertPos);
2536 return QualType(New, 0);
2539 /// getMemberPointerType - Return the uniqued reference to the type for a
2540 /// member pointer to the specified type, in the specified class.
2541 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2542 // Unique pointers, to guarantee there is only one pointer of a particular
2544 llvm::FoldingSetNodeID ID;
2545 MemberPointerType::Profile(ID, T, Cls);
2547 void *InsertPos = nullptr;
2548 if (MemberPointerType *PT =
2549 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2550 return QualType(PT, 0);
2552 // If the pointee or class type isn't canonical, this won't be a canonical
2553 // type either, so fill in the canonical type field.
2555 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2556 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2558 // Get the new insert position for the node we care about.
2559 MemberPointerType *NewIP =
2560 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2561 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2563 MemberPointerType *New
2564 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2565 Types.push_back(New);
2566 MemberPointerTypes.InsertNode(New, InsertPos);
2567 return QualType(New, 0);
2570 /// getConstantArrayType - Return the unique reference to the type for an
2571 /// array of the specified element type.
2572 QualType ASTContext::getConstantArrayType(QualType EltTy,
2573 const llvm::APInt &ArySizeIn,
2574 ArrayType::ArraySizeModifier ASM,
2575 unsigned IndexTypeQuals) const {
2576 assert((EltTy->isDependentType() ||
2577 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2578 "Constant array of VLAs is illegal!");
2580 // Convert the array size into a canonical width matching the pointer size for
2582 llvm::APInt ArySize(ArySizeIn);
2584 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2586 llvm::FoldingSetNodeID ID;
2587 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2589 void *InsertPos = nullptr;
2590 if (ConstantArrayType *ATP =
2591 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2592 return QualType(ATP, 0);
2594 // If the element type isn't canonical or has qualifiers, this won't
2595 // be a canonical type either, so fill in the canonical type field.
2597 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2598 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2599 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2600 ASM, IndexTypeQuals);
2601 Canon = getQualifiedType(Canon, canonSplit.Quals);
2603 // Get the new insert position for the node we care about.
2604 ConstantArrayType *NewIP =
2605 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2606 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2609 ConstantArrayType *New = new(*this,TypeAlignment)
2610 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2611 ConstantArrayTypes.InsertNode(New, InsertPos);
2612 Types.push_back(New);
2613 return QualType(New, 0);
2616 /// getVariableArrayDecayedType - Turns the given type, which may be
2617 /// variably-modified, into the corresponding type with all the known
2618 /// sizes replaced with [*].
2619 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2620 // Vastly most common case.
2621 if (!type->isVariablyModifiedType()) return type;
2625 SplitQualType split = type.getSplitDesugaredType();
2626 const Type *ty = split.Ty;
2627 switch (ty->getTypeClass()) {
2628 #define TYPE(Class, Base)
2629 #define ABSTRACT_TYPE(Class, Base)
2630 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2631 #include "clang/AST/TypeNodes.def"
2632 llvm_unreachable("didn't desugar past all non-canonical types?");
2634 // These types should never be variably-modified.
2638 case Type::ExtVector:
2639 case Type::DependentSizedExtVector:
2640 case Type::ObjCObject:
2641 case Type::ObjCInterface:
2642 case Type::ObjCObjectPointer:
2645 case Type::UnresolvedUsing:
2646 case Type::TypeOfExpr:
2648 case Type::Decltype:
2649 case Type::UnaryTransform:
2650 case Type::DependentName:
2651 case Type::InjectedClassName:
2652 case Type::TemplateSpecialization:
2653 case Type::DependentTemplateSpecialization:
2654 case Type::TemplateTypeParm:
2655 case Type::SubstTemplateTypeParmPack:
2657 case Type::PackExpansion:
2658 llvm_unreachable("type should never be variably-modified");
2660 // These types can be variably-modified but should never need to
2662 case Type::FunctionNoProto:
2663 case Type::FunctionProto:
2664 case Type::BlockPointer:
2665 case Type::MemberPointer:
2669 // These types can be variably-modified. All these modifications
2670 // preserve structure except as noted by comments.
2671 // TODO: if we ever care about optimizing VLAs, there are no-op
2672 // optimizations available here.
2674 result = getPointerType(getVariableArrayDecayedType(
2675 cast<PointerType>(ty)->getPointeeType()));
2678 case Type::LValueReference: {
2679 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2680 result = getLValueReferenceType(
2681 getVariableArrayDecayedType(lv->getPointeeType()),
2682 lv->isSpelledAsLValue());
2686 case Type::RValueReference: {
2687 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2688 result = getRValueReferenceType(
2689 getVariableArrayDecayedType(lv->getPointeeType()));
2693 case Type::Atomic: {
2694 const AtomicType *at = cast<AtomicType>(ty);
2695 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2699 case Type::ConstantArray: {
2700 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2701 result = getConstantArrayType(
2702 getVariableArrayDecayedType(cat->getElementType()),
2704 cat->getSizeModifier(),
2705 cat->getIndexTypeCVRQualifiers());
2709 case Type::DependentSizedArray: {
2710 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2711 result = getDependentSizedArrayType(
2712 getVariableArrayDecayedType(dat->getElementType()),
2714 dat->getSizeModifier(),
2715 dat->getIndexTypeCVRQualifiers(),
2716 dat->getBracketsRange());
2720 // Turn incomplete types into [*] types.
2721 case Type::IncompleteArray: {
2722 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2723 result = getVariableArrayType(
2724 getVariableArrayDecayedType(iat->getElementType()),
2727 iat->getIndexTypeCVRQualifiers(),
2732 // Turn VLA types into [*] types.
2733 case Type::VariableArray: {
2734 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2735 result = getVariableArrayType(
2736 getVariableArrayDecayedType(vat->getElementType()),
2739 vat->getIndexTypeCVRQualifiers(),
2740 vat->getBracketsRange());
2745 // Apply the top-level qualifiers from the original.
2746 return getQualifiedType(result, split.Quals);
2749 /// getVariableArrayType - Returns a non-unique reference to the type for a
2750 /// variable array of the specified element type.
2751 QualType ASTContext::getVariableArrayType(QualType EltTy,
2753 ArrayType::ArraySizeModifier ASM,
2754 unsigned IndexTypeQuals,
2755 SourceRange Brackets) const {
2756 // Since we don't unique expressions, it isn't possible to unique VLA's
2757 // that have an expression provided for their size.
2760 // Be sure to pull qualifiers off the element type.
2761 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2762 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2763 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2764 IndexTypeQuals, Brackets);
2765 Canon = getQualifiedType(Canon, canonSplit.Quals);
2768 VariableArrayType *New = new(*this, TypeAlignment)
2769 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2771 VariableArrayTypes.push_back(New);
2772 Types.push_back(New);
2773 return QualType(New, 0);
2776 /// getDependentSizedArrayType - Returns a non-unique reference to
2777 /// the type for a dependently-sized array of the specified element
2779 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2781 ArrayType::ArraySizeModifier ASM,
2782 unsigned elementTypeQuals,
2783 SourceRange brackets) const {
2784 assert((!numElements || numElements->isTypeDependent() ||
2785 numElements->isValueDependent()) &&
2786 "Size must be type- or value-dependent!");
2788 // Dependently-sized array types that do not have a specified number
2789 // of elements will have their sizes deduced from a dependent
2790 // initializer. We do no canonicalization here at all, which is okay
2791 // because they can't be used in most locations.
2793 DependentSizedArrayType *newType
2794 = new (*this, TypeAlignment)
2795 DependentSizedArrayType(*this, elementType, QualType(),
2796 numElements, ASM, elementTypeQuals,
2798 Types.push_back(newType);
2799 return QualType(newType, 0);
2802 // Otherwise, we actually build a new type every time, but we
2803 // also build a canonical type.
2805 SplitQualType canonElementType = getCanonicalType(elementType).split();
2807 void *insertPos = nullptr;
2808 llvm::FoldingSetNodeID ID;
2809 DependentSizedArrayType::Profile(ID, *this,
2810 QualType(canonElementType.Ty, 0),
2811 ASM, elementTypeQuals, numElements);
2813 // Look for an existing type with these properties.
2814 DependentSizedArrayType *canonTy =
2815 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2817 // If we don't have one, build one.
2819 canonTy = new (*this, TypeAlignment)
2820 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2821 QualType(), numElements, ASM, elementTypeQuals,
2823 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2824 Types.push_back(canonTy);
2827 // Apply qualifiers from the element type to the array.
2828 QualType canon = getQualifiedType(QualType(canonTy,0),
2829 canonElementType.Quals);
2831 // If we didn't need extra canonicalization for the element type or the size
2832 // expression, then just use that as our result.
2833 if (QualType(canonElementType.Ty, 0) == elementType &&
2834 canonTy->getSizeExpr() == numElements)
2837 // Otherwise, we need to build a type which follows the spelling
2838 // of the element type.
2839 DependentSizedArrayType *sugaredType
2840 = new (*this, TypeAlignment)
2841 DependentSizedArrayType(*this, elementType, canon, numElements,
2842 ASM, elementTypeQuals, brackets);
2843 Types.push_back(sugaredType);
2844 return QualType(sugaredType, 0);
2847 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2848 ArrayType::ArraySizeModifier ASM,
2849 unsigned elementTypeQuals) const {
2850 llvm::FoldingSetNodeID ID;
2851 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2853 void *insertPos = nullptr;
2854 if (IncompleteArrayType *iat =
2855 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2856 return QualType(iat, 0);
2858 // If the element type isn't canonical, this won't be a canonical type
2859 // either, so fill in the canonical type field. We also have to pull
2860 // qualifiers off the element type.
2863 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2864 SplitQualType canonSplit = getCanonicalType(elementType).split();
2865 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2866 ASM, elementTypeQuals);
2867 canon = getQualifiedType(canon, canonSplit.Quals);
2869 // Get the new insert position for the node we care about.
2870 IncompleteArrayType *existing =
2871 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2872 assert(!existing && "Shouldn't be in the map!"); (void) existing;
2875 IncompleteArrayType *newType = new (*this, TypeAlignment)
2876 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2878 IncompleteArrayTypes.InsertNode(newType, insertPos);
2879 Types.push_back(newType);
2880 return QualType(newType, 0);
2883 /// getVectorType - Return the unique reference to a vector type of
2884 /// the specified element type and size. VectorType must be a built-in type.
2885 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2886 VectorType::VectorKind VecKind) const {
2887 assert(vecType->isBuiltinType());
2889 // Check if we've already instantiated a vector of this type.
2890 llvm::FoldingSetNodeID ID;
2891 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2893 void *InsertPos = nullptr;
2894 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2895 return QualType(VTP, 0);
2897 // If the element type isn't canonical, this won't be a canonical type either,
2898 // so fill in the canonical type field.
2900 if (!vecType.isCanonical()) {
2901 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2903 // Get the new insert position for the node we care about.
2904 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2905 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2907 VectorType *New = new (*this, TypeAlignment)
2908 VectorType(vecType, NumElts, Canonical, VecKind);
2909 VectorTypes.InsertNode(New, InsertPos);
2910 Types.push_back(New);
2911 return QualType(New, 0);
2914 /// getExtVectorType - Return the unique reference to an extended vector type of
2915 /// the specified element type and size. VectorType must be a built-in type.
2917 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2918 assert(vecType->isBuiltinType() || vecType->isDependentType());
2920 // Check if we've already instantiated a vector of this type.
2921 llvm::FoldingSetNodeID ID;
2922 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2923 VectorType::GenericVector);
2924 void *InsertPos = nullptr;
2925 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2926 return QualType(VTP, 0);
2928 // If the element type isn't canonical, this won't be a canonical type either,
2929 // so fill in the canonical type field.
2931 if (!vecType.isCanonical()) {
2932 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2934 // Get the new insert position for the node we care about.
2935 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2936 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2938 ExtVectorType *New = new (*this, TypeAlignment)
2939 ExtVectorType(vecType, NumElts, Canonical);
2940 VectorTypes.InsertNode(New, InsertPos);
2941 Types.push_back(New);
2942 return QualType(New, 0);
2946 ASTContext::getDependentSizedExtVectorType(QualType vecType,
2948 SourceLocation AttrLoc) const {
2949 llvm::FoldingSetNodeID ID;
2950 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2953 void *InsertPos = nullptr;
2954 DependentSizedExtVectorType *Canon
2955 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2956 DependentSizedExtVectorType *New;
2958 // We already have a canonical version of this array type; use it as
2959 // the canonical type for a newly-built type.
2960 New = new (*this, TypeAlignment)
2961 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2964 QualType CanonVecTy = getCanonicalType(vecType);
2965 if (CanonVecTy == vecType) {
2966 New = new (*this, TypeAlignment)
2967 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2970 DependentSizedExtVectorType *CanonCheck
2971 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2972 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2974 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2976 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2978 New = new (*this, TypeAlignment)
2979 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2983 Types.push_back(New);
2984 return QualType(New, 0);
2987 /// \brief Determine whether \p T is canonical as the result type of a function.
2988 static bool isCanonicalResultType(QualType T) {
2989 return T.isCanonical() &&
2990 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2991 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2994 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2997 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2998 const FunctionType::ExtInfo &Info) const {
2999 // Unique functions, to guarantee there is only one function of a particular
3001 llvm::FoldingSetNodeID ID;
3002 FunctionNoProtoType::Profile(ID, ResultTy, Info);
3004 void *InsertPos = nullptr;
3005 if (FunctionNoProtoType *FT =
3006 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3007 return QualType(FT, 0);
3010 if (!isCanonicalResultType(ResultTy)) {
3012 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
3014 // Get the new insert position for the node we care about.
3015 FunctionNoProtoType *NewIP =
3016 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3017 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3020 FunctionNoProtoType *New = new (*this, TypeAlignment)
3021 FunctionNoProtoType(ResultTy, Canonical, Info);
3022 Types.push_back(New);
3023 FunctionNoProtoTypes.InsertNode(New, InsertPos);
3024 return QualType(New, 0);
3028 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3029 CanQualType CanResultType = getCanonicalType(ResultType);
3031 // Canonical result types do not have ARC lifetime qualifiers.
3032 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3033 Qualifiers Qs = CanResultType.getQualifiers();
3034 Qs.removeObjCLifetime();
3035 return CanQualType::CreateUnsafe(
3036 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3039 return CanResultType;
3043 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
3044 const FunctionProtoType::ExtProtoInfo &EPI) const {
3045 size_t NumArgs = ArgArray.size();
3047 // Unique functions, to guarantee there is only one function of a particular
3049 llvm::FoldingSetNodeID ID;
3050 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3053 void *InsertPos = nullptr;
3054 if (FunctionProtoType *FTP =
3055 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3056 return QualType(FTP, 0);
3058 // Determine whether the type being created is already canonical or not.
3060 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
3061 !EPI.HasTrailingReturn;
3062 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
3063 if (!ArgArray[i].isCanonicalAsParam())
3064 isCanonical = false;
3066 // If this type isn't canonical, get the canonical version of it.
3067 // The exception spec is not part of the canonical type.
3070 SmallVector<QualType, 16> CanonicalArgs;
3071 CanonicalArgs.reserve(NumArgs);
3072 for (unsigned i = 0; i != NumArgs; ++i)
3073 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
3075 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
3076 CanonicalEPI.HasTrailingReturn = false;
3077 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3079 // Adjust the canonical function result type.
3080 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
3081 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
3083 // Get the new insert position for the node we care about.
3084 FunctionProtoType *NewIP =
3085 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3086 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3089 // FunctionProtoType objects are allocated with extra bytes after
3090 // them for three variable size arrays at the end:
3091 // - parameter types
3092 // - exception types
3093 // - extended parameter information
3094 // Instead of the exception types, there could be a noexcept
3095 // expression, or information used to resolve the exception
3097 size_t Size = sizeof(FunctionProtoType) +
3098 NumArgs * sizeof(QualType);
3100 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3101 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3102 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3103 Size += sizeof(Expr*);
3104 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3105 Size += 2 * sizeof(FunctionDecl*);
3106 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3107 Size += sizeof(FunctionDecl*);
3110 // Put the ExtParameterInfos last. If all were equal, it would make
3111 // more sense to put these before the exception specification, because
3112 // it's much easier to skip past them compared to the elaborate switch
3113 // required to skip the exception specification. However, all is not
3114 // equal; ExtParameterInfos are used to model very uncommon features,
3115 // and it's better not to burden the more common paths.
3116 if (EPI.ExtParameterInfos) {
3117 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3120 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
3121 FunctionProtoType::ExtProtoInfo newEPI = EPI;
3122 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3123 Types.push_back(FTP);
3124 FunctionProtoTypes.InsertNode(FTP, InsertPos);
3125 return QualType(FTP, 0);
3128 /// Return pipe type for the specified type.
3129 QualType ASTContext::getPipeType(QualType T) const {
3130 llvm::FoldingSetNodeID ID;
3131 PipeType::Profile(ID, T);
3133 void *InsertPos = 0;
3134 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
3135 return QualType(PT, 0);
3137 // If the pipe element type isn't canonical, this won't be a canonical type
3138 // either, so fill in the canonical type field.
3140 if (!T.isCanonical()) {
3141 Canonical = getPipeType(getCanonicalType(T));
3143 // Get the new insert position for the node we care about.
3144 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
3145 assert(!NewIP && "Shouldn't be in the map!");
3148 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical);
3149 Types.push_back(New);
3150 PipeTypes.InsertNode(New, InsertPos);
3151 return QualType(New, 0);
3155 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3156 if (!isa<CXXRecordDecl>(D)) return false;
3157 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3158 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3160 if (RD->getDescribedClassTemplate() &&
3161 !isa<ClassTemplateSpecializationDecl>(RD))
3167 /// getInjectedClassNameType - Return the unique reference to the
3168 /// injected class name type for the specified templated declaration.
3169 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
3170 QualType TST) const {
3171 assert(NeedsInjectedClassNameType(Decl));
3172 if (Decl->TypeForDecl) {
3173 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3174 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
3175 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3176 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3177 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3180 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
3181 Decl->TypeForDecl = newType;
3182 Types.push_back(newType);
3184 return QualType(Decl->TypeForDecl, 0);
3187 /// getTypeDeclType - Return the unique reference to the type for the
3188 /// specified type declaration.
3189 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3190 assert(Decl && "Passed null for Decl param");
3191 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3193 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3194 return getTypedefType(Typedef);
3196 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3197 "Template type parameter types are always available.");
3199 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
3200 assert(Record->isFirstDecl() && "struct/union has previous declaration");
3201 assert(!NeedsInjectedClassNameType(Record));
3202 return getRecordType(Record);
3203 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
3204 assert(Enum->isFirstDecl() && "enum has previous declaration");
3205 return getEnumType(Enum);
3206 } else if (const UnresolvedUsingTypenameDecl *Using =
3207 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3208 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3209 Decl->TypeForDecl = newType;
3210 Types.push_back(newType);
3212 llvm_unreachable("TypeDecl without a type?");
3214 return QualType(Decl->TypeForDecl, 0);
3217 /// getTypedefType - Return the unique reference to the type for the
3218 /// specified typedef name decl.
3220 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3221 QualType Canonical) const {
3222 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3224 if (Canonical.isNull())
3225 Canonical = getCanonicalType(Decl->getUnderlyingType());
3226 TypedefType *newType = new(*this, TypeAlignment)
3227 TypedefType(Type::Typedef, Decl, Canonical);
3228 Decl->TypeForDecl = newType;
3229 Types.push_back(newType);
3230 return QualType(newType, 0);
3233 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
3234 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3236 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3237 if (PrevDecl->TypeForDecl)
3238 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3240 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3241 Decl->TypeForDecl = newType;
3242 Types.push_back(newType);
3243 return QualType(newType, 0);
3246 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3247 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3249 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3250 if (PrevDecl->TypeForDecl)
3251 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3253 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3254 Decl->TypeForDecl = newType;
3255 Types.push_back(newType);
3256 return QualType(newType, 0);
3259 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3260 QualType modifiedType,
3261 QualType equivalentType) {
3262 llvm::FoldingSetNodeID id;
3263 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3265 void *insertPos = nullptr;
3266 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3267 if (type) return QualType(type, 0);
3269 QualType canon = getCanonicalType(equivalentType);
3270 type = new (*this, TypeAlignment)
3271 AttributedType(canon, attrKind, modifiedType, equivalentType);
3273 Types.push_back(type);
3274 AttributedTypes.InsertNode(type, insertPos);
3276 return QualType(type, 0);
3279 /// \brief Retrieve a substitution-result type.
3281 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3282 QualType Replacement) const {
3283 assert(Replacement.isCanonical()
3284 && "replacement types must always be canonical");
3286 llvm::FoldingSetNodeID ID;
3287 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3288 void *InsertPos = nullptr;
3289 SubstTemplateTypeParmType *SubstParm
3290 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3293 SubstParm = new (*this, TypeAlignment)
3294 SubstTemplateTypeParmType(Parm, Replacement);
3295 Types.push_back(SubstParm);
3296 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3299 return QualType(SubstParm, 0);
3302 /// \brief Retrieve a
3303 QualType ASTContext::getSubstTemplateTypeParmPackType(
3304 const TemplateTypeParmType *Parm,
3305 const TemplateArgument &ArgPack) {
3307 for (const auto &P : ArgPack.pack_elements()) {
3308 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3309 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
3313 llvm::FoldingSetNodeID ID;
3314 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3315 void *InsertPos = nullptr;
3316 if (SubstTemplateTypeParmPackType *SubstParm
3317 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3318 return QualType(SubstParm, 0);
3321 if (!Parm->isCanonicalUnqualified()) {
3322 Canon = getCanonicalType(QualType(Parm, 0));
3323 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3325 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3328 SubstTemplateTypeParmPackType *SubstParm
3329 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3331 Types.push_back(SubstParm);
3332 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3333 return QualType(SubstParm, 0);
3336 /// \brief Retrieve the template type parameter type for a template
3337 /// parameter or parameter pack with the given depth, index, and (optionally)
3339 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3341 TemplateTypeParmDecl *TTPDecl) const {
3342 llvm::FoldingSetNodeID ID;
3343 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3344 void *InsertPos = nullptr;
3345 TemplateTypeParmType *TypeParm
3346 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3349 return QualType(TypeParm, 0);
3352 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3353 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3355 TemplateTypeParmType *TypeCheck
3356 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3357 assert(!TypeCheck && "Template type parameter canonical type broken");
3360 TypeParm = new (*this, TypeAlignment)
3361 TemplateTypeParmType(Depth, Index, ParameterPack);
3363 Types.push_back(TypeParm);
3364 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3366 return QualType(TypeParm, 0);
3370 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3371 SourceLocation NameLoc,
3372 const TemplateArgumentListInfo &Args,
3373 QualType Underlying) const {
3374 assert(!Name.getAsDependentTemplateName() &&
3375 "No dependent template names here!");
3376 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3378 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3379 TemplateSpecializationTypeLoc TL =
3380 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3381 TL.setTemplateKeywordLoc(SourceLocation());
3382 TL.setTemplateNameLoc(NameLoc);
3383 TL.setLAngleLoc(Args.getLAngleLoc());
3384 TL.setRAngleLoc(Args.getRAngleLoc());
3385 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3386 TL.setArgLocInfo(i, Args[i].getLocInfo());
3391 ASTContext::getTemplateSpecializationType(TemplateName Template,
3392 const TemplateArgumentListInfo &Args,
3393 QualType Underlying) const {
3394 assert(!Template.getAsDependentTemplateName() &&
3395 "No dependent template names here!");
3397 SmallVector<TemplateArgument, 4> ArgVec;
3398 ArgVec.reserve(Args.size());
3399 for (const TemplateArgumentLoc &Arg : Args.arguments())
3400 ArgVec.push_back(Arg.getArgument());
3402 return getTemplateSpecializationType(Template, ArgVec, Underlying);
3406 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3407 for (const TemplateArgument &Arg : Args)
3408 if (Arg.isPackExpansion())
3416 ASTContext::getTemplateSpecializationType(TemplateName Template,
3417 ArrayRef<TemplateArgument> Args,
3418 QualType Underlying) const {
3419 assert(!Template.getAsDependentTemplateName() &&
3420 "No dependent template names here!");
3421 // Look through qualified template names.
3422 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3423 Template = TemplateName(QTN->getTemplateDecl());
3426 Template.getAsTemplateDecl() &&
3427 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3429 if (!Underlying.isNull())
3430 CanonType = getCanonicalType(Underlying);
3432 // We can get here with an alias template when the specialization contains
3433 // a pack expansion that does not match up with a parameter pack.
3434 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
3435 "Caller must compute aliased type");
3436 IsTypeAlias = false;
3437 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
3440 // Allocate the (non-canonical) template specialization type, but don't
3441 // try to unique it: these types typically have location information that
3442 // we don't unique and don't want to lose.
3443 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3444 sizeof(TemplateArgument) * Args.size() +
3445 (IsTypeAlias? sizeof(QualType) : 0),
3447 TemplateSpecializationType *Spec
3448 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
3449 IsTypeAlias ? Underlying : QualType());
3451 Types.push_back(Spec);
3452 return QualType(Spec, 0);
3455 QualType ASTContext::getCanonicalTemplateSpecializationType(
3456 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
3457 assert(!Template.getAsDependentTemplateName() &&
3458 "No dependent template names here!");
3460 // Look through qualified template names.
3461 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3462 Template = TemplateName(QTN->getTemplateDecl());
3464 // Build the canonical template specialization type.
3465 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3466 SmallVector<TemplateArgument, 4> CanonArgs;
3467 unsigned NumArgs = Args.size();
3468 CanonArgs.reserve(NumArgs);
3469 for (const TemplateArgument &Arg : Args)
3470 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
3472 // Determine whether this canonical template specialization type already
3474 llvm::FoldingSetNodeID ID;
3475 TemplateSpecializationType::Profile(ID, CanonTemplate,
3478 void *InsertPos = nullptr;
3479 TemplateSpecializationType *Spec
3480 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3483 // Allocate a new canonical template specialization type.
3484 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3485 sizeof(TemplateArgument) * NumArgs),
3487 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3489 QualType(), QualType());
3490 Types.push_back(Spec);
3491 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3494 assert(Spec->isDependentType() &&
3495 "Non-dependent template-id type must have a canonical type");
3496 return QualType(Spec, 0);
3500 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3501 NestedNameSpecifier *NNS,
3502 QualType NamedType) const {
3503 llvm::FoldingSetNodeID ID;
3504 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3506 void *InsertPos = nullptr;
3507 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3509 return QualType(T, 0);
3511 QualType Canon = NamedType;
3512 if (!Canon.isCanonical()) {
3513 Canon = getCanonicalType(NamedType);
3514 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3515 assert(!CheckT && "Elaborated canonical type broken");
3519 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
3521 ElaboratedTypes.InsertNode(T, InsertPos);
3522 return QualType(T, 0);
3526 ASTContext::getParenType(QualType InnerType) const {
3527 llvm::FoldingSetNodeID ID;
3528 ParenType::Profile(ID, InnerType);
3530 void *InsertPos = nullptr;
3531 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3533 return QualType(T, 0);
3535 QualType Canon = InnerType;
3536 if (!Canon.isCanonical()) {
3537 Canon = getCanonicalType(InnerType);
3538 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3539 assert(!CheckT && "Paren canonical type broken");
3543 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
3545 ParenTypes.InsertNode(T, InsertPos);
3546 return QualType(T, 0);
3549 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3550 NestedNameSpecifier *NNS,
3551 const IdentifierInfo *Name,
3552 QualType Canon) const {
3553 if (Canon.isNull()) {
3554 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3555 ElaboratedTypeKeyword CanonKeyword = Keyword;
3556 if (Keyword == ETK_None)
3557 CanonKeyword = ETK_Typename;
3559 if (CanonNNS != NNS || CanonKeyword != Keyword)
3560 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3563 llvm::FoldingSetNodeID ID;
3564 DependentNameType::Profile(ID, Keyword, NNS, Name);
3566 void *InsertPos = nullptr;
3567 DependentNameType *T
3568 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3570 return QualType(T, 0);
3572 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
3574 DependentNameTypes.InsertNode(T, InsertPos);
3575 return QualType(T, 0);
3579 ASTContext::getDependentTemplateSpecializationType(
3580 ElaboratedTypeKeyword Keyword,
3581 NestedNameSpecifier *NNS,
3582 const IdentifierInfo *Name,
3583 const TemplateArgumentListInfo &Args) const {
3584 // TODO: avoid this copy
3585 SmallVector<TemplateArgument, 16> ArgCopy;
3586 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3587 ArgCopy.push_back(Args[I].getArgument());
3588 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
3592 ASTContext::getDependentTemplateSpecializationType(
3593 ElaboratedTypeKeyword Keyword,
3594 NestedNameSpecifier *NNS,
3595 const IdentifierInfo *Name,
3596 ArrayRef<TemplateArgument> Args) const {
3597 assert((!NNS || NNS->isDependent()) &&
3598 "nested-name-specifier must be dependent");
3600 llvm::FoldingSetNodeID ID;
3601 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3604 void *InsertPos = nullptr;
3605 DependentTemplateSpecializationType *T
3606 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3608 return QualType(T, 0);
3610 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3612 ElaboratedTypeKeyword CanonKeyword = Keyword;
3613 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3615 bool AnyNonCanonArgs = false;
3616 unsigned NumArgs = Args.size();
3617 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3618 for (unsigned I = 0; I != NumArgs; ++I) {
3619 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3620 if (!CanonArgs[I].structurallyEquals(Args[I]))
3621 AnyNonCanonArgs = true;
3625 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3626 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3630 // Find the insert position again.
3631 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3634 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3635 sizeof(TemplateArgument) * NumArgs),
3637 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3640 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3641 return QualType(T, 0);
3644 QualType ASTContext::getPackExpansionType(QualType Pattern,
3645 Optional<unsigned> NumExpansions) {
3646 llvm::FoldingSetNodeID ID;
3647 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3649 assert(Pattern->containsUnexpandedParameterPack() &&
3650 "Pack expansions must expand one or more parameter packs");
3651 void *InsertPos = nullptr;
3652 PackExpansionType *T
3653 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3655 return QualType(T, 0);
3658 if (!Pattern.isCanonical()) {
3659 Canon = getCanonicalType(Pattern);
3660 // The canonical type might not contain an unexpanded parameter pack, if it
3661 // contains an alias template specialization which ignores one of its
3663 if (Canon->containsUnexpandedParameterPack()) {
3664 Canon = getPackExpansionType(Canon, NumExpansions);
3666 // Find the insert position again, in case we inserted an element into
3667 // PackExpansionTypes and invalidated our insert position.
3668 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3672 T = new (*this, TypeAlignment)
3673 PackExpansionType(Pattern, Canon, NumExpansions);
3675 PackExpansionTypes.InsertNode(T, InsertPos);
3676 return QualType(T, 0);
3679 /// CmpProtocolNames - Comparison predicate for sorting protocols
3681 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3682 ObjCProtocolDecl *const *RHS) {
3683 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
3686 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3687 if (Protocols.empty()) return true;
3689 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3692 for (unsigned i = 1; i != Protocols.size(); ++i)
3693 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
3694 Protocols[i]->getCanonicalDecl() != Protocols[i])
3700 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
3701 // Sort protocols, keyed by name.
3702 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
3705 for (ObjCProtocolDecl *&P : Protocols)
3706 P = P->getCanonicalDecl();
3708 // Remove duplicates.
3709 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3710 Protocols.erase(ProtocolsEnd, Protocols.end());
3713 QualType ASTContext::getObjCObjectType(QualType BaseType,
3714 ObjCProtocolDecl * const *Protocols,
3715 unsigned NumProtocols) const {
3716 return getObjCObjectType(BaseType, { },
3717 llvm::makeArrayRef(Protocols, NumProtocols),
3718 /*isKindOf=*/false);
3721 QualType ASTContext::getObjCObjectType(
3723 ArrayRef<QualType> typeArgs,
3724 ArrayRef<ObjCProtocolDecl *> protocols,
3725 bool isKindOf) const {
3726 // If the base type is an interface and there aren't any protocols or
3727 // type arguments to add, then the interface type will do just fine.
3728 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3729 isa<ObjCInterfaceType>(baseType))
3732 // Look in the folding set for an existing type.
3733 llvm::FoldingSetNodeID ID;
3734 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
3735 void *InsertPos = nullptr;
3736 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3737 return QualType(QT, 0);
3739 // Determine the type arguments to be used for canonicalization,
3740 // which may be explicitly specified here or written on the base
3742 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3743 if (effectiveTypeArgs.empty()) {
3744 if (auto baseObject = baseType->getAs<ObjCObjectType>())
3745 effectiveTypeArgs = baseObject->getTypeArgs();
3748 // Build the canonical type, which has the canonical base type and a
3749 // sorted-and-uniqued list of protocols and the type arguments
3752 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3753 effectiveTypeArgs.end(),
3754 [&](QualType type) {
3755 return type.isCanonical();
3757 bool protocolsSorted = areSortedAndUniqued(protocols);
3758 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3759 // Determine the canonical type arguments.
3760 ArrayRef<QualType> canonTypeArgs;
3761 SmallVector<QualType, 4> canonTypeArgsVec;
3762 if (!typeArgsAreCanonical) {
3763 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3764 for (auto typeArg : effectiveTypeArgs)
3765 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3766 canonTypeArgs = canonTypeArgsVec;
3768 canonTypeArgs = effectiveTypeArgs;
3771 ArrayRef<ObjCProtocolDecl *> canonProtocols;
3772 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3773 if (!protocolsSorted) {
3774 canonProtocolsVec.append(protocols.begin(), protocols.end());
3775 SortAndUniqueProtocols(canonProtocolsVec);
3776 canonProtocols = canonProtocolsVec;
3778 canonProtocols = protocols;
3781 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
3782 canonProtocols, isKindOf);
3784 // Regenerate InsertPos.
3785 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3788 unsigned size = sizeof(ObjCObjectTypeImpl);
3789 size += typeArgs.size() * sizeof(QualType);
3790 size += protocols.size() * sizeof(ObjCProtocolDecl *);
3791 void *mem = Allocate(size, TypeAlignment);
3792 ObjCObjectTypeImpl *T =
3793 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3797 ObjCObjectTypes.InsertNode(T, InsertPos);
3798 return QualType(T, 0);
3801 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3802 /// protocol list adopt all protocols in QT's qualified-id protocol
3804 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3805 ObjCInterfaceDecl *IC) {
3806 if (!QT->isObjCQualifiedIdType())
3809 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3810 // If both the right and left sides have qualifiers.
3811 for (auto *Proto : OPT->quals()) {
3812 if (!IC->ClassImplementsProtocol(Proto, false))
3820 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3821 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
3823 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3824 ObjCInterfaceDecl *IDecl) {
3825 if (!QT->isObjCQualifiedIdType())
3827 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3830 if (!IDecl->hasDefinition())
3832 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3833 CollectInheritedProtocols(IDecl, InheritedProtocols);
3834 if (InheritedProtocols.empty())
3836 // Check that if every protocol in list of id<plist> conforms to a protcol
3837 // of IDecl's, then bridge casting is ok.
3838 bool Conforms = false;
3839 for (auto *Proto : OPT->quals()) {
3841 for (auto *PI : InheritedProtocols) {
3842 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3853 for (auto *PI : InheritedProtocols) {
3854 // If both the right and left sides have qualifiers.
3855 bool Adopts = false;
3856 for (auto *Proto : OPT->quals()) {
3857 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
3858 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
3867 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3868 /// the given object type.
3869 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
3870 llvm::FoldingSetNodeID ID;
3871 ObjCObjectPointerType::Profile(ID, ObjectT);
3873 void *InsertPos = nullptr;
3874 if (ObjCObjectPointerType *QT =
3875 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3876 return QualType(QT, 0);
3878 // Find the canonical object type.
3880 if (!ObjectT.isCanonical()) {
3881 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3883 // Regenerate InsertPos.
3884 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3888 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3889 ObjCObjectPointerType *QType =
3890 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
3892 Types.push_back(QType);
3893 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
3894 return QualType(QType, 0);
3897 /// getObjCInterfaceType - Return the unique reference to the type for the
3898 /// specified ObjC interface decl. The list of protocols is optional.
3899 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3900 ObjCInterfaceDecl *PrevDecl) const {
3901 if (Decl->TypeForDecl)
3902 return QualType(Decl->TypeForDecl, 0);
3905 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3906 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3907 return QualType(PrevDecl->TypeForDecl, 0);
3910 // Prefer the definition, if there is one.
3911 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3914 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3915 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3916 Decl->TypeForDecl = T;
3918 return QualType(T, 0);
3921 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3922 /// TypeOfExprType AST's (since expression's are never shared). For example,
3923 /// multiple declarations that refer to "typeof(x)" all contain different
3924 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
3925 /// on canonical type's (which are always unique).
3926 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
3927 TypeOfExprType *toe;
3928 if (tofExpr->isTypeDependent()) {
3929 llvm::FoldingSetNodeID ID;
3930 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3932 void *InsertPos = nullptr;
3933 DependentTypeOfExprType *Canon
3934 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3936 // We already have a "canonical" version of an identical, dependent
3937 // typeof(expr) type. Use that as our canonical type.
3938 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3939 QualType((TypeOfExprType*)Canon, 0));
3941 // Build a new, canonical typeof(expr) type.
3943 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3944 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3948 QualType Canonical = getCanonicalType(tofExpr->getType());
3949 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3951 Types.push_back(toe);
3952 return QualType(toe, 0);
3955 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3956 /// TypeOfType nodes. The only motivation to unique these nodes would be
3957 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3958 /// an issue. This doesn't affect the type checker, since it operates
3959 /// on canonical types (which are always unique).
3960 QualType ASTContext::getTypeOfType(QualType tofType) const {
3961 QualType Canonical = getCanonicalType(tofType);
3962 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3963 Types.push_back(tot);
3964 return QualType(tot, 0);
3967 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3968 /// nodes. This would never be helpful, since each such type has its own
3969 /// expression, and would not give a significant memory saving, since there
3970 /// is an Expr tree under each such type.
3971 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3974 // C++11 [temp.type]p2:
3975 // If an expression e involves a template parameter, decltype(e) denotes a
3976 // unique dependent type. Two such decltype-specifiers refer to the same
3977 // type only if their expressions are equivalent (14.5.6.1).
3978 if (e->isInstantiationDependent()) {
3979 llvm::FoldingSetNodeID ID;
3980 DependentDecltypeType::Profile(ID, *this, e);
3982 void *InsertPos = nullptr;
3983 DependentDecltypeType *Canon
3984 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3986 // Build a new, canonical typeof(expr) type.
3987 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3988 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3990 dt = new (*this, TypeAlignment)
3991 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
3993 dt = new (*this, TypeAlignment)
3994 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
3996 Types.push_back(dt);
3997 return QualType(dt, 0);
4000 /// getUnaryTransformationType - We don't unique these, since the memory
4001 /// savings are minimal and these are rare.
4002 QualType ASTContext::getUnaryTransformType(QualType BaseType,
4003 QualType UnderlyingType,
4004 UnaryTransformType::UTTKind Kind)
4006 UnaryTransformType *ut = nullptr;
4008 if (BaseType->isDependentType()) {
4009 // Look in the folding set for an existing type.
4010 llvm::FoldingSetNodeID ID;
4011 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4013 void *InsertPos = nullptr;
4014 DependentUnaryTransformType *Canon
4015 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4018 // Build a new, canonical __underlying_type(type) type.
4019 Canon = new (*this, TypeAlignment)
4020 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4022 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4024 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4026 QualType(Canon, 0));
4028 QualType CanonType = getCanonicalType(UnderlyingType);
4029 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4030 UnderlyingType, Kind,
4033 Types.push_back(ut);
4034 return QualType(ut, 0);
4037 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
4038 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4039 /// canonical deduced-but-dependent 'auto' type.
4040 QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
4041 bool IsDependent) const {
4042 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
4043 return getAutoDeductType();
4045 // Look in the folding set for an existing type.
4046 void *InsertPos = nullptr;
4047 llvm::FoldingSetNodeID ID;
4048 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
4049 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4050 return QualType(AT, 0);
4052 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
4055 Types.push_back(AT);
4057 AutoTypes.InsertNode(AT, InsertPos);
4058 return QualType(AT, 0);
4061 /// getAtomicType - Return the uniqued reference to the atomic type for
4062 /// the given value type.
4063 QualType ASTContext::getAtomicType(QualType T) const {
4064 // Unique pointers, to guarantee there is only one pointer of a particular
4066 llvm::FoldingSetNodeID ID;
4067 AtomicType::Profile(ID, T);
4069 void *InsertPos = nullptr;
4070 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4071 return QualType(AT, 0);
4073 // If the atomic value type isn't canonical, this won't be a canonical type
4074 // either, so fill in the canonical type field.
4076 if (!T.isCanonical()) {
4077 Canonical = getAtomicType(getCanonicalType(T));
4079 // Get the new insert position for the node we care about.
4080 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
4081 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4083 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4084 Types.push_back(New);
4085 AtomicTypes.InsertNode(New, InsertPos);
4086 return QualType(New, 0);
4089 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
4090 QualType ASTContext::getAutoDeductType() const {
4091 if (AutoDeductTy.isNull())
4092 AutoDeductTy = QualType(
4093 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
4094 /*dependent*/false),
4096 return AutoDeductTy;
4099 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4100 QualType ASTContext::getAutoRRefDeductType() const {
4101 if (AutoRRefDeductTy.isNull())
4102 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4103 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4104 return AutoRRefDeductTy;
4107 /// getTagDeclType - Return the unique reference to the type for the
4108 /// specified TagDecl (struct/union/class/enum) decl.
4109 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
4111 // FIXME: What is the design on getTagDeclType when it requires casting
4112 // away const? mutable?
4113 return getTypeDeclType(const_cast<TagDecl*>(Decl));
4116 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4117 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4118 /// needs to agree with the definition in <stddef.h>.
4119 CanQualType ASTContext::getSizeType() const {
4120 return getFromTargetType(Target->getSizeType());
4123 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4124 CanQualType ASTContext::getIntMaxType() const {
4125 return getFromTargetType(Target->getIntMaxType());
4128 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4129 CanQualType ASTContext::getUIntMaxType() const {
4130 return getFromTargetType(Target->getUIntMaxType());
4133 /// getSignedWCharType - Return the type of "signed wchar_t".
4134 /// Used when in C++, as a GCC extension.
4135 QualType ASTContext::getSignedWCharType() const {
4136 // FIXME: derive from "Target" ?
4140 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4141 /// Used when in C++, as a GCC extension.
4142 QualType ASTContext::getUnsignedWCharType() const {
4143 // FIXME: derive from "Target" ?
4144 return UnsignedIntTy;
4147 QualType ASTContext::getIntPtrType() const {
4148 return getFromTargetType(Target->getIntPtrType());
4151 QualType ASTContext::getUIntPtrType() const {
4152 return getCorrespondingUnsignedType(getIntPtrType());
4155 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
4156 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4157 QualType ASTContext::getPointerDiffType() const {
4158 return getFromTargetType(Target->getPtrDiffType(0));
4161 /// \brief Return the unique type for "pid_t" defined in
4162 /// <sys/types.h>. We need this to compute the correct type for vfork().
4163 QualType ASTContext::getProcessIDType() const {
4164 return getFromTargetType(Target->getProcessIDType());
4167 //===----------------------------------------------------------------------===//
4169 //===----------------------------------------------------------------------===//
4171 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
4172 // Push qualifiers into arrays, and then discard any remaining
4174 T = getCanonicalType(T);
4175 T = getVariableArrayDecayedType(T);
4176 const Type *Ty = T.getTypePtr();
4178 if (isa<ArrayType>(Ty)) {
4179 Result = getArrayDecayedType(QualType(Ty,0));
4180 } else if (isa<FunctionType>(Ty)) {
4181 Result = getPointerType(QualType(Ty, 0));
4183 Result = QualType(Ty, 0);
4186 return CanQualType::CreateUnsafe(Result);
4189 QualType ASTContext::getUnqualifiedArrayType(QualType type,
4190 Qualifiers &quals) {
4191 SplitQualType splitType = type.getSplitUnqualifiedType();
4193 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4194 // the unqualified desugared type and then drops it on the floor.
4195 // We then have to strip that sugar back off with
4196 // getUnqualifiedDesugaredType(), which is silly.
4197 const ArrayType *AT =
4198 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
4200 // If we don't have an array, just use the results in splitType.
4202 quals = splitType.Quals;
4203 return QualType(splitType.Ty, 0);
4206 // Otherwise, recurse on the array's element type.
4207 QualType elementType = AT->getElementType();
4208 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4210 // If that didn't change the element type, AT has no qualifiers, so we
4211 // can just use the results in splitType.
4212 if (elementType == unqualElementType) {
4213 assert(quals.empty()); // from the recursive call
4214 quals = splitType.Quals;
4215 return QualType(splitType.Ty, 0);
4218 // Otherwise, add in the qualifiers from the outermost type, then
4219 // build the type back up.
4220 quals.addConsistentQualifiers(splitType.Quals);
4222 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4223 return getConstantArrayType(unqualElementType, CAT->getSize(),
4224 CAT->getSizeModifier(), 0);
4227 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
4228 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
4231 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
4232 return getVariableArrayType(unqualElementType,
4234 VAT->getSizeModifier(),
4235 VAT->getIndexTypeCVRQualifiers(),
4236 VAT->getBracketsRange());
4239 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
4240 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
4241 DSAT->getSizeModifier(), 0,
4245 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4246 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4247 /// they point to and return true. If T1 and T2 aren't pointer types
4248 /// or pointer-to-member types, or if they are not similar at this
4249 /// level, returns false and leaves T1 and T2 unchanged. Top-level
4250 /// qualifiers on T1 and T2 are ignored. This function will typically
4251 /// be called in a loop that successively "unwraps" pointer and
4252 /// pointer-to-member types to compare them at each level.
4253 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4254 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4255 *T2PtrType = T2->getAs<PointerType>();
4256 if (T1PtrType && T2PtrType) {
4257 T1 = T1PtrType->getPointeeType();
4258 T2 = T2PtrType->getPointeeType();
4262 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4263 *T2MPType = T2->getAs<MemberPointerType>();
4264 if (T1MPType && T2MPType &&
4265 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4266 QualType(T2MPType->getClass(), 0))) {
4267 T1 = T1MPType->getPointeeType();
4268 T2 = T2MPType->getPointeeType();
4272 if (getLangOpts().ObjC1) {
4273 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4274 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4275 if (T1OPType && T2OPType) {
4276 T1 = T1OPType->getPointeeType();
4277 T2 = T2OPType->getPointeeType();
4282 // FIXME: Block pointers, too?
4288 ASTContext::getNameForTemplate(TemplateName Name,
4289 SourceLocation NameLoc) const {
4290 switch (Name.getKind()) {
4291 case TemplateName::QualifiedTemplate:
4292 case TemplateName::Template:
4293 // DNInfo work in progress: CHECKME: what about DNLoc?
4294 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4297 case TemplateName::OverloadedTemplate: {
4298 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4299 // DNInfo work in progress: CHECKME: what about DNLoc?
4300 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4303 case TemplateName::DependentTemplate: {
4304 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4305 DeclarationName DName;
4306 if (DTN->isIdentifier()) {
4307 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4308 return DeclarationNameInfo(DName, NameLoc);
4310 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4311 // DNInfo work in progress: FIXME: source locations?
4312 DeclarationNameLoc DNLoc;
4313 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4314 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4315 return DeclarationNameInfo(DName, NameLoc, DNLoc);
4319 case TemplateName::SubstTemplateTemplateParm: {
4320 SubstTemplateTemplateParmStorage *subst
4321 = Name.getAsSubstTemplateTemplateParm();
4322 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4326 case TemplateName::SubstTemplateTemplateParmPack: {
4327 SubstTemplateTemplateParmPackStorage *subst
4328 = Name.getAsSubstTemplateTemplateParmPack();
4329 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4334 llvm_unreachable("bad template name kind!");
4337 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4338 switch (Name.getKind()) {
4339 case TemplateName::QualifiedTemplate:
4340 case TemplateName::Template: {
4341 TemplateDecl *Template = Name.getAsTemplateDecl();
4342 if (TemplateTemplateParmDecl *TTP
4343 = dyn_cast<TemplateTemplateParmDecl>(Template))
4344 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4346 // The canonical template name is the canonical template declaration.
4347 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4350 case TemplateName::OverloadedTemplate:
4351 llvm_unreachable("cannot canonicalize overloaded template");
4353 case TemplateName::DependentTemplate: {
4354 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4355 assert(DTN && "Non-dependent template names must refer to template decls.");
4356 return DTN->CanonicalTemplateName;
4359 case TemplateName::SubstTemplateTemplateParm: {
4360 SubstTemplateTemplateParmStorage *subst
4361 = Name.getAsSubstTemplateTemplateParm();
4362 return getCanonicalTemplateName(subst->getReplacement());
4365 case TemplateName::SubstTemplateTemplateParmPack: {
4366 SubstTemplateTemplateParmPackStorage *subst
4367 = Name.getAsSubstTemplateTemplateParmPack();
4368 TemplateTemplateParmDecl *canonParameter
4369 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4370 TemplateArgument canonArgPack
4371 = getCanonicalTemplateArgument(subst->getArgumentPack());
4372 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4376 llvm_unreachable("bad template name!");
4379 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4380 X = getCanonicalTemplateName(X);
4381 Y = getCanonicalTemplateName(Y);
4382 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4386 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4387 switch (Arg.getKind()) {
4388 case TemplateArgument::Null:
4391 case TemplateArgument::Expression:
4394 case TemplateArgument::Declaration: {
4395 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4396 return TemplateArgument(D, Arg.getParamTypeForDecl());
4399 case TemplateArgument::NullPtr:
4400 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4403 case TemplateArgument::Template:
4404 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4406 case TemplateArgument::TemplateExpansion:
4407 return TemplateArgument(getCanonicalTemplateName(
4408 Arg.getAsTemplateOrTemplatePattern()),
4409 Arg.getNumTemplateExpansions());
4411 case TemplateArgument::Integral:
4412 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4414 case TemplateArgument::Type:
4415 return TemplateArgument(getCanonicalType(Arg.getAsType()));
4417 case TemplateArgument::Pack: {
4418 if (Arg.pack_size() == 0)
4421 TemplateArgument *CanonArgs
4422 = new (*this) TemplateArgument[Arg.pack_size()];
4424 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4425 AEnd = Arg.pack_end();
4426 A != AEnd; (void)++A, ++Idx)
4427 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4429 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
4433 // Silence GCC warning
4434 llvm_unreachable("Unhandled template argument kind");
4437 NestedNameSpecifier *
4438 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4442 switch (NNS->getKind()) {
4443 case NestedNameSpecifier::Identifier:
4444 // Canonicalize the prefix but keep the identifier the same.
4445 return NestedNameSpecifier::Create(*this,
4446 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4447 NNS->getAsIdentifier());
4449 case NestedNameSpecifier::Namespace:
4450 // A namespace is canonical; build a nested-name-specifier with
4451 // this namespace and no prefix.
4452 return NestedNameSpecifier::Create(*this, nullptr,
4453 NNS->getAsNamespace()->getOriginalNamespace());
4455 case NestedNameSpecifier::NamespaceAlias:
4456 // A namespace is canonical; build a nested-name-specifier with
4457 // this namespace and no prefix.
4458 return NestedNameSpecifier::Create(*this, nullptr,
4459 NNS->getAsNamespaceAlias()->getNamespace()
4460 ->getOriginalNamespace());
4462 case NestedNameSpecifier::TypeSpec:
4463 case NestedNameSpecifier::TypeSpecWithTemplate: {
4464 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4466 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4467 // break it apart into its prefix and identifier, then reconsititute those
4468 // as the canonical nested-name-specifier. This is required to canonicalize
4469 // a dependent nested-name-specifier involving typedefs of dependent-name
4471 // typedef typename T::type T1;
4472 // typedef typename T1::type T2;
4473 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4474 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4475 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4477 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4478 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4480 return NestedNameSpecifier::Create(*this, nullptr, false,
4481 const_cast<Type *>(T.getTypePtr()));
4484 case NestedNameSpecifier::Global:
4485 case NestedNameSpecifier::Super:
4486 // The global specifier and __super specifer are canonical and unique.
4490 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4493 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4494 // Handle the non-qualified case efficiently.
4495 if (!T.hasLocalQualifiers()) {
4496 // Handle the common positive case fast.
4497 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4501 // Handle the common negative case fast.
4502 if (!isa<ArrayType>(T.getCanonicalType()))
4505 // Apply any qualifiers from the array type to the element type. This
4506 // implements C99 6.7.3p8: "If the specification of an array type includes
4507 // any type qualifiers, the element type is so qualified, not the array type."
4509 // If we get here, we either have type qualifiers on the type, or we have
4510 // sugar such as a typedef in the way. If we have type qualifiers on the type
4511 // we must propagate them down into the element type.
4513 SplitQualType split = T.getSplitDesugaredType();
4514 Qualifiers qs = split.Quals;
4516 // If we have a simple case, just return now.
4517 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4518 if (!ATy || qs.empty())
4521 // Otherwise, we have an array and we have qualifiers on it. Push the
4522 // qualifiers into the array element type and return a new array type.
4523 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4525 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4526 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4527 CAT->getSizeModifier(),
4528 CAT->getIndexTypeCVRQualifiers()));
4529 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4530 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4531 IAT->getSizeModifier(),
4532 IAT->getIndexTypeCVRQualifiers()));
4534 if (const DependentSizedArrayType *DSAT
4535 = dyn_cast<DependentSizedArrayType>(ATy))
4536 return cast<ArrayType>(
4537 getDependentSizedArrayType(NewEltTy,
4538 DSAT->getSizeExpr(),
4539 DSAT->getSizeModifier(),
4540 DSAT->getIndexTypeCVRQualifiers(),
4541 DSAT->getBracketsRange()));
4543 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4544 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4546 VAT->getSizeModifier(),
4547 VAT->getIndexTypeCVRQualifiers(),
4548 VAT->getBracketsRange()));
4551 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4552 if (T->isArrayType() || T->isFunctionType())
4553 return getDecayedType(T);
4557 QualType ASTContext::getSignatureParameterType(QualType T) const {
4558 T = getVariableArrayDecayedType(T);
4559 T = getAdjustedParameterType(T);
4560 return T.getUnqualifiedType();
4563 QualType ASTContext::getExceptionObjectType(QualType T) const {
4564 // C++ [except.throw]p3:
4565 // A throw-expression initializes a temporary object, called the exception
4566 // object, the type of which is determined by removing any top-level
4567 // cv-qualifiers from the static type of the operand of throw and adjusting
4568 // the type from "array of T" or "function returning T" to "pointer to T"
4569 // or "pointer to function returning T", [...]
4570 T = getVariableArrayDecayedType(T);
4571 if (T->isArrayType() || T->isFunctionType())
4572 T = getDecayedType(T);
4573 return T.getUnqualifiedType();
4576 /// getArrayDecayedType - Return the properly qualified result of decaying the
4577 /// specified array type to a pointer. This operation is non-trivial when
4578 /// handling typedefs etc. The canonical type of "T" must be an array type,
4579 /// this returns a pointer to a properly qualified element of the array.
4581 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4582 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4583 // Get the element type with 'getAsArrayType' so that we don't lose any
4584 // typedefs in the element type of the array. This also handles propagation
4585 // of type qualifiers from the array type into the element type if present
4587 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4588 assert(PrettyArrayType && "Not an array type!");
4590 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4592 // int x[restrict 4] -> int *restrict
4593 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
4596 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4597 return getBaseElementType(array->getElementType());
4600 QualType ASTContext::getBaseElementType(QualType type) const {
4603 SplitQualType split = type.getSplitDesugaredType();
4604 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4607 type = array->getElementType();
4608 qs.addConsistentQualifiers(split.Quals);
4611 return getQualifiedType(type, qs);
4614 /// getConstantArrayElementCount - Returns number of constant array elements.
4616 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4617 uint64_t ElementCount = 1;
4619 ElementCount *= CA->getSize().getZExtValue();
4620 CA = dyn_cast_or_null<ConstantArrayType>(
4621 CA->getElementType()->getAsArrayTypeUnsafe());
4623 return ElementCount;
4626 /// getFloatingRank - Return a relative rank for floating point types.
4627 /// This routine will assert if passed a built-in type that isn't a float.
4628 static FloatingRank getFloatingRank(QualType T) {
4629 if (const ComplexType *CT = T->getAs<ComplexType>())
4630 return getFloatingRank(CT->getElementType());
4632 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4633 switch (T->getAs<BuiltinType>()->getKind()) {
4634 default: llvm_unreachable("getFloatingRank(): not a floating type");
4635 case BuiltinType::Half: return HalfRank;
4636 case BuiltinType::Float: return FloatRank;
4637 case BuiltinType::Double: return DoubleRank;
4638 case BuiltinType::LongDouble: return LongDoubleRank;
4639 case BuiltinType::Float128: return Float128Rank;
4643 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4644 /// point or a complex type (based on typeDomain/typeSize).
4645 /// 'typeDomain' is a real floating point or complex type.
4646 /// 'typeSize' is a real floating point or complex type.
4647 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4648 QualType Domain) const {
4649 FloatingRank EltRank = getFloatingRank(Size);
4650 if (Domain->isComplexType()) {
4652 case HalfRank: llvm_unreachable("Complex half is not supported");
4653 case FloatRank: return FloatComplexTy;
4654 case DoubleRank: return DoubleComplexTy;
4655 case LongDoubleRank: return LongDoubleComplexTy;
4656 case Float128Rank: return Float128ComplexTy;
4660 assert(Domain->isRealFloatingType() && "Unknown domain!");
4662 case HalfRank: return HalfTy;
4663 case FloatRank: return FloatTy;
4664 case DoubleRank: return DoubleTy;
4665 case LongDoubleRank: return LongDoubleTy;
4666 case Float128Rank: return Float128Ty;
4668 llvm_unreachable("getFloatingRank(): illegal value for rank");
4671 /// getFloatingTypeOrder - Compare the rank of the two specified floating
4672 /// point types, ignoring the domain of the type (i.e. 'double' ==
4673 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
4674 /// LHS < RHS, return -1.
4675 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
4676 FloatingRank LHSR = getFloatingRank(LHS);
4677 FloatingRank RHSR = getFloatingRank(RHS);
4686 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4687 /// routine will assert if passed a built-in type that isn't an integer or enum,
4688 /// or if it is not canonicalized.
4689 unsigned ASTContext::getIntegerRank(const Type *T) const {
4690 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
4692 switch (cast<BuiltinType>(T)->getKind()) {
4693 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
4694 case BuiltinType::Bool:
4695 return 1 + (getIntWidth(BoolTy) << 3);
4696 case BuiltinType::Char_S:
4697 case BuiltinType::Char_U:
4698 case BuiltinType::SChar:
4699 case BuiltinType::UChar:
4700 return 2 + (getIntWidth(CharTy) << 3);
4701 case BuiltinType::Short:
4702 case BuiltinType::UShort:
4703 return 3 + (getIntWidth(ShortTy) << 3);
4704 case BuiltinType::Int:
4705 case BuiltinType::UInt:
4706 return 4 + (getIntWidth(IntTy) << 3);
4707 case BuiltinType::Long:
4708 case BuiltinType::ULong:
4709 return 5 + (getIntWidth(LongTy) << 3);
4710 case BuiltinType::LongLong:
4711 case BuiltinType::ULongLong:
4712 return 6 + (getIntWidth(LongLongTy) << 3);
4713 case BuiltinType::Int128:
4714 case BuiltinType::UInt128:
4715 return 7 + (getIntWidth(Int128Ty) << 3);
4719 /// \brief Whether this is a promotable bitfield reference according
4720 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4722 /// \returns the type this bit-field will promote to, or NULL if no
4723 /// promotion occurs.
4724 QualType ASTContext::isPromotableBitField(Expr *E) const {
4725 if (E->isTypeDependent() || E->isValueDependent())
4728 // FIXME: We should not do this unless E->refersToBitField() is true. This
4729 // matters in C where getSourceBitField() will find bit-fields for various
4730 // cases where the source expression is not a bit-field designator.
4732 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
4736 QualType FT = Field->getType();
4738 uint64_t BitWidth = Field->getBitWidthValue(*this);
4739 uint64_t IntSize = getTypeSize(IntTy);
4740 // C++ [conv.prom]p5:
4741 // A prvalue for an integral bit-field can be converted to a prvalue of type
4742 // int if int can represent all the values of the bit-field; otherwise, it
4743 // can be converted to unsigned int if unsigned int can represent all the
4744 // values of the bit-field. If the bit-field is larger yet, no integral
4745 // promotion applies to it.
4747 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4748 // If an int can represent all values of the original type (as restricted by
4749 // the width, for a bit-field), the value is converted to an int; otherwise,
4750 // it is converted to an unsigned int.
4752 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4753 // We perform that promotion here to match GCC and C++.
4754 if (BitWidth < IntSize)
4757 if (BitWidth == IntSize)
4758 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4760 // Types bigger than int are not subject to promotions, and therefore act
4761 // like the base type. GCC has some weird bugs in this area that we
4762 // deliberately do not follow (GCC follows a pre-standard resolution to
4763 // C's DR315 which treats bit-width as being part of the type, and this leaks
4764 // into their semantics in some cases).
4768 /// getPromotedIntegerType - Returns the type that Promotable will
4769 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4771 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
4772 assert(!Promotable.isNull());
4773 assert(Promotable->isPromotableIntegerType());
4774 if (const EnumType *ET = Promotable->getAs<EnumType>())
4775 return ET->getDecl()->getPromotionType();
4777 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4778 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4779 // (3.9.1) can be converted to a prvalue of the first of the following
4780 // types that can represent all the values of its underlying type:
4781 // int, unsigned int, long int, unsigned long int, long long int, or
4782 // unsigned long long int [...]
4783 // FIXME: Is there some better way to compute this?
4784 if (BT->getKind() == BuiltinType::WChar_S ||
4785 BT->getKind() == BuiltinType::WChar_U ||
4786 BT->getKind() == BuiltinType::Char16 ||
4787 BT->getKind() == BuiltinType::Char32) {
4788 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4789 uint64_t FromSize = getTypeSize(BT);
4790 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4791 LongLongTy, UnsignedLongLongTy };
4792 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4793 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4794 if (FromSize < ToSize ||
4795 (FromSize == ToSize &&
4796 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4797 return PromoteTypes[Idx];
4799 llvm_unreachable("char type should fit into long long");
4803 // At this point, we should have a signed or unsigned integer type.
4804 if (Promotable->isSignedIntegerType())
4806 uint64_t PromotableSize = getIntWidth(Promotable);
4807 uint64_t IntSize = getIntWidth(IntTy);
4808 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4809 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4812 /// \brief Recurses in pointer/array types until it finds an objc retainable
4813 /// type and returns its ownership.
4814 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4815 while (!T.isNull()) {
4816 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4817 return T.getObjCLifetime();
4818 if (T->isArrayType())
4819 T = getBaseElementType(T);
4820 else if (const PointerType *PT = T->getAs<PointerType>())
4821 T = PT->getPointeeType();
4822 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4823 T = RT->getPointeeType();
4828 return Qualifiers::OCL_None;
4831 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4832 // Incomplete enum types are not treated as integer types.
4833 // FIXME: In C++, enum types are never integer types.
4834 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4835 return ET->getDecl()->getIntegerType().getTypePtr();
4839 /// getIntegerTypeOrder - Returns the highest ranked integer type:
4840 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
4841 /// LHS < RHS, return -1.
4842 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
4843 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4844 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
4846 // Unwrap enums to their underlying type.
4847 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4848 LHSC = getIntegerTypeForEnum(ET);
4849 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4850 RHSC = getIntegerTypeForEnum(ET);
4852 if (LHSC == RHSC) return 0;
4854 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4855 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
4857 unsigned LHSRank = getIntegerRank(LHSC);
4858 unsigned RHSRank = getIntegerRank(RHSC);
4860 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4861 if (LHSRank == RHSRank) return 0;
4862 return LHSRank > RHSRank ? 1 : -1;
4865 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4867 // If the unsigned [LHS] type is larger, return it.
4868 if (LHSRank >= RHSRank)
4871 // If the signed type can represent all values of the unsigned type, it
4872 // wins. Because we are dealing with 2's complement and types that are
4873 // powers of two larger than each other, this is always safe.
4877 // If the unsigned [RHS] type is larger, return it.
4878 if (RHSRank >= LHSRank)
4881 // If the signed type can represent all values of the unsigned type, it
4882 // wins. Because we are dealing with 2's complement and types that are
4883 // powers of two larger than each other, this is always safe.
4887 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
4888 if (!CFConstantStringTypeDecl) {
4889 assert(!CFConstantStringTagDecl &&
4890 "tag and typedef should be initialized together");
4891 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
4892 CFConstantStringTagDecl->startDefinition();
4894 QualType FieldTypes[4];
4895 const char *FieldNames[4];
4898 FieldTypes[0] = getPointerType(IntTy.withConst());
4899 FieldNames[0] = "isa";
4901 FieldTypes[1] = IntTy;
4902 FieldNames[1] = "flags";
4904 FieldTypes[2] = getPointerType(CharTy.withConst());
4905 FieldNames[2] = "str";
4907 FieldTypes[3] = LongTy;
4908 FieldNames[3] = "length";
4911 for (unsigned i = 0; i < 4; ++i) {
4912 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
4915 &Idents.get(FieldNames[i]),
4916 FieldTypes[i], /*TInfo=*/nullptr,
4917 /*BitWidth=*/nullptr,
4920 Field->setAccess(AS_public);
4921 CFConstantStringTagDecl->addDecl(Field);
4924 CFConstantStringTagDecl->completeDefinition();
4925 // This type is designed to be compatible with NSConstantString, but cannot
4926 // use the same name, since NSConstantString is an interface.
4927 auto tagType = getTagDeclType(CFConstantStringTagDecl);
4928 CFConstantStringTypeDecl =
4929 buildImplicitTypedef(tagType, "__NSConstantString");
4932 return CFConstantStringTypeDecl;
4935 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
4936 if (!CFConstantStringTagDecl)
4937 getCFConstantStringDecl(); // Build the tag and the typedef.
4938 return CFConstantStringTagDecl;
4941 // getCFConstantStringType - Return the type used for constant CFStrings.
4942 QualType ASTContext::getCFConstantStringType() const {
4943 return getTypedefType(getCFConstantStringDecl());
4946 QualType ASTContext::getObjCSuperType() const {
4947 if (ObjCSuperType.isNull()) {
4948 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
4949 TUDecl->addDecl(ObjCSuperTypeDecl);
4950 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4952 return ObjCSuperType;
4955 void ASTContext::setCFConstantStringType(QualType T) {
4956 const TypedefType *TD = T->getAs<TypedefType>();
4957 assert(TD && "Invalid CFConstantStringType");
4958 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
4960 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
4961 assert(TagType && "Invalid CFConstantStringType");
4962 CFConstantStringTagDecl = TagType->getDecl();
4965 QualType ASTContext::getBlockDescriptorType() const {
4966 if (BlockDescriptorType)
4967 return getTagDeclType(BlockDescriptorType);
4970 // FIXME: Needs the FlagAppleBlock bit.
4971 RD = buildImplicitRecord("__block_descriptor");
4972 RD->startDefinition();
4974 QualType FieldTypes[] = {
4979 static const char *const FieldNames[] = {
4984 for (size_t i = 0; i < 2; ++i) {
4985 FieldDecl *Field = FieldDecl::Create(
4986 *this, RD, SourceLocation(), SourceLocation(),
4987 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4988 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
4989 Field->setAccess(AS_public);
4993 RD->completeDefinition();
4995 BlockDescriptorType = RD;
4997 return getTagDeclType(BlockDescriptorType);
5000 QualType ASTContext::getBlockDescriptorExtendedType() const {
5001 if (BlockDescriptorExtendedType)
5002 return getTagDeclType(BlockDescriptorExtendedType);
5005 // FIXME: Needs the FlagAppleBlock bit.
5006 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5007 RD->startDefinition();
5009 QualType FieldTypes[] = {
5012 getPointerType(VoidPtrTy),
5013 getPointerType(VoidPtrTy)
5016 static const char *const FieldNames[] = {
5023 for (size_t i = 0; i < 4; ++i) {
5024 FieldDecl *Field = FieldDecl::Create(
5025 *this, RD, SourceLocation(), SourceLocation(),
5026 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5027 /*BitWidth=*/nullptr,
5028 /*Mutable=*/false, ICIS_NoInit);
5029 Field->setAccess(AS_public);
5033 RD->completeDefinition();
5035 BlockDescriptorExtendedType = RD;
5036 return getTagDeclType(BlockDescriptorExtendedType);
5039 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5040 /// requires copy/dispose. Note that this must match the logic
5041 /// in buildByrefHelpers.
5042 bool ASTContext::BlockRequiresCopying(QualType Ty,
5044 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5045 const Expr *copyExpr = getBlockVarCopyInits(D);
5046 if (!copyExpr && record->hasTrivialDestructor()) return false;
5051 if (!Ty->isObjCRetainableType()) return false;
5053 Qualifiers qs = Ty.getQualifiers();
5055 // If we have lifetime, that dominates.
5056 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
5058 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5060 // These are just bits as far as the runtime is concerned.
5061 case Qualifiers::OCL_ExplicitNone:
5062 case Qualifiers::OCL_Autoreleasing:
5065 // Tell the runtime that this is ARC __weak, called by the
5067 case Qualifiers::OCL_Weak:
5068 // ARC __strong __block variables need to be retained.
5069 case Qualifiers::OCL_Strong:
5072 llvm_unreachable("fell out of lifetime switch!");
5074 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5075 Ty->isObjCObjectPointerType());
5078 bool ASTContext::getByrefLifetime(QualType Ty,
5079 Qualifiers::ObjCLifetime &LifeTime,
5080 bool &HasByrefExtendedLayout) const {
5082 if (!getLangOpts().ObjC1 ||
5083 getLangOpts().getGC() != LangOptions::NonGC)
5086 HasByrefExtendedLayout = false;
5087 if (Ty->isRecordType()) {
5088 HasByrefExtendedLayout = true;
5089 LifeTime = Qualifiers::OCL_None;
5090 } else if ((LifeTime = Ty.getObjCLifetime())) {
5091 // Honor the ARC qualifiers.
5092 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5094 LifeTime = Qualifiers::OCL_ExplicitNone;
5096 LifeTime = Qualifiers::OCL_None;
5101 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5102 if (!ObjCInstanceTypeDecl)
5103 ObjCInstanceTypeDecl =
5104 buildImplicitTypedef(getObjCIdType(), "instancetype");
5105 return ObjCInstanceTypeDecl;
5108 // This returns true if a type has been typedefed to BOOL:
5109 // typedef <type> BOOL;
5110 static bool isTypeTypedefedAsBOOL(QualType T) {
5111 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
5112 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5113 return II->isStr("BOOL");
5118 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
5120 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
5121 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5122 return CharUnits::Zero();
5124 CharUnits sz = getTypeSizeInChars(type);
5126 // Make all integer and enum types at least as large as an int
5127 if (sz.isPositive() && type->isIntegralOrEnumerationType())
5128 sz = std::max(sz, getTypeSizeInChars(IntTy));
5129 // Treat arrays as pointers, since that's how they're passed in.
5130 else if (type->isArrayType())
5131 sz = getTypeSizeInChars(VoidPtrTy);
5135 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
5136 return getTargetInfo().getCXXABI().isMicrosoft() &&
5137 VD->isStaticDataMember() &&
5138 VD->getType()->isIntegralOrEnumerationType() &&
5139 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
5142 ASTContext::InlineVariableDefinitionKind
5143 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5144 if (!VD->isInline())
5145 return InlineVariableDefinitionKind::None;
5147 // In almost all cases, it's a weak definition.
5148 auto *First = VD->getFirstDecl();
5149 if (!First->isConstexpr() || First->isInlineSpecified() ||
5150 !VD->isStaticDataMember())
5151 return InlineVariableDefinitionKind::Weak;
5153 // If there's a file-context declaration in this translation unit, it's a
5154 // non-discardable definition.
5155 for (auto *D : VD->redecls())
5156 if (D->getLexicalDeclContext()->isFileContext())
5157 return InlineVariableDefinitionKind::Strong;
5159 // If we've not seen one yet, we don't know.
5160 return InlineVariableDefinitionKind::WeakUnknown;
5164 std::string charUnitsToString(const CharUnits &CU) {
5165 return llvm::itostr(CU.getQuantity());
5168 /// getObjCEncodingForBlock - Return the encoded type for this block
5170 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5173 const BlockDecl *Decl = Expr->getBlockDecl();
5175 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5176 // Encode result type.
5177 if (getLangOpts().EncodeExtendedBlockSig)
5178 getObjCEncodingForMethodParameter(
5179 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5182 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
5183 // Compute size of all parameters.
5184 // Start with computing size of a pointer in number of bytes.
5185 // FIXME: There might(should) be a better way of doing this computation!
5187 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5188 CharUnits ParmOffset = PtrSize;
5189 for (auto PI : Decl->parameters()) {
5190 QualType PType = PI->getType();
5191 CharUnits sz = getObjCEncodingTypeSize(PType);
5194 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
5197 // Size of the argument frame
5198 S += charUnitsToString(ParmOffset);
5199 // Block pointer and offset.
5203 ParmOffset = PtrSize;
5204 for (auto PVDecl : Decl->parameters()) {
5205 QualType PType = PVDecl->getOriginalType();
5206 if (const ArrayType *AT =
5207 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5208 // Use array's original type only if it has known number of
5210 if (!isa<ConstantArrayType>(AT))
5211 PType = PVDecl->getType();
5212 } else if (PType->isFunctionType())
5213 PType = PVDecl->getType();
5214 if (getLangOpts().EncodeExtendedBlockSig)
5215 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5216 S, true /*Extended*/);
5218 getObjCEncodingForType(PType, S);
5219 S += charUnitsToString(ParmOffset);
5220 ParmOffset += getObjCEncodingTypeSize(PType);
5226 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
5228 // Encode result type.
5229 getObjCEncodingForType(Decl->getReturnType(), S);
5230 CharUnits ParmOffset;
5231 // Compute size of all parameters.
5232 for (auto PI : Decl->parameters()) {
5233 QualType PType = PI->getType();
5234 CharUnits sz = getObjCEncodingTypeSize(PType);
5238 assert (sz.isPositive() &&
5239 "getObjCEncodingForFunctionDecl - Incomplete param type");
5242 S += charUnitsToString(ParmOffset);
5243 ParmOffset = CharUnits::Zero();
5246 for (auto PVDecl : Decl->parameters()) {
5247 QualType PType = PVDecl->getOriginalType();
5248 if (const ArrayType *AT =
5249 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5250 // Use array's original type only if it has known number of
5252 if (!isa<ConstantArrayType>(AT))
5253 PType = PVDecl->getType();
5254 } else if (PType->isFunctionType())
5255 PType = PVDecl->getType();
5256 getObjCEncodingForType(PType, S);
5257 S += charUnitsToString(ParmOffset);
5258 ParmOffset += getObjCEncodingTypeSize(PType);
5264 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
5265 /// method parameter or return type. If Extended, include class names and
5266 /// block object types.
5267 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5268 QualType T, std::string& S,
5269 bool Extended) const {
5270 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5271 getObjCEncodingForTypeQualifier(QT, S);
5272 // Encode parameter type.
5273 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5274 true /*OutermostType*/,
5275 false /*EncodingProperty*/,
5276 false /*StructField*/,
5277 Extended /*EncodeBlockParameters*/,
5278 Extended /*EncodeClassNames*/);
5281 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
5283 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5285 bool Extended) const {
5286 // FIXME: This is not very efficient.
5287 // Encode return type.
5288 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5289 Decl->getReturnType(), S, Extended);
5290 // Compute size of all parameters.
5291 // Start with computing size of a pointer in number of bytes.
5292 // FIXME: There might(should) be a better way of doing this computation!
5294 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5295 // The first two arguments (self and _cmd) are pointers; account for
5297 CharUnits ParmOffset = 2 * PtrSize;
5298 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5299 E = Decl->sel_param_end(); PI != E; ++PI) {
5300 QualType PType = (*PI)->getType();
5301 CharUnits sz = getObjCEncodingTypeSize(PType);
5305 assert (sz.isPositive() &&
5306 "getObjCEncodingForMethodDecl - Incomplete param type");
5309 S += charUnitsToString(ParmOffset);
5311 S += charUnitsToString(PtrSize);
5314 ParmOffset = 2 * PtrSize;
5315 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5316 E = Decl->sel_param_end(); PI != E; ++PI) {
5317 const ParmVarDecl *PVDecl = *PI;
5318 QualType PType = PVDecl->getOriginalType();
5319 if (const ArrayType *AT =
5320 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5321 // Use array's original type only if it has known number of
5323 if (!isa<ConstantArrayType>(AT))
5324 PType = PVDecl->getType();
5325 } else if (PType->isFunctionType())
5326 PType = PVDecl->getType();
5327 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5328 PType, S, Extended);
5329 S += charUnitsToString(ParmOffset);
5330 ParmOffset += getObjCEncodingTypeSize(PType);
5336 ObjCPropertyImplDecl *
5337 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5338 const ObjCPropertyDecl *PD,
5339 const Decl *Container) const {
5342 if (const ObjCCategoryImplDecl *CID =
5343 dyn_cast<ObjCCategoryImplDecl>(Container)) {
5344 for (auto *PID : CID->property_impls())
5345 if (PID->getPropertyDecl() == PD)
5348 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5349 for (auto *PID : OID->property_impls())
5350 if (PID->getPropertyDecl() == PD)
5356 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
5357 /// property declaration. If non-NULL, Container must be either an
5358 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5359 /// NULL when getting encodings for protocol properties.
5360 /// Property attributes are stored as a comma-delimited C string. The simple
5361 /// attributes readonly and bycopy are encoded as single characters. The
5362 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
5363 /// encoded as single characters, followed by an identifier. Property types
5364 /// are also encoded as a parametrized attribute. The characters used to encode
5365 /// these attributes are defined by the following enumeration:
5367 /// enum PropertyAttributes {
5368 /// kPropertyReadOnly = 'R', // property is read-only.
5369 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5370 /// kPropertyByref = '&', // property is a reference to the value last assigned
5371 /// kPropertyDynamic = 'D', // property is dynamic
5372 /// kPropertyGetter = 'G', // followed by getter selector name
5373 /// kPropertySetter = 'S', // followed by setter selector name
5374 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
5375 /// kPropertyType = 'T' // followed by old-style type encoding.
5376 /// kPropertyWeak = 'W' // 'weak' property
5377 /// kPropertyStrong = 'P' // property GC'able
5378 /// kPropertyNonAtomic = 'N' // property non-atomic
5381 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5382 const Decl *Container,
5383 std::string& S) const {
5384 // Collect information from the property implementation decl(s).
5385 bool Dynamic = false;
5386 ObjCPropertyImplDecl *SynthesizePID = nullptr;
5388 if (ObjCPropertyImplDecl *PropertyImpDecl =
5389 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5390 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5393 SynthesizePID = PropertyImpDecl;
5396 // FIXME: This is not very efficient.
5399 // Encode result type.
5400 // GCC has some special rules regarding encoding of properties which
5401 // closely resembles encoding of ivars.
5402 getObjCEncodingForPropertyType(PD->getType(), S);
5404 if (PD->isReadOnly()) {
5406 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5408 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5410 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5413 switch (PD->getSetterKind()) {
5414 case ObjCPropertyDecl::Assign: break;
5415 case ObjCPropertyDecl::Copy: S += ",C"; break;
5416 case ObjCPropertyDecl::Retain: S += ",&"; break;
5417 case ObjCPropertyDecl::Weak: S += ",W"; break;
5421 // It really isn't clear at all what this means, since properties
5422 // are "dynamic by default".
5426 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5429 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5431 S += PD->getGetterName().getAsString();
5434 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5436 S += PD->getSetterName().getAsString();
5439 if (SynthesizePID) {
5440 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5442 S += OID->getNameAsString();
5445 // FIXME: OBJCGC: weak & strong
5448 /// getLegacyIntegralTypeEncoding -
5449 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5450 /// 'l' or 'L' , but not always. For typedefs, we need to use
5451 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5453 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5454 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5455 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5456 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5457 PointeeTy = UnsignedIntTy;
5459 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5465 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5466 const FieldDecl *Field,
5467 QualType *NotEncodedT) const {
5468 // We follow the behavior of gcc, expanding structures which are
5469 // directly pointed to, and expanding embedded structures. Note that
5470 // these rules are sufficient to prevent recursive encoding of the
5472 getObjCEncodingForTypeImpl(T, S, true, true, Field,
5473 true /* outermost type */, false, false,
5474 false, false, false, NotEncodedT);
5477 void ASTContext::getObjCEncodingForPropertyType(QualType T,
5478 std::string& S) const {
5479 // Encode result type.
5480 // GCC has some special rules regarding encoding of properties which
5481 // closely resembles encoding of ivars.
5482 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5483 true /* outermost type */,
5484 true /* encoding property */);
5487 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5488 BuiltinType::Kind kind) {
5490 case BuiltinType::Void: return 'v';
5491 case BuiltinType::Bool: return 'B';
5492 case BuiltinType::Char_U:
5493 case BuiltinType::UChar: return 'C';
5494 case BuiltinType::Char16:
5495 case BuiltinType::UShort: return 'S';
5496 case BuiltinType::Char32:
5497 case BuiltinType::UInt: return 'I';
5498 case BuiltinType::ULong:
5499 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5500 case BuiltinType::UInt128: return 'T';
5501 case BuiltinType::ULongLong: return 'Q';
5502 case BuiltinType::Char_S:
5503 case BuiltinType::SChar: return 'c';
5504 case BuiltinType::Short: return 's';
5505 case BuiltinType::WChar_S:
5506 case BuiltinType::WChar_U:
5507 case BuiltinType::Int: return 'i';
5508 case BuiltinType::Long:
5509 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5510 case BuiltinType::LongLong: return 'q';
5511 case BuiltinType::Int128: return 't';
5512 case BuiltinType::Float: return 'f';
5513 case BuiltinType::Double: return 'd';
5514 case BuiltinType::LongDouble: return 'D';
5515 case BuiltinType::NullPtr: return '*'; // like char*
5517 case BuiltinType::Float128:
5518 case BuiltinType::Half:
5519 // FIXME: potentially need @encodes for these!
5522 case BuiltinType::ObjCId:
5523 case BuiltinType::ObjCClass:
5524 case BuiltinType::ObjCSel:
5525 llvm_unreachable("@encoding ObjC primitive type");
5527 // OpenCL and placeholder types don't need @encodings.
5528 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5529 case BuiltinType::Id:
5530 #include "clang/Basic/OpenCLImageTypes.def"
5531 case BuiltinType::OCLEvent:
5532 case BuiltinType::OCLClkEvent:
5533 case BuiltinType::OCLQueue:
5534 case BuiltinType::OCLNDRange:
5535 case BuiltinType::OCLReserveID:
5536 case BuiltinType::OCLSampler:
5537 case BuiltinType::Dependent:
5538 #define BUILTIN_TYPE(KIND, ID)
5539 #define PLACEHOLDER_TYPE(KIND, ID) \
5540 case BuiltinType::KIND:
5541 #include "clang/AST/BuiltinTypes.def"
5542 llvm_unreachable("invalid builtin type for @encode");
5544 llvm_unreachable("invalid BuiltinType::Kind value");
5547 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5548 EnumDecl *Enum = ET->getDecl();
5550 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5551 if (!Enum->isFixed())
5554 // The encoding of a fixed enum type matches its fixed underlying type.
5555 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5556 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5559 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5560 QualType T, const FieldDecl *FD) {
5561 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5563 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5564 // The GNU runtime requires more information; bitfields are encoded as b,
5565 // then the offset (in bits) of the first element, then the type of the
5566 // bitfield, then the size in bits. For example, in this structure:
5573 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5574 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5575 // information is not especially sensible, but we're stuck with it for
5576 // compatibility with GCC, although providing it breaks anything that
5577 // actually uses runtime introspection and wants to work on both runtimes...
5578 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5579 const RecordDecl *RD = FD->getParent();
5580 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5581 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5582 if (const EnumType *ET = T->getAs<EnumType>())
5583 S += ObjCEncodingForEnumType(Ctx, ET);
5585 const BuiltinType *BT = T->castAs<BuiltinType>();
5586 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5589 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5592 // FIXME: Use SmallString for accumulating string.
5593 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5594 bool ExpandPointedToStructures,
5595 bool ExpandStructures,
5596 const FieldDecl *FD,
5598 bool EncodingProperty,
5600 bool EncodeBlockParameters,
5601 bool EncodeClassNames,
5602 bool EncodePointerToObjCTypedef,
5603 QualType *NotEncodedT) const {
5604 CanQualType CT = getCanonicalType(T);
5605 switch (CT->getTypeClass()) {
5608 if (FD && FD->isBitField())
5609 return EncodeBitField(this, S, T, FD);
5610 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5611 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5613 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5616 case Type::Complex: {
5617 const ComplexType *CT = T->castAs<ComplexType>();
5619 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
5623 case Type::Atomic: {
5624 const AtomicType *AT = T->castAs<AtomicType>();
5626 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
5630 // encoding for pointer or reference types.
5632 case Type::LValueReference:
5633 case Type::RValueReference: {
5635 if (isa<PointerType>(CT)) {
5636 const PointerType *PT = T->castAs<PointerType>();
5637 if (PT->isObjCSelType()) {
5641 PointeeTy = PT->getPointeeType();
5643 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5646 bool isReadOnly = false;
5647 // For historical/compatibility reasons, the read-only qualifier of the
5648 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5649 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5650 // Also, do not emit the 'r' for anything but the outermost type!
5651 if (isa<TypedefType>(T.getTypePtr())) {
5652 if (OutermostType && T.isConstQualified()) {
5656 } else if (OutermostType) {
5657 QualType P = PointeeTy;
5658 while (P->getAs<PointerType>())
5659 P = P->getAs<PointerType>()->getPointeeType();
5660 if (P.isConstQualified()) {
5666 // Another legacy compatibility encoding. Some ObjC qualifier and type
5667 // combinations need to be rearranged.
5668 // Rewrite "in const" from "nr" to "rn"
5669 if (StringRef(S).endswith("nr"))
5670 S.replace(S.end()-2, S.end(), "rn");
5673 if (PointeeTy->isCharType()) {
5674 // char pointer types should be encoded as '*' unless it is a
5675 // type that has been typedef'd to 'BOOL'.
5676 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5680 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5681 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5682 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5686 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5687 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5694 getLegacyIntegralTypeEncoding(PointeeTy);
5696 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5697 nullptr, false, false, false, false, false, false,
5702 case Type::ConstantArray:
5703 case Type::IncompleteArray:
5704 case Type::VariableArray: {
5705 const ArrayType *AT = cast<ArrayType>(CT);
5707 if (isa<IncompleteArrayType>(AT) && !StructField) {
5708 // Incomplete arrays are encoded as a pointer to the array element.
5711 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5712 false, ExpandStructures, FD);
5716 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5717 S += llvm::utostr(CAT->getSize().getZExtValue());
5719 //Variable length arrays are encoded as a regular array with 0 elements.
5720 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5721 "Unknown array type!");
5725 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5726 false, ExpandStructures, FD,
5727 false, false, false, false, false, false,
5734 case Type::FunctionNoProto:
5735 case Type::FunctionProto:
5739 case Type::Record: {
5740 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5741 S += RDecl->isUnion() ? '(' : '{';
5742 // Anonymous structures print as '?'
5743 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5745 if (ClassTemplateSpecializationDecl *Spec
5746 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5747 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5748 llvm::raw_string_ostream OS(S);
5749 TemplateSpecializationType::PrintTemplateArgumentList(OS,
5750 TemplateArgs.asArray(),
5751 (*this).getPrintingPolicy());
5756 if (ExpandStructures) {
5758 if (!RDecl->isUnion()) {
5759 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
5761 for (const auto *Field : RDecl->fields()) {
5764 S += Field->getNameAsString();
5768 // Special case bit-fields.
5769 if (Field->isBitField()) {
5770 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5773 QualType qt = Field->getType();
5774 getLegacyIntegralTypeEncoding(qt);
5775 getObjCEncodingForTypeImpl(qt, S, false, true,
5776 FD, /*OutermostType*/false,
5777 /*EncodingProperty*/false,
5778 /*StructField*/true,
5779 false, false, false, NotEncodedT);
5784 S += RDecl->isUnion() ? ')' : '}';
5788 case Type::BlockPointer: {
5789 const BlockPointerType *BT = T->castAs<BlockPointerType>();
5790 S += "@?"; // Unlike a pointer-to-function, which is "^?".
5791 if (EncodeBlockParameters) {
5792 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5795 // Block return type
5796 getObjCEncodingForTypeImpl(
5797 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5798 FD, false /* OutermostType */, EncodingProperty,
5799 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5804 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5805 for (const auto &I : FPT->param_types())
5806 getObjCEncodingForTypeImpl(
5807 I, S, ExpandPointedToStructures, ExpandStructures, FD,
5808 false /* OutermostType */, EncodingProperty,
5809 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5810 false, NotEncodedT);
5817 case Type::ObjCObject: {
5818 // hack to match legacy encoding of *id and *Class
5819 QualType Ty = getObjCObjectPointerType(CT);
5820 if (Ty->isObjCIdType()) {
5821 S += "{objc_object=}";
5824 else if (Ty->isObjCClassType()) {
5825 S += "{objc_class=}";
5830 case Type::ObjCInterface: {
5831 // Ignore protocol qualifiers when mangling at this level.
5832 // @encode(class_name)
5833 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
5835 S += OI->getObjCRuntimeNameAsString();
5837 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5838 DeepCollectObjCIvars(OI, true, Ivars);
5839 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5840 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5841 if (Field->isBitField())
5842 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5844 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5845 false, false, false, false, false,
5846 EncodePointerToObjCTypedef,
5853 case Type::ObjCObjectPointer: {
5854 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5855 if (OPT->isObjCIdType()) {
5860 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5861 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5862 // Since this is a binary compatibility issue, need to consult with runtime
5863 // folks. Fortunately, this is a *very* obsure construct.
5868 if (OPT->isObjCQualifiedIdType()) {
5869 getObjCEncodingForTypeImpl(getObjCIdType(), S,
5870 ExpandPointedToStructures,
5871 ExpandStructures, FD);
5872 if (FD || EncodingProperty || EncodeClassNames) {
5873 // Note that we do extended encoding of protocol qualifer list
5874 // Only when doing ivar or property encoding.
5876 for (const auto *I : OPT->quals()) {
5878 S += I->getObjCRuntimeNameAsString();
5886 QualType PointeeTy = OPT->getPointeeType();
5887 if (!EncodingProperty &&
5888 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5889 !EncodePointerToObjCTypedef) {
5890 // Another historical/compatibility reason.
5891 // We encode the underlying type which comes out as
5894 if (FD && OPT->getInterfaceDecl()) {
5895 // Prevent recursive encoding of fields in some rare cases.
5896 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5897 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5898 DeepCollectObjCIvars(OI, true, Ivars);
5899 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5900 if (cast<FieldDecl>(Ivars[i]) == FD) {
5902 S += OI->getObjCRuntimeNameAsString();
5908 getObjCEncodingForTypeImpl(PointeeTy, S,
5909 false, ExpandPointedToStructures,
5911 false, false, false, false, false,
5912 /*EncodePointerToObjCTypedef*/true);
5917 if (OPT->getInterfaceDecl() &&
5918 (FD || EncodingProperty || EncodeClassNames)) {
5920 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
5921 for (const auto *I : OPT->quals()) {
5923 S += I->getObjCRuntimeNameAsString();
5931 // gcc just blithely ignores member pointers.
5932 // FIXME: we shoul do better than that. 'M' is available.
5933 case Type::MemberPointer:
5934 // This matches gcc's encoding, even though technically it is insufficient.
5935 //FIXME. We should do a better job than gcc.
5937 case Type::ExtVector:
5938 // Until we have a coherent encoding of these three types, issue warning.
5944 // We could see an undeduced auto type here during error recovery.
5950 #define ABSTRACT_TYPE(KIND, BASE)
5951 #define TYPE(KIND, BASE)
5952 #define DEPENDENT_TYPE(KIND, BASE) \
5954 #define NON_CANONICAL_TYPE(KIND, BASE) \
5956 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5958 #include "clang/AST/TypeNodes.def"
5959 llvm_unreachable("@encode for dependent type!");
5961 llvm_unreachable("bad type kind!");
5964 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5966 const FieldDecl *FD,
5968 QualType *NotEncodedT) const {
5969 assert(RDecl && "Expected non-null RecordDecl");
5970 assert(!RDecl->isUnion() && "Should not be called for unions");
5971 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
5974 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5975 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5976 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5979 for (const auto &BI : CXXRec->bases()) {
5980 if (!BI.isVirtual()) {
5981 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5982 if (base->isEmpty())
5984 uint64_t offs = toBits(layout.getBaseClassOffset(base));
5985 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5986 std::make_pair(offs, base));
5992 for (auto *Field : RDecl->fields()) {
5993 uint64_t offs = layout.getFieldOffset(i);
5994 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5995 std::make_pair(offs, Field));
5999 if (CXXRec && includeVBases) {
6000 for (const auto &BI : CXXRec->vbases()) {
6001 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
6002 if (base->isEmpty())
6004 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
6005 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6006 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
6007 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6008 std::make_pair(offs, base));
6014 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6016 size = layout.getSize();
6020 uint64_t CurOffs = 0;
6022 std::multimap<uint64_t, NamedDecl *>::iterator
6023 CurLayObj = FieldOrBaseOffsets.begin();
6025 if (CXXRec && CXXRec->isDynamicClass() &&
6026 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
6029 std::string recname = CXXRec->getNameAsString();
6030 if (recname.empty()) recname = "?";
6036 CurOffs += getTypeSize(VoidPtrTy);
6040 if (!RDecl->hasFlexibleArrayMember()) {
6041 // Mark the end of the structure.
6042 uint64_t offs = toBits(size);
6043 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6044 std::make_pair(offs, nullptr));
6047 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
6049 assert(CurOffs <= CurLayObj->first);
6050 if (CurOffs < CurLayObj->first) {
6051 uint64_t padding = CurLayObj->first - CurOffs;
6052 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6053 // packing/alignment of members is different that normal, in which case
6054 // the encoding will be out-of-sync with the real layout.
6055 // If the runtime switches to just consider the size of types without
6056 // taking into account alignment, we could make padding explicit in the
6057 // encoding (e.g. using arrays of chars). The encoding strings would be
6058 // longer then though.
6063 NamedDecl *dcl = CurLayObj->second;
6065 break; // reached end of structure.
6067 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6068 // We expand the bases without their virtual bases since those are going
6069 // in the initial structure. Note that this differs from gcc which
6070 // expands virtual bases each time one is encountered in the hierarchy,
6071 // making the encoding type bigger than it really is.
6072 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6074 assert(!base->isEmpty());
6076 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
6079 FieldDecl *field = cast<FieldDecl>(dcl);
6082 S += field->getNameAsString();
6086 if (field->isBitField()) {
6087 EncodeBitField(this, S, field->getType(), field);
6089 CurOffs += field->getBitWidthValue(*this);
6092 QualType qt = field->getType();
6093 getLegacyIntegralTypeEncoding(qt);
6094 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6095 /*OutermostType*/false,
6096 /*EncodingProperty*/false,
6097 /*StructField*/true,
6098 false, false, false, NotEncodedT);
6100 CurOffs += getTypeSize(field->getType());
6107 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
6108 std::string& S) const {
6109 if (QT & Decl::OBJC_TQ_In)
6111 if (QT & Decl::OBJC_TQ_Inout)
6113 if (QT & Decl::OBJC_TQ_Out)
6115 if (QT & Decl::OBJC_TQ_Bycopy)
6117 if (QT & Decl::OBJC_TQ_Byref)
6119 if (QT & Decl::OBJC_TQ_Oneway)
6123 TypedefDecl *ASTContext::getObjCIdDecl() const {
6125 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
6126 T = getObjCObjectPointerType(T);
6127 ObjCIdDecl = buildImplicitTypedef(T, "id");
6132 TypedefDecl *ASTContext::getObjCSelDecl() const {
6134 QualType T = getPointerType(ObjCBuiltinSelTy);
6135 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
6140 TypedefDecl *ASTContext::getObjCClassDecl() const {
6141 if (!ObjCClassDecl) {
6142 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
6143 T = getObjCObjectPointerType(T);
6144 ObjCClassDecl = buildImplicitTypedef(T, "Class");
6146 return ObjCClassDecl;
6149 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6150 if (!ObjCProtocolClassDecl) {
6151 ObjCProtocolClassDecl
6152 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6154 &Idents.get("Protocol"),
6155 /*typeParamList=*/nullptr,
6156 /*PrevDecl=*/nullptr,
6157 SourceLocation(), true);
6160 return ObjCProtocolClassDecl;
6163 //===----------------------------------------------------------------------===//
6164 // __builtin_va_list Construction Functions
6165 //===----------------------------------------------------------------------===//
6167 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6169 // typedef char* __builtin[_ms]_va_list;
6170 QualType T = Context->getPointerType(Context->CharTy);
6171 return Context->buildImplicitTypedef(T, Name);
6174 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6175 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6178 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6179 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
6182 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6183 // typedef void* __builtin_va_list;
6184 QualType T = Context->getPointerType(Context->VoidTy);
6185 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6188 static TypedefDecl *
6189 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
6191 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
6192 if (Context->getLangOpts().CPlusPlus) {
6193 // namespace std { struct __va_list {
6195 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6196 Context->getTranslationUnitDecl(),
6197 /*Inline*/ false, SourceLocation(),
6198 SourceLocation(), &Context->Idents.get("std"),
6199 /*PrevDecl*/ nullptr);
6201 VaListTagDecl->setDeclContext(NS);
6204 VaListTagDecl->startDefinition();
6206 const size_t NumFields = 5;
6207 QualType FieldTypes[NumFields];
6208 const char *FieldNames[NumFields];
6211 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6212 FieldNames[0] = "__stack";
6215 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6216 FieldNames[1] = "__gr_top";
6219 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6220 FieldNames[2] = "__vr_top";
6223 FieldTypes[3] = Context->IntTy;
6224 FieldNames[3] = "__gr_offs";
6227 FieldTypes[4] = Context->IntTy;
6228 FieldNames[4] = "__vr_offs";
6231 for (unsigned i = 0; i < NumFields; ++i) {
6232 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6236 &Context->Idents.get(FieldNames[i]),
6237 FieldTypes[i], /*TInfo=*/nullptr,
6238 /*BitWidth=*/nullptr,
6241 Field->setAccess(AS_public);
6242 VaListTagDecl->addDecl(Field);
6244 VaListTagDecl->completeDefinition();
6245 Context->VaListTagDecl = VaListTagDecl;
6246 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6248 // } __builtin_va_list;
6249 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
6252 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6253 // typedef struct __va_list_tag {
6254 RecordDecl *VaListTagDecl;
6256 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6257 VaListTagDecl->startDefinition();
6259 const size_t NumFields = 5;
6260 QualType FieldTypes[NumFields];
6261 const char *FieldNames[NumFields];
6263 // unsigned char gpr;
6264 FieldTypes[0] = Context->UnsignedCharTy;
6265 FieldNames[0] = "gpr";
6267 // unsigned char fpr;
6268 FieldTypes[1] = Context->UnsignedCharTy;
6269 FieldNames[1] = "fpr";
6271 // unsigned short reserved;
6272 FieldTypes[2] = Context->UnsignedShortTy;
6273 FieldNames[2] = "reserved";
6275 // void* overflow_arg_area;
6276 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6277 FieldNames[3] = "overflow_arg_area";
6279 // void* reg_save_area;
6280 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6281 FieldNames[4] = "reg_save_area";
6284 for (unsigned i = 0; i < NumFields; ++i) {
6285 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6288 &Context->Idents.get(FieldNames[i]),
6289 FieldTypes[i], /*TInfo=*/nullptr,
6290 /*BitWidth=*/nullptr,
6293 Field->setAccess(AS_public);
6294 VaListTagDecl->addDecl(Field);
6296 VaListTagDecl->completeDefinition();
6297 Context->VaListTagDecl = VaListTagDecl;
6298 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6301 TypedefDecl *VaListTagTypedefDecl =
6302 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6304 QualType VaListTagTypedefType =
6305 Context->getTypedefType(VaListTagTypedefDecl);
6307 // typedef __va_list_tag __builtin_va_list[1];
6308 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6309 QualType VaListTagArrayType
6310 = Context->getConstantArrayType(VaListTagTypedefType,
6311 Size, ArrayType::Normal, 0);
6312 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6315 static TypedefDecl *
6316 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6317 // struct __va_list_tag {
6318 RecordDecl *VaListTagDecl;
6319 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6320 VaListTagDecl->startDefinition();
6322 const size_t NumFields = 4;
6323 QualType FieldTypes[NumFields];
6324 const char *FieldNames[NumFields];
6326 // unsigned gp_offset;
6327 FieldTypes[0] = Context->UnsignedIntTy;
6328 FieldNames[0] = "gp_offset";
6330 // unsigned fp_offset;
6331 FieldTypes[1] = Context->UnsignedIntTy;
6332 FieldNames[1] = "fp_offset";
6334 // void* overflow_arg_area;
6335 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6336 FieldNames[2] = "overflow_arg_area";
6338 // void* reg_save_area;
6339 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6340 FieldNames[3] = "reg_save_area";
6343 for (unsigned i = 0; i < NumFields; ++i) {
6344 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6348 &Context->Idents.get(FieldNames[i]),
6349 FieldTypes[i], /*TInfo=*/nullptr,
6350 /*BitWidth=*/nullptr,
6353 Field->setAccess(AS_public);
6354 VaListTagDecl->addDecl(Field);
6356 VaListTagDecl->completeDefinition();
6357 Context->VaListTagDecl = VaListTagDecl;
6358 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6362 // typedef struct __va_list_tag __builtin_va_list[1];
6363 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6364 QualType VaListTagArrayType =
6365 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6366 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6369 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6370 // typedef int __builtin_va_list[4];
6371 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6372 QualType IntArrayType
6373 = Context->getConstantArrayType(Context->IntTy,
6374 Size, ArrayType::Normal, 0);
6375 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6378 static TypedefDecl *
6379 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6381 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6382 if (Context->getLangOpts().CPlusPlus) {
6383 // namespace std { struct __va_list {
6385 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6386 Context->getTranslationUnitDecl(),
6387 /*Inline*/false, SourceLocation(),
6388 SourceLocation(), &Context->Idents.get("std"),
6389 /*PrevDecl*/ nullptr);
6391 VaListDecl->setDeclContext(NS);
6394 VaListDecl->startDefinition();
6397 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6401 &Context->Idents.get("__ap"),
6402 Context->getPointerType(Context->VoidTy),
6404 /*BitWidth=*/nullptr,
6407 Field->setAccess(AS_public);
6408 VaListDecl->addDecl(Field);
6411 VaListDecl->completeDefinition();
6412 Context->VaListTagDecl = VaListDecl;
6414 // typedef struct __va_list __builtin_va_list;
6415 QualType T = Context->getRecordType(VaListDecl);
6416 return Context->buildImplicitTypedef(T, "__builtin_va_list");
6419 static TypedefDecl *
6420 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6421 // struct __va_list_tag {
6422 RecordDecl *VaListTagDecl;
6423 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6424 VaListTagDecl->startDefinition();
6426 const size_t NumFields = 4;
6427 QualType FieldTypes[NumFields];
6428 const char *FieldNames[NumFields];
6431 FieldTypes[0] = Context->LongTy;
6432 FieldNames[0] = "__gpr";
6435 FieldTypes[1] = Context->LongTy;
6436 FieldNames[1] = "__fpr";
6438 // void *__overflow_arg_area;
6439 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6440 FieldNames[2] = "__overflow_arg_area";
6442 // void *__reg_save_area;
6443 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6444 FieldNames[3] = "__reg_save_area";
6447 for (unsigned i = 0; i < NumFields; ++i) {
6448 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6452 &Context->Idents.get(FieldNames[i]),
6453 FieldTypes[i], /*TInfo=*/nullptr,
6454 /*BitWidth=*/nullptr,
6457 Field->setAccess(AS_public);
6458 VaListTagDecl->addDecl(Field);
6460 VaListTagDecl->completeDefinition();
6461 Context->VaListTagDecl = VaListTagDecl;
6462 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6466 // typedef __va_list_tag __builtin_va_list[1];
6467 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6468 QualType VaListTagArrayType =
6469 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6471 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6474 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6475 TargetInfo::BuiltinVaListKind Kind) {
6477 case TargetInfo::CharPtrBuiltinVaList:
6478 return CreateCharPtrBuiltinVaListDecl(Context);
6479 case TargetInfo::VoidPtrBuiltinVaList:
6480 return CreateVoidPtrBuiltinVaListDecl(Context);
6481 case TargetInfo::AArch64ABIBuiltinVaList:
6482 return CreateAArch64ABIBuiltinVaListDecl(Context);
6483 case TargetInfo::PowerABIBuiltinVaList:
6484 return CreatePowerABIBuiltinVaListDecl(Context);
6485 case TargetInfo::X86_64ABIBuiltinVaList:
6486 return CreateX86_64ABIBuiltinVaListDecl(Context);
6487 case TargetInfo::PNaClABIBuiltinVaList:
6488 return CreatePNaClABIBuiltinVaListDecl(Context);
6489 case TargetInfo::AAPCSABIBuiltinVaList:
6490 return CreateAAPCSABIBuiltinVaListDecl(Context);
6491 case TargetInfo::SystemZBuiltinVaList:
6492 return CreateSystemZBuiltinVaListDecl(Context);
6495 llvm_unreachable("Unhandled __builtin_va_list type kind");
6498 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6499 if (!BuiltinVaListDecl) {
6500 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6501 assert(BuiltinVaListDecl->isImplicit());
6504 return BuiltinVaListDecl;
6507 Decl *ASTContext::getVaListTagDecl() const {
6508 // Force the creation of VaListTagDecl by building the __builtin_va_list
6511 (void)getBuiltinVaListDecl();
6513 return VaListTagDecl;
6516 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6517 if (!BuiltinMSVaListDecl)
6518 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6520 return BuiltinMSVaListDecl;
6523 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6524 assert(ObjCConstantStringType.isNull() &&
6525 "'NSConstantString' type already set!");
6527 ObjCConstantStringType = getObjCInterfaceType(Decl);
6530 /// \brief Retrieve the template name that corresponds to a non-empty
6533 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6534 UnresolvedSetIterator End) const {
6535 unsigned size = End - Begin;
6536 assert(size > 1 && "set is not overloaded!");
6538 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6539 size * sizeof(FunctionTemplateDecl*));
6540 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6542 NamedDecl **Storage = OT->getStorage();
6543 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6545 assert(isa<FunctionTemplateDecl>(D) ||
6546 (isa<UsingShadowDecl>(D) &&
6547 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6551 return TemplateName(OT);
6554 /// \brief Retrieve the template name that represents a qualified
6555 /// template name such as \c std::vector.
6557 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6558 bool TemplateKeyword,
6559 TemplateDecl *Template) const {
6560 assert(NNS && "Missing nested-name-specifier in qualified template name");
6562 // FIXME: Canonicalization?
6563 llvm::FoldingSetNodeID ID;
6564 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6566 void *InsertPos = nullptr;
6567 QualifiedTemplateName *QTN =
6568 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6570 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6571 QualifiedTemplateName(NNS, TemplateKeyword, Template);
6572 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6575 return TemplateName(QTN);
6578 /// \brief Retrieve the template name that represents a dependent
6579 /// template name such as \c MetaFun::template apply.
6581 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6582 const IdentifierInfo *Name) const {
6583 assert((!NNS || NNS->isDependent()) &&
6584 "Nested name specifier must be dependent");
6586 llvm::FoldingSetNodeID ID;
6587 DependentTemplateName::Profile(ID, NNS, Name);
6589 void *InsertPos = nullptr;
6590 DependentTemplateName *QTN =
6591 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6594 return TemplateName(QTN);
6596 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6597 if (CanonNNS == NNS) {
6598 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6599 DependentTemplateName(NNS, Name);
6601 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6602 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6603 DependentTemplateName(NNS, Name, Canon);
6604 DependentTemplateName *CheckQTN =
6605 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6606 assert(!CheckQTN && "Dependent type name canonicalization broken");
6610 DependentTemplateNames.InsertNode(QTN, InsertPos);
6611 return TemplateName(QTN);
6614 /// \brief Retrieve the template name that represents a dependent
6615 /// template name such as \c MetaFun::template operator+.
6617 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6618 OverloadedOperatorKind Operator) const {
6619 assert((!NNS || NNS->isDependent()) &&
6620 "Nested name specifier must be dependent");
6622 llvm::FoldingSetNodeID ID;
6623 DependentTemplateName::Profile(ID, NNS, Operator);
6625 void *InsertPos = nullptr;
6626 DependentTemplateName *QTN
6627 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6630 return TemplateName(QTN);
6632 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6633 if (CanonNNS == NNS) {
6634 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6635 DependentTemplateName(NNS, Operator);
6637 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6638 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6639 DependentTemplateName(NNS, Operator, Canon);
6641 DependentTemplateName *CheckQTN
6642 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6643 assert(!CheckQTN && "Dependent template name canonicalization broken");
6647 DependentTemplateNames.InsertNode(QTN, InsertPos);
6648 return TemplateName(QTN);
6652 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6653 TemplateName replacement) const {
6654 llvm::FoldingSetNodeID ID;
6655 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6657 void *insertPos = nullptr;
6658 SubstTemplateTemplateParmStorage *subst
6659 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6662 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6663 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6666 return TemplateName(subst);
6670 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6671 const TemplateArgument &ArgPack) const {
6672 ASTContext &Self = const_cast<ASTContext &>(*this);
6673 llvm::FoldingSetNodeID ID;
6674 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6676 void *InsertPos = nullptr;
6677 SubstTemplateTemplateParmPackStorage *Subst
6678 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6681 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6682 ArgPack.pack_size(),
6683 ArgPack.pack_begin());
6684 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6687 return TemplateName(Subst);
6690 /// getFromTargetType - Given one of the integer types provided by
6691 /// TargetInfo, produce the corresponding type. The unsigned @p Type
6692 /// is actually a value of type @c TargetInfo::IntType.
6693 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6695 case TargetInfo::NoInt: return CanQualType();
6696 case TargetInfo::SignedChar: return SignedCharTy;
6697 case TargetInfo::UnsignedChar: return UnsignedCharTy;
6698 case TargetInfo::SignedShort: return ShortTy;
6699 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6700 case TargetInfo::SignedInt: return IntTy;
6701 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6702 case TargetInfo::SignedLong: return LongTy;
6703 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6704 case TargetInfo::SignedLongLong: return LongLongTy;
6705 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6708 llvm_unreachable("Unhandled TargetInfo::IntType value");
6711 //===----------------------------------------------------------------------===//
6713 //===----------------------------------------------------------------------===//
6715 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6716 /// garbage collection attribute.
6718 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6719 if (getLangOpts().getGC() == LangOptions::NonGC)
6720 return Qualifiers::GCNone;
6722 assert(getLangOpts().ObjC1);
6723 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6725 // Default behaviour under objective-C's gc is for ObjC pointers
6726 // (or pointers to them) be treated as though they were declared
6728 if (GCAttrs == Qualifiers::GCNone) {
6729 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6730 return Qualifiers::Strong;
6731 else if (Ty->isPointerType())
6732 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6734 // It's not valid to set GC attributes on anything that isn't a
6737 QualType CT = Ty->getCanonicalTypeInternal();
6738 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6739 CT = AT->getElementType();
6740 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6746 //===----------------------------------------------------------------------===//
6747 // Type Compatibility Testing
6748 //===----------------------------------------------------------------------===//
6750 /// areCompatVectorTypes - Return true if the two specified vector types are
6752 static bool areCompatVectorTypes(const VectorType *LHS,
6753 const VectorType *RHS) {
6754 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6755 return LHS->getElementType() == RHS->getElementType() &&
6756 LHS->getNumElements() == RHS->getNumElements();
6759 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6760 QualType SecondVec) {
6761 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6762 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6764 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6767 // Treat Neon vector types and most AltiVec vector types as if they are the
6768 // equivalent GCC vector types.
6769 const VectorType *First = FirstVec->getAs<VectorType>();
6770 const VectorType *Second = SecondVec->getAs<VectorType>();
6771 if (First->getNumElements() == Second->getNumElements() &&
6772 hasSameType(First->getElementType(), Second->getElementType()) &&
6773 First->getVectorKind() != VectorType::AltiVecPixel &&
6774 First->getVectorKind() != VectorType::AltiVecBool &&
6775 Second->getVectorKind() != VectorType::AltiVecPixel &&
6776 Second->getVectorKind() != VectorType::AltiVecBool)
6782 //===----------------------------------------------------------------------===//
6783 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6784 //===----------------------------------------------------------------------===//
6786 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6787 /// inheritance hierarchy of 'rProto'.
6789 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6790 ObjCProtocolDecl *rProto) const {
6791 if (declaresSameEntity(lProto, rProto))
6793 for (auto *PI : rProto->protocols())
6794 if (ProtocolCompatibleWithProtocol(lProto, PI))
6799 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6800 /// Class<pr1, ...>.
6801 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6803 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6804 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6805 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6807 for (auto *lhsProto : lhsQID->quals()) {
6809 for (auto *rhsProto : rhsOPT->quals()) {
6810 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6821 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6822 /// ObjCQualifiedIDType.
6823 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6825 // Allow id<P..> and an 'id' or void* type in all cases.
6826 if (lhs->isVoidPointerType() ||
6827 lhs->isObjCIdType() || lhs->isObjCClassType())
6829 else if (rhs->isVoidPointerType() ||
6830 rhs->isObjCIdType() || rhs->isObjCClassType())
6833 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6834 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6836 if (!rhsOPT) return false;
6838 if (rhsOPT->qual_empty()) {
6839 // If the RHS is a unqualified interface pointer "NSString*",
6840 // make sure we check the class hierarchy.
6841 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6842 for (auto *I : lhsQID->quals()) {
6843 // when comparing an id<P> on lhs with a static type on rhs,
6844 // see if static class implements all of id's protocols, directly or
6845 // through its super class and categories.
6846 if (!rhsID->ClassImplementsProtocol(I, true))
6850 // If there are no qualifiers and no interface, we have an 'id'.
6853 // Both the right and left sides have qualifiers.
6854 for (auto *lhsProto : lhsQID->quals()) {
6857 // when comparing an id<P> on lhs with a static type on rhs,
6858 // see if static class implements all of id's protocols, directly or
6859 // through its super class and categories.
6860 for (auto *rhsProto : rhsOPT->quals()) {
6861 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6862 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6867 // If the RHS is a qualified interface pointer "NSString<P>*",
6868 // make sure we check the class hierarchy.
6869 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6870 for (auto *I : lhsQID->quals()) {
6871 // when comparing an id<P> on lhs with a static type on rhs,
6872 // see if static class implements all of id's protocols, directly or
6873 // through its super class and categories.
6874 if (rhsID->ClassImplementsProtocol(I, true)) {
6887 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6888 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6890 if (const ObjCObjectPointerType *lhsOPT =
6891 lhs->getAsObjCInterfacePointerType()) {
6892 // If both the right and left sides have qualifiers.
6893 for (auto *lhsProto : lhsOPT->quals()) {
6896 // when comparing an id<P> on rhs with a static type on lhs,
6897 // see if static class implements all of id's protocols, directly or
6898 // through its super class and categories.
6899 // First, lhs protocols in the qualifier list must be found, direct
6900 // or indirect in rhs's qualifier list or it is a mismatch.
6901 for (auto *rhsProto : rhsQID->quals()) {
6902 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6903 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6912 // Static class's protocols, or its super class or category protocols
6913 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6914 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6915 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6916 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6917 // This is rather dubious but matches gcc's behavior. If lhs has
6918 // no type qualifier and its class has no static protocol(s)
6919 // assume that it is mismatch.
6920 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6922 for (auto *lhsProto : LHSInheritedProtocols) {
6924 for (auto *rhsProto : rhsQID->quals()) {
6925 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6926 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6940 /// canAssignObjCInterfaces - Return true if the two interface types are
6941 /// compatible for assignment from RHS to LHS. This handles validation of any
6942 /// protocol qualifiers on the LHS or RHS.
6944 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6945 const ObjCObjectPointerType *RHSOPT) {
6946 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6947 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6949 // If either type represents the built-in 'id' or 'Class' types, return true.
6950 if (LHS->isObjCUnqualifiedIdOrClass() ||
6951 RHS->isObjCUnqualifiedIdOrClass())
6954 // Function object that propagates a successful result or handles
6956 auto finish = [&](bool succeeded) -> bool {
6960 if (!RHS->isKindOfType())
6963 // Strip off __kindof and protocol qualifiers, then check whether
6964 // we can assign the other way.
6965 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6966 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6969 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6970 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6975 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6976 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6977 QualType(RHSOPT,0)));
6980 // If we have 2 user-defined types, fall into that path.
6981 if (LHS->getInterface() && RHS->getInterface()) {
6982 return finish(canAssignObjCInterfaces(LHS, RHS));
6988 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6989 /// for providing type-safety for objective-c pointers used to pass/return
6990 /// arguments in block literals. When passed as arguments, passing 'A*' where
6991 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6992 /// not OK. For the return type, the opposite is not OK.
6993 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6994 const ObjCObjectPointerType *LHSOPT,
6995 const ObjCObjectPointerType *RHSOPT,
6996 bool BlockReturnType) {
6998 // Function object that propagates a successful result or handles
7000 auto finish = [&](bool succeeded) -> bool {
7004 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7005 if (!Expected->isKindOfType())
7008 // Strip off __kindof and protocol qualifiers, then check whether
7009 // we can assign the other way.
7010 return canAssignObjCInterfacesInBlockPointer(
7011 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7012 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7016 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
7019 if (LHSOPT->isObjCBuiltinType()) {
7020 return finish(RHSOPT->isObjCBuiltinType() ||
7021 RHSOPT->isObjCQualifiedIdType());
7024 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
7025 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7029 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7030 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7031 if (LHS && RHS) { // We have 2 user-defined types.
7033 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
7034 return finish(BlockReturnType);
7035 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
7036 return finish(!BlockReturnType);
7044 /// Comparison routine for Objective-C protocols to be used with
7045 /// llvm::array_pod_sort.
7046 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7047 ObjCProtocolDecl * const *rhs) {
7048 return (*lhs)->getName().compare((*rhs)->getName());
7052 /// getIntersectionOfProtocols - This routine finds the intersection of set
7053 /// of protocols inherited from two distinct objective-c pointer objects with
7054 /// the given common base.
7055 /// It is used to build composite qualifier list of the composite type of
7056 /// the conditional expression involving two objective-c pointer objects.
7058 void getIntersectionOfProtocols(ASTContext &Context,
7059 const ObjCInterfaceDecl *CommonBase,
7060 const ObjCObjectPointerType *LHSOPT,
7061 const ObjCObjectPointerType *RHSOPT,
7062 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
7064 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7065 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7066 assert(LHS->getInterface() && "LHS must have an interface base");
7067 assert(RHS->getInterface() && "RHS must have an interface base");
7069 // Add all of the protocols for the LHS.
7070 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7072 // Start with the protocol qualifiers.
7073 for (auto proto : LHS->quals()) {
7074 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
7077 // Also add the protocols associated with the LHS interface.
7078 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7080 // Add all of the protocls for the RHS.
7081 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7083 // Start with the protocol qualifiers.
7084 for (auto proto : RHS->quals()) {
7085 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
7088 // Also add the protocols associated with the RHS interface.
7089 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7091 // Compute the intersection of the collected protocol sets.
7092 for (auto proto : LHSProtocolSet) {
7093 if (RHSProtocolSet.count(proto))
7094 IntersectionSet.push_back(proto);
7097 // Compute the set of protocols that is implied by either the common type or
7098 // the protocols within the intersection.
7099 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7100 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7102 // Remove any implied protocols from the list of inherited protocols.
7103 if (!ImpliedProtocols.empty()) {
7104 IntersectionSet.erase(
7105 std::remove_if(IntersectionSet.begin(),
7106 IntersectionSet.end(),
7107 [&](ObjCProtocolDecl *proto) -> bool {
7108 return ImpliedProtocols.count(proto) > 0;
7110 IntersectionSet.end());
7113 // Sort the remaining protocols by name.
7114 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7115 compareObjCProtocolsByName);
7118 /// Determine whether the first type is a subtype of the second.
7119 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7121 // Common case: two object pointers.
7122 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7123 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7124 if (lhsOPT && rhsOPT)
7125 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7127 // Two block pointers.
7128 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7129 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7130 if (lhsBlock && rhsBlock)
7131 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7133 // If either is an unqualified 'id' and the other is a block, it's
7135 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7136 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7142 // Check that the given Objective-C type argument lists are equivalent.
7143 static bool sameObjCTypeArgs(ASTContext &ctx,
7144 const ObjCInterfaceDecl *iface,
7145 ArrayRef<QualType> lhsArgs,
7146 ArrayRef<QualType> rhsArgs,
7148 if (lhsArgs.size() != rhsArgs.size())
7151 ObjCTypeParamList *typeParams = iface->getTypeParamList();
7152 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
7153 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7156 switch (typeParams->begin()[i]->getVariance()) {
7157 case ObjCTypeParamVariance::Invariant:
7159 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7160 rhsArgs[i].stripObjCKindOfType(ctx))) {
7165 case ObjCTypeParamVariance::Covariant:
7166 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7170 case ObjCTypeParamVariance::Contravariant:
7171 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7180 QualType ASTContext::areCommonBaseCompatible(
7181 const ObjCObjectPointerType *Lptr,
7182 const ObjCObjectPointerType *Rptr) {
7183 const ObjCObjectType *LHS = Lptr->getObjectType();
7184 const ObjCObjectType *RHS = Rptr->getObjectType();
7185 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7186 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
7188 if (!LDecl || !RDecl)
7191 // When either LHS or RHS is a kindof type, we should return a kindof type.
7192 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7194 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7196 // Follow the left-hand side up the class hierarchy until we either hit a
7197 // root or find the RHS. Record the ancestors in case we don't find it.
7198 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7201 // Record this ancestor. We'll need this if the common type isn't in the
7202 // path from the LHS to the root.
7203 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
7205 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7206 // Get the type arguments.
7207 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7208 bool anyChanges = false;
7209 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7210 // Both have type arguments, compare them.
7211 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7212 LHS->getTypeArgs(), RHS->getTypeArgs(),
7213 /*stripKindOf=*/true))
7215 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7216 // If only one has type arguments, the result will not have type
7222 // Compute the intersection of protocols.
7223 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7224 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7226 if (!Protocols.empty())
7229 // If anything in the LHS will have changed, build a new result type.
7230 // If we need to return a kindof type but LHS is not a kindof type, we
7231 // build a new result type.
7232 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
7233 QualType Result = getObjCInterfaceType(LHS->getInterface());
7234 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7235 anyKindOf || LHS->isKindOfType());
7236 return getObjCObjectPointerType(Result);
7239 return getObjCObjectPointerType(QualType(LHS, 0));
7242 // Find the superclass.
7243 QualType LHSSuperType = LHS->getSuperClassType();
7244 if (LHSSuperType.isNull())
7247 LHS = LHSSuperType->castAs<ObjCObjectType>();
7250 // We didn't find anything by following the LHS to its root; now check
7251 // the RHS against the cached set of ancestors.
7253 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7254 if (KnownLHS != LHSAncestors.end()) {
7255 LHS = KnownLHS->second;
7257 // Get the type arguments.
7258 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7259 bool anyChanges = false;
7260 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7261 // Both have type arguments, compare them.
7262 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7263 LHS->getTypeArgs(), RHS->getTypeArgs(),
7264 /*stripKindOf=*/true))
7266 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7267 // If only one has type arguments, the result will not have type
7273 // Compute the intersection of protocols.
7274 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7275 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7277 if (!Protocols.empty())
7280 // If we need to return a kindof type but RHS is not a kindof type, we
7281 // build a new result type.
7282 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
7283 QualType Result = getObjCInterfaceType(RHS->getInterface());
7284 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7285 anyKindOf || RHS->isKindOfType());
7286 return getObjCObjectPointerType(Result);
7289 return getObjCObjectPointerType(QualType(RHS, 0));
7292 // Find the superclass of the RHS.
7293 QualType RHSSuperType = RHS->getSuperClassType();
7294 if (RHSSuperType.isNull())
7297 RHS = RHSSuperType->castAs<ObjCObjectType>();
7303 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7304 const ObjCObjectType *RHS) {
7305 assert(LHS->getInterface() && "LHS is not an interface type");
7306 assert(RHS->getInterface() && "RHS is not an interface type");
7308 // Verify that the base decls are compatible: the RHS must be a subclass of
7310 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7311 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7315 // If the LHS has protocol qualifiers, determine whether all of them are
7316 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7318 if (LHS->getNumProtocols() > 0) {
7319 // OK if conversion of LHS to SuperClass results in narrowing of types
7320 // ; i.e., SuperClass may implement at least one of the protocols
7321 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7322 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7323 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7324 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7325 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7327 for (auto *RHSPI : RHS->quals())
7328 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
7329 // If there is no protocols associated with RHS, it is not a match.
7330 if (SuperClassInheritedProtocols.empty())
7333 for (const auto *LHSProto : LHS->quals()) {
7334 bool SuperImplementsProtocol = false;
7335 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7336 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7337 SuperImplementsProtocol = true;
7340 if (!SuperImplementsProtocol)
7345 // If the LHS is specialized, we may need to check type arguments.
7346 if (LHS->isSpecialized()) {
7347 // Follow the superclass chain until we've matched the LHS class in the
7348 // hierarchy. This substitutes type arguments through.
7349 const ObjCObjectType *RHSSuper = RHS;
7350 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7351 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7353 // If the RHS is specializd, compare type arguments.
7354 if (RHSSuper->isSpecialized() &&
7355 !sameObjCTypeArgs(*this, LHS->getInterface(),
7356 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
7357 /*stripKindOf=*/true)) {
7365 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7366 // get the "pointed to" types
7367 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7368 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
7370 if (!LHSOPT || !RHSOPT)
7373 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7374 canAssignObjCInterfaces(RHSOPT, LHSOPT);
7377 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7378 return canAssignObjCInterfaces(
7379 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7380 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7383 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
7384 /// both shall have the identically qualified version of a compatible type.
7385 /// C99 6.2.7p1: Two types have compatible types if their types are the
7386 /// same. See 6.7.[2,3,5] for additional rules.
7387 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7388 bool CompareUnqualified) {
7389 if (getLangOpts().CPlusPlus)
7390 return hasSameType(LHS, RHS);
7392 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
7395 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
7396 return typesAreCompatible(LHS, RHS);
7399 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7400 return !mergeTypes(LHS, RHS, true).isNull();
7403 /// mergeTransparentUnionType - if T is a transparent union type and a member
7404 /// of T is compatible with SubType, return the merged type, else return
7406 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7407 bool OfBlockPointer,
7409 if (const RecordType *UT = T->getAsUnionType()) {
7410 RecordDecl *UD = UT->getDecl();
7411 if (UD->hasAttr<TransparentUnionAttr>()) {
7412 for (const auto *I : UD->fields()) {
7413 QualType ET = I->getType().getUnqualifiedType();
7414 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7424 /// mergeFunctionParameterTypes - merge two types which appear as function
7426 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7427 bool OfBlockPointer,
7429 // GNU extension: two types are compatible if they appear as a function
7430 // argument, one of the types is a transparent union type and the other
7431 // type is compatible with a union member
7432 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7434 if (!lmerge.isNull())
7437 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7439 if (!rmerge.isNull())
7442 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7445 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
7446 bool OfBlockPointer,
7448 const FunctionType *lbase = lhs->getAs<FunctionType>();
7449 const FunctionType *rbase = rhs->getAs<FunctionType>();
7450 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7451 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
7452 bool allLTypes = true;
7453 bool allRTypes = true;
7455 // Check return type
7457 if (OfBlockPointer) {
7458 QualType RHS = rbase->getReturnType();
7459 QualType LHS = lbase->getReturnType();
7460 bool UnqualifiedResult = Unqualified;
7461 if (!UnqualifiedResult)
7462 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
7463 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
7466 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
7468 if (retType.isNull()) return QualType();
7471 retType = retType.getUnqualifiedType();
7473 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7474 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
7476 LRetType = LRetType.getUnqualifiedType();
7477 RRetType = RRetType.getUnqualifiedType();
7480 if (getCanonicalType(retType) != LRetType)
7482 if (getCanonicalType(retType) != RRetType)
7485 // FIXME: double check this
7486 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7487 // rbase->getRegParmAttr() != 0 &&
7488 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
7489 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7490 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
7492 // Compatible functions must have compatible calling conventions
7493 if (lbaseInfo.getCC() != rbaseInfo.getCC())
7496 // Regparm is part of the calling convention.
7497 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7499 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7502 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7505 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7506 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
7508 if (lbaseInfo.getNoReturn() != NoReturn)
7510 if (rbaseInfo.getNoReturn() != NoReturn)
7513 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
7515 if (lproto && rproto) { // two C99 style function prototypes
7516 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7517 "C++ shouldn't be here");
7518 // Compatible functions must have the same number of parameters
7519 if (lproto->getNumParams() != rproto->getNumParams())
7522 // Variadic and non-variadic functions aren't compatible
7523 if (lproto->isVariadic() != rproto->isVariadic())
7526 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7529 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
7532 // Check parameter type compatibility
7533 SmallVector<QualType, 10> types;
7534 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7535 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7536 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7537 QualType paramType = mergeFunctionParameterTypes(
7538 lParamType, rParamType, OfBlockPointer, Unqualified);
7539 if (paramType.isNull())
7543 paramType = paramType.getUnqualifiedType();
7545 types.push_back(paramType);
7547 lParamType = lParamType.getUnqualifiedType();
7548 rParamType = rParamType.getUnqualifiedType();
7551 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
7553 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
7557 if (allLTypes) return lhs;
7558 if (allRTypes) return rhs;
7560 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7561 EPI.ExtInfo = einfo;
7562 return getFunctionType(retType, types, EPI);
7565 if (lproto) allRTypes = false;
7566 if (rproto) allLTypes = false;
7568 const FunctionProtoType *proto = lproto ? lproto : rproto;
7570 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7571 if (proto->isVariadic()) return QualType();
7572 // Check that the types are compatible with the types that
7573 // would result from default argument promotions (C99 6.7.5.3p15).
7574 // The only types actually affected are promotable integer
7575 // types and floats, which would be passed as a different
7576 // type depending on whether the prototype is visible.
7577 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7578 QualType paramTy = proto->getParamType(i);
7580 // Look at the converted type of enum types, since that is the type used
7581 // to pass enum values.
7582 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7583 paramTy = Enum->getDecl()->getIntegerType();
7584 if (paramTy.isNull())
7588 if (paramTy->isPromotableIntegerType() ||
7589 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
7593 if (allLTypes) return lhs;
7594 if (allRTypes) return rhs;
7596 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7597 EPI.ExtInfo = einfo;
7598 return getFunctionType(retType, proto->getParamTypes(), EPI);
7601 if (allLTypes) return lhs;
7602 if (allRTypes) return rhs;
7603 return getFunctionNoProtoType(retType, einfo);
7606 /// Given that we have an enum type and a non-enum type, try to merge them.
7607 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7608 QualType other, bool isBlockReturnType) {
7609 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7610 // a signed integer type, or an unsigned integer type.
7611 // Compatibility is based on the underlying type, not the promotion
7613 QualType underlyingType = ET->getDecl()->getIntegerType();
7614 if (underlyingType.isNull()) return QualType();
7615 if (Context.hasSameType(underlyingType, other))
7618 // In block return types, we're more permissive and accept any
7619 // integral type of the same size.
7620 if (isBlockReturnType && other->isIntegerType() &&
7621 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7627 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
7628 bool OfBlockPointer,
7629 bool Unqualified, bool BlockReturnType) {
7630 // C++ [expr]: If an expression initially has the type "reference to T", the
7631 // type is adjusted to "T" prior to any further analysis, the expression
7632 // designates the object or function denoted by the reference, and the
7633 // expression is an lvalue unless the reference is an rvalue reference and
7634 // the expression is a function call (possibly inside parentheses).
7635 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7636 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
7639 LHS = LHS.getUnqualifiedType();
7640 RHS = RHS.getUnqualifiedType();
7643 QualType LHSCan = getCanonicalType(LHS),
7644 RHSCan = getCanonicalType(RHS);
7646 // If two types are identical, they are compatible.
7647 if (LHSCan == RHSCan)
7650 // If the qualifiers are different, the types aren't compatible... mostly.
7651 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7652 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7653 if (LQuals != RQuals) {
7654 if (getLangOpts().OpenCL) {
7655 if (LHSCan.getUnqualifiedType() != RHSCan.getUnqualifiedType() ||
7656 LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers())
7658 if (LQuals.isAddressSpaceSupersetOf(RQuals))
7660 if (RQuals.isAddressSpaceSupersetOf(LQuals))
7663 // If any of these qualifiers are different, we have a type
7665 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7666 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7667 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
7670 // Exactly one GC qualifier difference is allowed: __strong is
7671 // okay if the other type has no GC qualifier but is an Objective
7672 // C object pointer (i.e. implicitly strong by default). We fix
7673 // this by pretending that the unqualified type was actually
7674 // qualified __strong.
7675 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7676 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7677 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7679 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7682 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7683 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7685 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7686 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7691 // Okay, qualifiers are equal.
7693 Type::TypeClass LHSClass = LHSCan->getTypeClass();
7694 Type::TypeClass RHSClass = RHSCan->getTypeClass();
7696 // We want to consider the two function types to be the same for these
7697 // comparisons, just force one to the other.
7698 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7699 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
7701 // Same as above for arrays
7702 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7703 LHSClass = Type::ConstantArray;
7704 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7705 RHSClass = Type::ConstantArray;
7707 // ObjCInterfaces are just specialized ObjCObjects.
7708 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7709 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7711 // Canonicalize ExtVector -> Vector.
7712 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7713 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
7715 // If the canonical type classes don't match.
7716 if (LHSClass != RHSClass) {
7717 // Note that we only have special rules for turning block enum
7718 // returns into block int returns, not vice-versa.
7719 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
7720 return mergeEnumWithInteger(*this, ETy, RHS, false);
7722 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
7723 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
7725 // allow block pointer type to match an 'id' type.
7726 if (OfBlockPointer && !BlockReturnType) {
7727 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7729 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7736 // The canonical type classes match.
7738 #define TYPE(Class, Base)
7739 #define ABSTRACT_TYPE(Class, Base)
7740 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
7741 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7742 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
7743 #include "clang/AST/TypeNodes.def"
7744 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
7747 case Type::LValueReference:
7748 case Type::RValueReference:
7749 case Type::MemberPointer:
7750 llvm_unreachable("C++ should never be in mergeTypes");
7752 case Type::ObjCInterface:
7753 case Type::IncompleteArray:
7754 case Type::VariableArray:
7755 case Type::FunctionProto:
7756 case Type::ExtVector:
7757 llvm_unreachable("Types are eliminated above");
7761 // Merge two pointer types, while trying to preserve typedef info
7762 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7763 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
7765 LHSPointee = LHSPointee.getUnqualifiedType();
7766 RHSPointee = RHSPointee.getUnqualifiedType();
7768 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7770 if (ResultType.isNull()) return QualType();
7771 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7773 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7775 return getPointerType(ResultType);
7777 case Type::BlockPointer:
7779 // Merge two block pointer types, while trying to preserve typedef info
7780 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7781 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7783 LHSPointee = LHSPointee.getUnqualifiedType();
7784 RHSPointee = RHSPointee.getUnqualifiedType();
7786 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7788 if (ResultType.isNull()) return QualType();
7789 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7791 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7793 return getBlockPointerType(ResultType);
7797 // Merge two pointer types, while trying to preserve typedef info
7798 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7799 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7801 LHSValue = LHSValue.getUnqualifiedType();
7802 RHSValue = RHSValue.getUnqualifiedType();
7804 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7806 if (ResultType.isNull()) return QualType();
7807 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7809 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7811 return getAtomicType(ResultType);
7813 case Type::ConstantArray:
7815 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7816 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7817 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7820 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7821 QualType RHSElem = getAsArrayType(RHS)->getElementType();
7823 LHSElem = LHSElem.getUnqualifiedType();
7824 RHSElem = RHSElem.getUnqualifiedType();
7827 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7828 if (ResultType.isNull()) return QualType();
7829 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7831 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7833 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7834 ArrayType::ArraySizeModifier(), 0);
7835 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7836 ArrayType::ArraySizeModifier(), 0);
7837 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7838 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7839 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7841 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7844 // FIXME: This isn't correct! But tricky to implement because
7845 // the array's size has to be the size of LHS, but the type
7846 // has to be different.
7850 // FIXME: This isn't correct! But tricky to implement because
7851 // the array's size has to be the size of RHS, but the type
7852 // has to be different.
7855 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7856 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7857 return getIncompleteArrayType(ResultType,
7858 ArrayType::ArraySizeModifier(), 0);
7860 case Type::FunctionNoProto:
7861 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7866 // Only exactly equal builtin types are compatible, which is tested above.
7869 // Distinct complex types are incompatible.
7872 // FIXME: The merged type should be an ExtVector!
7873 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7874 RHSCan->getAs<VectorType>()))
7877 case Type::ObjCObject: {
7878 // Check if the types are assignment compatible.
7879 // FIXME: This should be type compatibility, e.g. whether
7880 // "LHS x; RHS x;" at global scope is legal.
7881 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7882 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7883 if (canAssignObjCInterfaces(LHSIface, RHSIface))
7888 case Type::ObjCObjectPointer: {
7889 if (OfBlockPointer) {
7890 if (canAssignObjCInterfacesInBlockPointer(
7891 LHS->getAs<ObjCObjectPointerType>(),
7892 RHS->getAs<ObjCObjectPointerType>(),
7897 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7898 RHS->getAs<ObjCObjectPointerType>()))
7905 // Merge two pointer types, while trying to preserve typedef info
7906 QualType LHSValue = LHS->getAs<PipeType>()->getElementType();
7907 QualType RHSValue = RHS->getAs<PipeType>()->getElementType();
7909 LHSValue = LHSValue.getUnqualifiedType();
7910 RHSValue = RHSValue.getUnqualifiedType();
7912 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7914 if (ResultType.isNull()) return QualType();
7915 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7917 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7919 return getPipeType(ResultType);
7923 llvm_unreachable("Invalid Type::Class!");
7926 bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
7927 const FunctionProtoType *firstFnType,
7928 const FunctionProtoType *secondFnType) {
7929 // Fast path: if the first type doesn't have ext parameter infos,
7930 // we match if and only if they second type also doesn't have them.
7931 if (!firstFnType->hasExtParameterInfos())
7932 return !secondFnType->hasExtParameterInfos();
7934 // Otherwise, we can only match if the second type has them.
7935 if (!secondFnType->hasExtParameterInfos())
7938 auto firstEPI = firstFnType->getExtParameterInfos();
7939 auto secondEPI = secondFnType->getExtParameterInfos();
7940 assert(firstEPI.size() == secondEPI.size());
7942 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
7943 if (firstEPI[i] != secondEPI[i])
7949 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
7950 ObjCLayouts[CD] = nullptr;
7953 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7954 /// 'RHS' attributes and returns the merged version; including for function
7956 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7957 QualType LHSCan = getCanonicalType(LHS),
7958 RHSCan = getCanonicalType(RHS);
7959 // If two types are identical, they are compatible.
7960 if (LHSCan == RHSCan)
7962 if (RHSCan->isFunctionType()) {
7963 if (!LHSCan->isFunctionType())
7965 QualType OldReturnType =
7966 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
7967 QualType NewReturnType =
7968 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
7969 QualType ResReturnType =
7970 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7971 if (ResReturnType.isNull())
7973 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7974 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7975 // In either case, use OldReturnType to build the new function type.
7976 const FunctionType *F = LHS->getAs<FunctionType>();
7977 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7978 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7979 EPI.ExtInfo = getFunctionExtInfo(LHS);
7980 QualType ResultType =
7981 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
7988 // If the qualifiers are different, the types can still be merged.
7989 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7990 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7991 if (LQuals != RQuals) {
7992 // If any of these qualifiers are different, we have a type mismatch.
7993 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7994 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7997 // Exactly one GC qualifier difference is allowed: __strong is
7998 // okay if the other type has no GC qualifier but is an Objective
7999 // C object pointer (i.e. implicitly strong by default). We fix
8000 // this by pretending that the unqualified type was actually
8001 // qualified __strong.
8002 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8003 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8004 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8006 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8009 if (GC_L == Qualifiers::Strong)
8011 if (GC_R == Qualifiers::Strong)
8016 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8017 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8018 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8019 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8020 if (ResQT == LHSBaseQT)
8022 if (ResQT == RHSBaseQT)
8028 //===----------------------------------------------------------------------===//
8029 // Integer Predicates
8030 //===----------------------------------------------------------------------===//
8032 unsigned ASTContext::getIntWidth(QualType T) const {
8033 if (const EnumType *ET = T->getAs<EnumType>())
8034 T = ET->getDecl()->getIntegerType();
8035 if (T->isBooleanType())
8037 // For builtin types, just use the standard type sizing method
8038 return (unsigned)getTypeSize(T);
8041 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
8042 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
8044 // Turn <4 x signed int> -> <4 x unsigned int>
8045 if (const VectorType *VTy = T->getAs<VectorType>())
8046 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
8047 VTy->getNumElements(), VTy->getVectorKind());
8049 // For enums, we return the unsigned version of the base type.
8050 if (const EnumType *ETy = T->getAs<EnumType>())
8051 T = ETy->getDecl()->getIntegerType();
8053 const BuiltinType *BTy = T->getAs<BuiltinType>();
8054 assert(BTy && "Unexpected signed integer type");
8055 switch (BTy->getKind()) {
8056 case BuiltinType::Char_S:
8057 case BuiltinType::SChar:
8058 return UnsignedCharTy;
8059 case BuiltinType::Short:
8060 return UnsignedShortTy;
8061 case BuiltinType::Int:
8062 return UnsignedIntTy;
8063 case BuiltinType::Long:
8064 return UnsignedLongTy;
8065 case BuiltinType::LongLong:
8066 return UnsignedLongLongTy;
8067 case BuiltinType::Int128:
8068 return UnsignedInt128Ty;
8070 llvm_unreachable("Unexpected signed integer type");
8074 ASTMutationListener::~ASTMutationListener() { }
8076 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8077 QualType ReturnType) {}
8079 //===----------------------------------------------------------------------===//
8080 // Builtin Type Computation
8081 //===----------------------------------------------------------------------===//
8083 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
8084 /// pointer over the consumed characters. This returns the resultant type. If
8085 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8086 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8087 /// a vector of "i*".
8089 /// RequiresICE is filled in on return to indicate whether the value is required
8090 /// to be an Integer Constant Expression.
8091 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
8092 ASTContext::GetBuiltinTypeError &Error,
8094 bool AllowTypeModifiers) {
8097 bool Signed = false, Unsigned = false;
8098 RequiresICE = false;
8100 // Read the prefixed modifiers first.
8104 default: Done = true; --Str; break;
8109 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8110 assert(!Signed && "Can't use 'S' modifier multiple times!");
8114 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
8115 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
8119 assert(HowLong <= 2 && "Can't have LLLL modifier");
8123 // This modifier represents int64 type.
8124 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8125 switch (Context.getTargetInfo().getInt64Type()) {
8127 llvm_unreachable("Unexpected integer type");
8128 case TargetInfo::SignedLong:
8131 case TargetInfo::SignedLongLong:
8140 // Read the base type.
8142 default: llvm_unreachable("Unknown builtin type letter!");
8144 assert(HowLong == 0 && !Signed && !Unsigned &&
8145 "Bad modifiers used with 'v'!");
8146 Type = Context.VoidTy;
8149 assert(HowLong == 0 && !Signed && !Unsigned &&
8150 "Bad modifiers used with 'h'!");
8151 Type = Context.HalfTy;
8154 assert(HowLong == 0 && !Signed && !Unsigned &&
8155 "Bad modifiers used with 'f'!");
8156 Type = Context.FloatTy;
8159 assert(HowLong < 2 && !Signed && !Unsigned &&
8160 "Bad modifiers used with 'd'!");
8162 Type = Context.LongDoubleTy;
8164 Type = Context.DoubleTy;
8167 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8169 Type = Context.UnsignedShortTy;
8171 Type = Context.ShortTy;
8175 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8176 else if (HowLong == 2)
8177 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8178 else if (HowLong == 1)
8179 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8181 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8184 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8186 Type = Context.SignedCharTy;
8188 Type = Context.UnsignedCharTy;
8190 Type = Context.CharTy;
8192 case 'b': // boolean
8193 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8194 Type = Context.BoolTy;
8196 case 'z': // size_t.
8197 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8198 Type = Context.getSizeType();
8201 Type = Context.getCFConstantStringType();
8204 Type = Context.getObjCIdType();
8207 Type = Context.getObjCSelType();
8210 Type = Context.getObjCSuperType();
8213 Type = Context.getBuiltinVaListType();
8214 assert(!Type.isNull() && "builtin va list type not initialized!");
8217 // This is a "reference" to a va_list; however, what exactly
8218 // this means depends on how va_list is defined. There are two
8219 // different kinds of va_list: ones passed by value, and ones
8220 // passed by reference. An example of a by-value va_list is
8221 // x86, where va_list is a char*. An example of by-ref va_list
8222 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8223 // we want this argument to be a char*&; for x86-64, we want
8224 // it to be a __va_list_tag*.
8225 Type = Context.getBuiltinVaListType();
8226 assert(!Type.isNull() && "builtin va list type not initialized!");
8227 if (Type->isArrayType())
8228 Type = Context.getArrayDecayedType(Type);
8230 Type = Context.getLValueReferenceType(Type);
8234 unsigned NumElements = strtoul(Str, &End, 10);
8235 assert(End != Str && "Missing vector size");
8238 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8239 RequiresICE, false);
8240 assert(!RequiresICE && "Can't require vector ICE");
8242 // TODO: No way to make AltiVec vectors in builtins yet.
8243 Type = Context.getVectorType(ElementType, NumElements,
8244 VectorType::GenericVector);
8250 unsigned NumElements = strtoul(Str, &End, 10);
8251 assert(End != Str && "Missing vector size");
8255 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8257 Type = Context.getExtVectorType(ElementType, NumElements);
8261 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8263 assert(!RequiresICE && "Can't require complex ICE");
8264 Type = Context.getComplexType(ElementType);
8268 Type = Context.getPointerDiffType();
8272 Type = Context.getFILEType();
8273 if (Type.isNull()) {
8274 Error = ASTContext::GE_Missing_stdio;
8280 Type = Context.getsigjmp_bufType();
8282 Type = Context.getjmp_bufType();
8284 if (Type.isNull()) {
8285 Error = ASTContext::GE_Missing_setjmp;
8290 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8291 Type = Context.getucontext_tType();
8293 if (Type.isNull()) {
8294 Error = ASTContext::GE_Missing_ucontext;
8299 Type = Context.getProcessIDType();
8303 // If there are modifiers and if we're allowed to parse them, go for it.
8304 Done = !AllowTypeModifiers;
8306 switch (char c = *Str++) {
8307 default: Done = true; --Str; break;
8310 // Both pointers and references can have their pointee types
8311 // qualified with an address space.
8313 unsigned AddrSpace = strtoul(Str, &End, 10);
8314 if (End != Str && AddrSpace != 0) {
8315 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8319 Type = Context.getPointerType(Type);
8321 Type = Context.getLValueReferenceType(Type);
8324 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8326 Type = Type.withConst();
8329 Type = Context.getVolatileType(Type);
8332 Type = Type.withRestrict();
8337 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
8338 "Integer constant 'I' type must be an integer");
8343 /// GetBuiltinType - Return the type for the specified builtin.
8344 QualType ASTContext::GetBuiltinType(unsigned Id,
8345 GetBuiltinTypeError &Error,
8346 unsigned *IntegerConstantArgs) const {
8347 const char *TypeStr = BuiltinInfo.getTypeString(Id);
8349 SmallVector<QualType, 8> ArgTypes;
8351 bool RequiresICE = false;
8353 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8355 if (Error != GE_None)
8358 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8360 while (TypeStr[0] && TypeStr[0] != '.') {
8361 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
8362 if (Error != GE_None)
8365 // If this argument is required to be an IntegerConstantExpression and the
8366 // caller cares, fill in the bitmask we return.
8367 if (RequiresICE && IntegerConstantArgs)
8368 *IntegerConstantArgs |= 1 << ArgTypes.size();
8370 // Do array -> pointer decay. The builtin should use the decayed type.
8371 if (Ty->isArrayType())
8372 Ty = getArrayDecayedType(Ty);
8374 ArgTypes.push_back(Ty);
8377 if (Id == Builtin::BI__GetExceptionInfo)
8380 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8381 "'.' should only occur at end of builtin type list!");
8383 FunctionType::ExtInfo EI(CC_C);
8384 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8386 bool Variadic = (TypeStr[0] == '.');
8388 // We really shouldn't be making a no-proto type here, especially in C++.
8389 if (ArgTypes.empty() && Variadic)
8390 return getFunctionNoProtoType(ResType, EI);
8392 FunctionProtoType::ExtProtoInfo EPI;
8394 EPI.Variadic = Variadic;
8396 return getFunctionType(ResType, ArgTypes, EPI);
8399 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8400 const FunctionDecl *FD) {
8401 if (!FD->isExternallyVisible())
8402 return GVA_Internal;
8404 GVALinkage External = GVA_StrongExternal;
8405 switch (FD->getTemplateSpecializationKind()) {
8406 case TSK_Undeclared:
8407 case TSK_ExplicitSpecialization:
8408 External = GVA_StrongExternal;
8411 case TSK_ExplicitInstantiationDefinition:
8412 return GVA_StrongODR;
8414 // C++11 [temp.explicit]p10:
8415 // [ Note: The intent is that an inline function that is the subject of
8416 // an explicit instantiation declaration will still be implicitly
8417 // instantiated when used so that the body can be considered for
8418 // inlining, but that no out-of-line copy of the inline function would be
8419 // generated in the translation unit. -- end note ]
8420 case TSK_ExplicitInstantiationDeclaration:
8421 return GVA_AvailableExternally;
8423 case TSK_ImplicitInstantiation:
8424 External = GVA_DiscardableODR;
8428 if (!FD->isInlined())
8431 if ((!Context.getLangOpts().CPlusPlus &&
8432 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8433 !FD->hasAttr<DLLExportAttr>()) ||
8434 FD->hasAttr<GNUInlineAttr>()) {
8435 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8437 // GNU or C99 inline semantics. Determine whether this symbol should be
8438 // externally visible.
8439 if (FD->isInlineDefinitionExternallyVisible())
8442 // C99 inline semantics, where the symbol is not externally visible.
8443 return GVA_AvailableExternally;
8446 // Functions specified with extern and inline in -fms-compatibility mode
8447 // forcibly get emitted. While the body of the function cannot be later
8448 // replaced, the function definition cannot be discarded.
8449 if (FD->isMSExternInline())
8450 return GVA_StrongODR;
8452 return GVA_DiscardableODR;
8455 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8456 GVALinkage L, const Decl *D) {
8457 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8458 // dllexport/dllimport on inline functions.
8459 if (D->hasAttr<DLLImportAttr>()) {
8460 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8461 return GVA_AvailableExternally;
8462 } else if (D->hasAttr<DLLExportAttr>()) {
8463 if (L == GVA_DiscardableODR)
8464 return GVA_StrongODR;
8465 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8466 D->hasAttr<CUDAGlobalAttr>()) {
8467 // Device-side functions with __global__ attribute must always be
8468 // visible externally so they can be launched from host.
8469 if (L == GVA_DiscardableODR || L == GVA_Internal)
8470 return GVA_StrongODR;
8475 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8476 return adjustGVALinkageForAttributes(
8477 *this, basicGVALinkageForFunction(*this, FD), FD);
8480 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8481 const VarDecl *VD) {
8482 if (!VD->isExternallyVisible())
8483 return GVA_Internal;
8485 if (VD->isStaticLocal()) {
8486 GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8487 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8488 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8489 LexicalContext = LexicalContext->getLexicalParent();
8491 // Let the static local variable inherit its linkage from the nearest
8492 // enclosing function.
8494 StaticLocalLinkage =
8495 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8497 // GVA_StrongODR function linkage is stronger than what we need,
8498 // downgrade to GVA_DiscardableODR.
8499 // This allows us to discard the variable if we never end up needing it.
8500 return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8501 : StaticLocalLinkage;
8504 // MSVC treats in-class initialized static data members as definitions.
8505 // By giving them non-strong linkage, out-of-line definitions won't
8506 // cause link errors.
8507 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8508 return GVA_DiscardableODR;
8510 // Most non-template variables have strong linkage; inline variables are
8511 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8512 GVALinkage StrongLinkage;
8513 switch (Context.getInlineVariableDefinitionKind(VD)) {
8514 case ASTContext::InlineVariableDefinitionKind::None:
8515 StrongLinkage = GVA_StrongExternal;
8517 case ASTContext::InlineVariableDefinitionKind::Weak:
8518 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
8519 StrongLinkage = GVA_DiscardableODR;
8521 case ASTContext::InlineVariableDefinitionKind::Strong:
8522 StrongLinkage = GVA_StrongODR;
8526 switch (VD->getTemplateSpecializationKind()) {
8527 case TSK_Undeclared:
8528 return StrongLinkage;
8530 case TSK_ExplicitSpecialization:
8531 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8532 VD->isStaticDataMember()
8536 case TSK_ExplicitInstantiationDefinition:
8537 return GVA_StrongODR;
8539 case TSK_ExplicitInstantiationDeclaration:
8540 return GVA_AvailableExternally;
8542 case TSK_ImplicitInstantiation:
8543 return GVA_DiscardableODR;
8546 llvm_unreachable("Invalid Linkage!");
8549 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8550 return adjustGVALinkageForAttributes(
8551 *this, basicGVALinkageForVariable(*this, VD), VD);
8554 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
8555 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8556 if (!VD->isFileVarDecl())
8558 // Global named register variables (GNU extension) are never emitted.
8559 if (VD->getStorageClass() == SC_Register)
8561 if (VD->getDescribedVarTemplate() ||
8562 isa<VarTemplatePartialSpecializationDecl>(VD))
8564 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8565 // We never need to emit an uninstantiated function template.
8566 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8568 } else if (isa<PragmaCommentDecl>(D))
8570 else if (isa<OMPThreadPrivateDecl>(D) ||
8571 D->hasAttr<OMPDeclareTargetDeclAttr>())
8573 else if (isa<PragmaDetectMismatchDecl>(D))
8575 else if (isa<OMPThreadPrivateDecl>(D))
8576 return !D->getDeclContext()->isDependentContext();
8577 else if (isa<OMPDeclareReductionDecl>(D))
8578 return !D->getDeclContext()->isDependentContext();
8582 // If this is a member of a class template, we do not need to emit it.
8583 if (D->getDeclContext()->isDependentContext())
8586 // Weak references don't produce any output by themselves.
8587 if (D->hasAttr<WeakRefAttr>())
8590 // Aliases and used decls are required.
8591 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8594 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8595 // Forward declarations aren't required.
8596 if (!FD->doesThisDeclarationHaveABody())
8597 return FD->doesDeclarationForceExternallyVisibleDefinition();
8599 // Constructors and destructors are required.
8600 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8603 // The key function for a class is required. This rule only comes
8604 // into play when inline functions can be key functions, though.
8605 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8606 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8607 const CXXRecordDecl *RD = MD->getParent();
8608 if (MD->isOutOfLine() && RD->isDynamicClass()) {
8609 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8610 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8616 GVALinkage Linkage = GetGVALinkageForFunction(FD);
8618 // static, static inline, always_inline, and extern inline functions can
8619 // always be deferred. Normal inline functions can be deferred in C99/C++.
8620 // Implicit template instantiations can also be deferred in C++.
8621 if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8622 Linkage == GVA_DiscardableODR)
8627 const VarDecl *VD = cast<VarDecl>(D);
8628 assert(VD->isFileVarDecl() && "Expected file scoped var");
8630 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8631 !isMSStaticDataMemberInlineDefinition(VD))
8634 // Variables that can be needed in other TUs are required.
8635 GVALinkage L = GetGVALinkageForVariable(VD);
8636 if (L != GVA_Internal && L != GVA_AvailableExternally &&
8637 L != GVA_DiscardableODR)
8640 // Variables that have destruction with side-effects are required.
8641 if (VD->getType().isDestructedType())
8644 // Variables that have initialization with side-effects are required.
8645 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8646 !VD->evaluateValue())
8652 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8653 bool IsCXXMethod) const {
8654 // Pass through to the C++ ABI object
8656 return ABI->getDefaultMethodCallConv(IsVariadic);
8658 switch (LangOpts.getDefaultCallingConv()) {
8659 case LangOptions::DCC_None:
8661 case LangOptions::DCC_CDecl:
8663 case LangOptions::DCC_FastCall:
8664 if (getTargetInfo().hasFeature("sse2"))
8665 return CC_X86FastCall;
8667 case LangOptions::DCC_StdCall:
8669 return CC_X86StdCall;
8671 case LangOptions::DCC_VectorCall:
8672 // __vectorcall cannot be applied to variadic functions.
8674 return CC_X86VectorCall;
8677 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
8680 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
8681 // Pass through to the C++ ABI object
8682 return ABI->isNearlyEmpty(RD);
8685 VTableContextBase *ASTContext::getVTableContext() {
8686 if (!VTContext.get()) {
8687 if (Target->getCXXABI().isMicrosoft())
8688 VTContext.reset(new MicrosoftVTableContext(*this));
8690 VTContext.reset(new ItaniumVTableContext(*this));
8692 return VTContext.get();
8695 MangleContext *ASTContext::createMangleContext() {
8696 switch (Target->getCXXABI().getKind()) {
8697 case TargetCXXABI::GenericAArch64:
8698 case TargetCXXABI::GenericItanium:
8699 case TargetCXXABI::GenericARM:
8700 case TargetCXXABI::GenericMIPS:
8701 case TargetCXXABI::iOS:
8702 case TargetCXXABI::iOS64:
8703 case TargetCXXABI::WebAssembly:
8704 case TargetCXXABI::WatchOS:
8705 return ItaniumMangleContext::create(*this, getDiagnostics());
8706 case TargetCXXABI::Microsoft:
8707 return MicrosoftMangleContext::create(*this, getDiagnostics());
8709 llvm_unreachable("Unsupported ABI");
8712 CXXABI::~CXXABI() {}
8714 size_t ASTContext::getSideTableAllocatedMemory() const {
8715 return ASTRecordLayouts.getMemorySize() +
8716 llvm::capacity_in_bytes(ObjCLayouts) +
8717 llvm::capacity_in_bytes(KeyFunctions) +
8718 llvm::capacity_in_bytes(ObjCImpls) +
8719 llvm::capacity_in_bytes(BlockVarCopyInits) +
8720 llvm::capacity_in_bytes(DeclAttrs) +
8721 llvm::capacity_in_bytes(TemplateOrInstantiation) +
8722 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8723 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8724 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8725 llvm::capacity_in_bytes(OverriddenMethods) +
8726 llvm::capacity_in_bytes(Types) +
8727 llvm::capacity_in_bytes(VariableArrayTypes) +
8728 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
8731 /// getIntTypeForBitwidth -
8732 /// sets integer QualTy according to specified details:
8733 /// bitwidth, signed/unsigned.
8734 /// Returns empty type if there is no appropriate target types.
8735 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8736 unsigned Signed) const {
8737 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8738 CanQualType QualTy = getFromTargetType(Ty);
8739 if (!QualTy && DestWidth == 128)
8740 return Signed ? Int128Ty : UnsignedInt128Ty;
8744 /// getRealTypeForBitwidth -
8745 /// sets floating point QualTy according to specified bitwidth.
8746 /// Returns empty type if there is no appropriate target types.
8747 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8748 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8750 case TargetInfo::Float:
8752 case TargetInfo::Double:
8754 case TargetInfo::LongDouble:
8755 return LongDoubleTy;
8756 case TargetInfo::Float128:
8758 case TargetInfo::NoFloat:
8762 llvm_unreachable("Unhandled TargetInfo::RealType value");
8765 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8767 MangleNumbers[ND] = Number;
8770 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8771 auto I = MangleNumbers.find(ND);
8772 return I != MangleNumbers.end() ? I->second : 1;
8775 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8777 StaticLocalNumbers[VD] = Number;
8780 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8781 auto I = StaticLocalNumbers.find(VD);
8782 return I != StaticLocalNumbers.end() ? I->second : 1;
8785 MangleNumberingContext &
8786 ASTContext::getManglingNumberContext(const DeclContext *DC) {
8787 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
8788 MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8790 MCtx = createMangleNumberingContext();
8794 MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8795 return ABI->createMangleNumberingContext();
8798 const CXXConstructorDecl *
8799 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8800 return ABI->getCopyConstructorForExceptionObject(
8801 cast<CXXRecordDecl>(RD->getFirstDecl()));
8804 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8805 CXXConstructorDecl *CD) {
8806 return ABI->addCopyConstructorForExceptionObject(
8807 cast<CXXRecordDecl>(RD->getFirstDecl()),
8808 cast<CXXConstructorDecl>(CD->getFirstDecl()));
8811 void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8812 unsigned ParmIdx, Expr *DAE) {
8813 ABI->addDefaultArgExprForConstructor(
8814 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8817 Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8819 return ABI->getDefaultArgExprForConstructor(
8820 cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8823 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8824 TypedefNameDecl *DD) {
8825 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8829 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8830 return ABI->getTypedefNameForUnnamedTagDecl(TD);
8833 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8834 DeclaratorDecl *DD) {
8835 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8838 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8839 return ABI->getDeclaratorForUnnamedTagDecl(TD);
8842 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8843 ParamIndices[D] = index;
8846 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8847 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8848 assert(I != ParamIndices.end() &&
8849 "ParmIndices lacks entry set by ParmVarDecl");
8854 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8856 assert(E && E->getStorageDuration() == SD_Static &&
8857 "don't need to cache the computed value for this temporary");
8859 APValue *&MTVI = MaterializedTemporaryValues[E];
8861 MTVI = new (*this) APValue;
8865 return MaterializedTemporaryValues.lookup(E);
8868 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8869 const llvm::Triple &T = getTargetInfo().getTriple();
8870 if (!T.isOSDarwin())
8873 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8874 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8877 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8878 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8879 uint64_t Size = sizeChars.getQuantity();
8880 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8881 unsigned Align = alignChars.getQuantity();
8882 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8883 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8888 ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8889 ASTContext::ParentMapPointers::mapped_type U) {
8890 if (const auto *D = U.dyn_cast<const Decl *>())
8891 return ast_type_traits::DynTypedNode::create(*D);
8892 if (const auto *S = U.dyn_cast<const Stmt *>())
8893 return ast_type_traits::DynTypedNode::create(*S);
8894 return *U.get<ast_type_traits::DynTypedNode *>();
8897 /// Template specializations to abstract away from pointers and TypeLocs.
8899 template <typename T>
8900 ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8901 return ast_type_traits::DynTypedNode::create(*Node);
8904 ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8905 return ast_type_traits::DynTypedNode::create(Node);
8908 ast_type_traits::DynTypedNode
8909 createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8910 return ast_type_traits::DynTypedNode::create(Node);
8914 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8915 /// parents as defined by the \c RecursiveASTVisitor.
8917 /// Note that the relationship described here is purely in terms of AST
8918 /// traversal - there are other relationships (for example declaration context)
8919 /// in the AST that are better modeled by special matchers.
8921 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8922 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8924 /// \brief Builds and returns the translation unit's parent map.
8926 /// The caller takes ownership of the returned \c ParentMap.
8927 static std::pair<ASTContext::ParentMapPointers *,
8928 ASTContext::ParentMapOtherNodes *>
8929 buildMap(TranslationUnitDecl &TU) {
8930 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8931 new ASTContext::ParentMapOtherNodes);
8932 Visitor.TraverseDecl(&TU);
8933 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
8937 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8939 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
8940 ASTContext::ParentMapOtherNodes *OtherParents)
8941 : Parents(Parents), OtherParents(OtherParents) {}
8943 bool shouldVisitTemplateInstantiations() const {
8946 bool shouldVisitImplicitCode() const {
8950 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
8952 bool TraverseNode(T Node, MapNodeTy MapNode,
8953 BaseTraverseFn BaseTraverse, MapTy *Parents) {
8956 if (ParentStack.size() > 0) {
8957 // FIXME: Currently we add the same parent multiple times, but only
8958 // when no memoization data is available for the type.
8959 // For example when we visit all subexpressions of template
8960 // instantiations; this is suboptimal, but benign: the only way to
8961 // visit those is with hasAncestor / hasParent, and those do not create
8963 // The plan is to enable DynTypedNode to be storable in a map or hash
8964 // map. The main problem there is to implement hash functions /
8965 // comparison operators for all types that DynTypedNode supports that
8966 // do not have pointer identity.
8967 auto &NodeOrVector = (*Parents)[MapNode];
8968 if (NodeOrVector.isNull()) {
8969 if (const auto *D = ParentStack.back().get<Decl>())
8971 else if (const auto *S = ParentStack.back().get<Stmt>())
8975 new ast_type_traits::DynTypedNode(ParentStack.back());
8977 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
8978 auto *Vector = new ASTContext::ParentVector(
8979 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
8982 .template dyn_cast<ast_type_traits::DynTypedNode *>())
8984 NodeOrVector = Vector;
8988 NodeOrVector.template get<ASTContext::ParentVector *>();
8989 // Skip duplicates for types that have memoization data.
8990 // We must check that the type has memoization data before calling
8991 // std::find() because DynTypedNode::operator== can't compare all
8993 bool Found = ParentStack.back().getMemoizationData() &&
8994 std::find(Vector->begin(), Vector->end(),
8995 ParentStack.back()) != Vector->end();
8997 Vector->push_back(ParentStack.back());
9000 ParentStack.push_back(createDynTypedNode(Node));
9001 bool Result = BaseTraverse();
9002 ParentStack.pop_back();
9006 bool TraverseDecl(Decl *DeclNode) {
9007 return TraverseNode(DeclNode, DeclNode,
9008 [&] { return VisitorBase::TraverseDecl(DeclNode); },
9012 bool TraverseStmt(Stmt *StmtNode) {
9013 return TraverseNode(StmtNode, StmtNode,
9014 [&] { return VisitorBase::TraverseStmt(StmtNode); },
9018 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
9019 return TraverseNode(
9020 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9021 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9025 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9026 return TraverseNode(
9027 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
9029 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9034 ASTContext::ParentMapPointers *Parents;
9035 ASTContext::ParentMapOtherNodes *OtherParents;
9036 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9038 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9041 } // anonymous namespace
9043 template <typename NodeTy, typename MapTy>
9044 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9046 auto I = Map.find(Node);
9047 if (I == Map.end()) {
9048 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
9050 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
9051 return llvm::makeArrayRef(*V);
9053 return getSingleDynTypedNodeFromParentMap(I->second);
9056 ASTContext::DynTypedNodeList
9057 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9058 if (!PointerParents) {
9059 // We always need to run over the whole translation unit, as
9060 // hasAncestor can escape any subtree.
9061 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9062 PointerParents.reset(Maps.first);
9063 OtherParents.reset(Maps.second);
9065 if (Node.getNodeKind().hasPointerIdentity())
9066 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9067 return getDynNodeFromMap(Node, *OtherParents);
9071 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9072 const ObjCMethodDecl *MethodImpl) {
9073 // No point trying to match an unavailable/deprecated mothod.
9074 if (MethodDecl->hasAttr<UnavailableAttr>()
9075 || MethodDecl->hasAttr<DeprecatedAttr>())
9077 if (MethodDecl->getObjCDeclQualifier() !=
9078 MethodImpl->getObjCDeclQualifier())
9080 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
9083 if (MethodDecl->param_size() != MethodImpl->param_size())
9086 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9087 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9088 EF = MethodDecl->param_end();
9089 IM != EM && IF != EF; ++IM, ++IF) {
9090 const ParmVarDecl *DeclVar = (*IF);
9091 const ParmVarDecl *ImplVar = (*IM);
9092 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9094 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9097 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9101 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9102 // doesn't include ASTContext.h
9104 clang::LazyGenerationalUpdatePtr<
9105 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9106 clang::LazyGenerationalUpdatePtr<
9107 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9108 const clang::ASTContext &Ctx, Decl *Value);