1 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ASTContext interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Comment.h"
20 #include "clang/AST/CommentCommandTraits.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/Mangle.h"
28 #include "clang/AST/RecordLayout.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/Builtins.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Support/Capacity.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
40 using namespace clang;
42 unsigned ASTContext::NumImplicitDefaultConstructors;
43 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
44 unsigned ASTContext::NumImplicitCopyConstructors;
45 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
46 unsigned ASTContext::NumImplicitMoveConstructors;
47 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
48 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
49 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
50 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
51 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
52 unsigned ASTContext::NumImplicitDestructors;
53 unsigned ASTContext::NumImplicitDestructorsDeclared;
56 HalfRank, FloatRank, DoubleRank, LongDoubleRank
59 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
60 if (!CommentsLoaded && ExternalSource) {
61 ExternalSource->ReadComments();
62 CommentsLoaded = true;
67 // User can not attach documentation to implicit declarations.
71 // User can not attach documentation to implicit instantiations.
72 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
73 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
77 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
78 if (VD->isStaticDataMember() &&
79 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
83 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
84 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
88 if (const ClassTemplateSpecializationDecl *CTSD =
89 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
90 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
91 if (TSK == TSK_ImplicitInstantiation ||
92 TSK == TSK_Undeclared)
96 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
97 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
101 // TODO: handle comments for function parameters properly.
102 if (isa<ParmVarDecl>(D))
105 // TODO: we could look up template parameter documentation in the template
107 if (isa<TemplateTypeParmDecl>(D) ||
108 isa<NonTypeTemplateParmDecl>(D) ||
109 isa<TemplateTemplateParmDecl>(D))
112 ArrayRef<RawComment *> RawComments = Comments.getComments();
114 // If there are no comments anywhere, we won't find anything.
115 if (RawComments.empty())
118 // Find declaration location.
119 // For Objective-C declarations we generally don't expect to have multiple
120 // declarators, thus use declaration starting location as the "declaration
122 // For all other declarations multiple declarators are used quite frequently,
123 // so we use the location of the identifier as the "declaration location".
124 SourceLocation DeclLoc;
125 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
126 isa<ObjCPropertyDecl>(D) ||
127 isa<RedeclarableTemplateDecl>(D) ||
128 isa<ClassTemplateSpecializationDecl>(D))
129 DeclLoc = D->getLocStart();
131 DeclLoc = D->getLocation();
133 // If the declaration doesn't map directly to a location in a file, we
134 // can't find the comment.
135 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
138 // Find the comment that occurs just after this declaration.
139 ArrayRef<RawComment *>::iterator Comment;
141 // When searching for comments during parsing, the comment we are looking
142 // for is usually among the last two comments we parsed -- check them
144 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
145 BeforeThanCompare<RawComment> Compare(SourceMgr);
146 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
147 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
148 if (!Found && RawComments.size() >= 2) {
150 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
154 Comment = MaybeBeforeDecl + 1;
155 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
156 &CommentAtDeclLoc, Compare));
159 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
160 &CommentAtDeclLoc, Compare);
164 // Decompose the location for the declaration and find the beginning of the
166 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
168 // First check whether we have a trailing comment.
169 if (Comment != RawComments.end() &&
170 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
171 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) {
172 std::pair<FileID, unsigned> CommentBeginDecomp
173 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
174 // Check that Doxygen trailing comment comes after the declaration, starts
175 // on the same line and in the same file as the declaration.
176 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
177 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
178 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
179 CommentBeginDecomp.second)) {
184 // The comment just after the declaration was not a trailing comment.
185 // Let's look at the previous comment.
186 if (Comment == RawComments.begin())
190 // Check that we actually have a non-member Doxygen comment.
191 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
194 // Decompose the end of the comment.
195 std::pair<FileID, unsigned> CommentEndDecomp
196 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
198 // If the comment and the declaration aren't in the same file, then they
200 if (DeclLocDecomp.first != CommentEndDecomp.first)
203 // Get the corresponding buffer.
204 bool Invalid = false;
205 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
210 // Extract text between the comment and declaration.
211 StringRef Text(Buffer + CommentEndDecomp.second,
212 DeclLocDecomp.second - CommentEndDecomp.second);
214 // There should be no other declarations or preprocessor directives between
215 // comment and declaration.
216 if (Text.find_first_of(",;{}#@") != StringRef::npos)
223 /// If we have a 'templated' declaration for a template, adjust 'D' to
224 /// refer to the actual template.
225 /// If we have an implicit instantiation, adjust 'D' to refer to template.
226 const Decl *adjustDeclToTemplate(const Decl *D) {
227 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
228 // Is this function declaration part of a function template?
229 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
232 // Nothing to do if function is not an implicit instantiation.
233 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
236 // Function is an implicit instantiation of a function template?
237 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
240 // Function is instantiated from a member definition of a class template?
241 if (const FunctionDecl *MemberDecl =
242 FD->getInstantiatedFromMemberFunction())
247 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
248 // Static data member is instantiated from a member definition of a class
250 if (VD->isStaticDataMember())
251 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
256 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
257 // Is this class declaration part of a class template?
258 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
261 // Class is an implicit instantiation of a class template or partial
263 if (const ClassTemplateSpecializationDecl *CTSD =
264 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
265 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
267 llvm::PointerUnion<ClassTemplateDecl *,
268 ClassTemplatePartialSpecializationDecl *>
269 PU = CTSD->getSpecializedTemplateOrPartial();
270 return PU.is<ClassTemplateDecl*>() ?
271 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
272 static_cast<const Decl*>(
273 PU.get<ClassTemplatePartialSpecializationDecl *>());
276 // Class is instantiated from a member definition of a class template?
277 if (const MemberSpecializationInfo *Info =
278 CRD->getMemberSpecializationInfo())
279 return Info->getInstantiatedFrom();
283 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
284 // Enum is instantiated from a member definition of a class template?
285 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
290 // FIXME: Adjust alias templates?
293 } // unnamed namespace
295 const RawComment *ASTContext::getRawCommentForAnyRedecl(
297 const Decl **OriginalDecl) const {
298 D = adjustDeclToTemplate(D);
300 // Check whether we have cached a comment for this declaration already.
302 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
303 RedeclComments.find(D);
304 if (Pos != RedeclComments.end()) {
305 const RawCommentAndCacheFlags &Raw = Pos->second;
306 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
308 *OriginalDecl = Raw.getOriginalDecl();
314 // Search for comments attached to declarations in the redeclaration chain.
315 const RawComment *RC = NULL;
316 const Decl *OriginalDeclForRC = NULL;
317 for (Decl::redecl_iterator I = D->redecls_begin(),
318 E = D->redecls_end();
320 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
321 RedeclComments.find(*I);
322 if (Pos != RedeclComments.end()) {
323 const RawCommentAndCacheFlags &Raw = Pos->second;
324 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
326 OriginalDeclForRC = Raw.getOriginalDecl();
330 RC = getRawCommentForDeclNoCache(*I);
331 OriginalDeclForRC = *I;
332 RawCommentAndCacheFlags Raw;
335 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
337 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
338 Raw.setOriginalDecl(*I);
339 RedeclComments[*I] = Raw;
345 // If we found a comment, it should be a documentation comment.
346 assert(!RC || RC->isDocumentation());
349 *OriginalDecl = OriginalDeclForRC;
351 // Update cache for every declaration in the redeclaration chain.
352 RawCommentAndCacheFlags Raw;
354 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
355 Raw.setOriginalDecl(OriginalDeclForRC);
357 for (Decl::redecl_iterator I = D->redecls_begin(),
358 E = D->redecls_end();
360 RawCommentAndCacheFlags &R = RedeclComments[*I];
361 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
368 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
369 SmallVectorImpl<const NamedDecl *> &Redeclared) {
370 const DeclContext *DC = ObjCMethod->getDeclContext();
371 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
372 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
375 // Add redeclared method here.
376 for (ObjCInterfaceDecl::known_extensions_iterator
377 Ext = ID->known_extensions_begin(),
378 ExtEnd = ID->known_extensions_end();
379 Ext != ExtEnd; ++Ext) {
380 if (ObjCMethodDecl *RedeclaredMethod =
381 Ext->getMethod(ObjCMethod->getSelector(),
382 ObjCMethod->isInstanceMethod()))
383 Redeclared.push_back(RedeclaredMethod);
388 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
389 const Decl *D) const {
390 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
391 ThisDeclInfo->CommentDecl = D;
392 ThisDeclInfo->IsFilled = false;
393 ThisDeclInfo->fill();
394 ThisDeclInfo->CommentDecl = FC->getDecl();
395 comments::FullComment *CFC =
396 new (*this) comments::FullComment(FC->getBlocks(),
402 comments::FullComment *ASTContext::getCommentForDecl(
404 const Preprocessor *PP) const {
405 D = adjustDeclToTemplate(D);
407 const Decl *Canonical = D->getCanonicalDecl();
408 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
409 ParsedComments.find(Canonical);
411 if (Pos != ParsedComments.end()) {
412 if (Canonical != D) {
413 comments::FullComment *FC = Pos->second;
414 comments::FullComment *CFC = cloneFullComment(FC, D);
420 const Decl *OriginalDecl;
422 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
424 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
425 SmallVector<const NamedDecl*, 8> Overridden;
426 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
427 if (OMD && OMD->isPropertyAccessor())
428 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
429 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
430 return cloneFullComment(FC, D);
432 addRedeclaredMethods(OMD, Overridden);
433 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
434 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
435 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
436 return cloneFullComment(FC, D);
438 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
439 // Attach any tag type's documentation to its typedef if latter
440 // does not have one of its own.
441 QualType QT = TD->getUnderlyingType();
442 if (const TagType *TT = QT->getAs<TagType>())
443 if (const Decl *TD = TT->getDecl())
444 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
445 return cloneFullComment(FC, D);
450 // If the RawComment was attached to other redeclaration of this Decl, we
451 // should parse the comment in context of that other Decl. This is important
452 // because comments can contain references to parameter names which can be
453 // different across redeclarations.
454 if (D != OriginalDecl)
455 return getCommentForDecl(OriginalDecl, PP);
457 comments::FullComment *FC = RC->parse(*this, PP, D);
458 ParsedComments[Canonical] = FC;
463 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
464 TemplateTemplateParmDecl *Parm) {
465 ID.AddInteger(Parm->getDepth());
466 ID.AddInteger(Parm->getPosition());
467 ID.AddBoolean(Parm->isParameterPack());
469 TemplateParameterList *Params = Parm->getTemplateParameters();
470 ID.AddInteger(Params->size());
471 for (TemplateParameterList::const_iterator P = Params->begin(),
472 PEnd = Params->end();
474 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
476 ID.AddBoolean(TTP->isParameterPack());
480 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
482 ID.AddBoolean(NTTP->isParameterPack());
483 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
484 if (NTTP->isExpandedParameterPack()) {
486 ID.AddInteger(NTTP->getNumExpansionTypes());
487 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
488 QualType T = NTTP->getExpansionType(I);
489 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
492 ID.AddBoolean(false);
496 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
502 TemplateTemplateParmDecl *
503 ASTContext::getCanonicalTemplateTemplateParmDecl(
504 TemplateTemplateParmDecl *TTP) const {
505 // Check if we already have a canonical template template parameter.
506 llvm::FoldingSetNodeID ID;
507 CanonicalTemplateTemplateParm::Profile(ID, TTP);
509 CanonicalTemplateTemplateParm *Canonical
510 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
512 return Canonical->getParam();
514 // Build a canonical template parameter list.
515 TemplateParameterList *Params = TTP->getTemplateParameters();
516 SmallVector<NamedDecl *, 4> CanonParams;
517 CanonParams.reserve(Params->size());
518 for (TemplateParameterList::const_iterator P = Params->begin(),
519 PEnd = Params->end();
521 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
522 CanonParams.push_back(
523 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
527 TTP->getIndex(), 0, false,
528 TTP->isParameterPack()));
529 else if (NonTypeTemplateParmDecl *NTTP
530 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
531 QualType T = getCanonicalType(NTTP->getType());
532 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
533 NonTypeTemplateParmDecl *Param;
534 if (NTTP->isExpandedParameterPack()) {
535 SmallVector<QualType, 2> ExpandedTypes;
536 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
537 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
538 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
539 ExpandedTInfos.push_back(
540 getTrivialTypeSourceInfo(ExpandedTypes.back()));
543 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
547 NTTP->getPosition(), 0,
550 ExpandedTypes.data(),
551 ExpandedTypes.size(),
552 ExpandedTInfos.data());
554 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
558 NTTP->getPosition(), 0,
560 NTTP->isParameterPack(),
563 CanonParams.push_back(Param);
566 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
567 cast<TemplateTemplateParmDecl>(*P)));
570 TemplateTemplateParmDecl *CanonTTP
571 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
572 SourceLocation(), TTP->getDepth(),
574 TTP->isParameterPack(),
576 TemplateParameterList::Create(*this, SourceLocation(),
582 // Get the new insert position for the node we care about.
583 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
584 assert(Canonical == 0 && "Shouldn't be in the map!");
587 // Create the canonical template template parameter entry.
588 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
589 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
593 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
594 if (!LangOpts.CPlusPlus) return 0;
596 switch (T.getCXXABI().getKind()) {
597 case TargetCXXABI::GenericARM:
598 case TargetCXXABI::iOS:
599 return CreateARMCXXABI(*this);
600 case TargetCXXABI::GenericAArch64: // Same as Itanium at this level
601 case TargetCXXABI::GenericItanium:
602 return CreateItaniumCXXABI(*this);
603 case TargetCXXABI::Microsoft:
604 return CreateMicrosoftCXXABI(*this);
606 llvm_unreachable("Invalid CXXABI type!");
609 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
610 const LangOptions &LOpts) {
611 if (LOpts.FakeAddressSpaceMap) {
612 // The fake address space map must have a distinct entry for each
613 // language-specific address space.
614 static const unsigned FakeAddrSpaceMap[] = {
617 3, // opencl_constant
622 return &FakeAddrSpaceMap;
624 return &T.getAddressSpaceMap();
628 ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
630 IdentifierTable &idents, SelectorTable &sels,
631 Builtin::Context &builtins,
632 unsigned size_reserve,
633 bool DelayInitialization)
634 : FunctionProtoTypes(this_()),
635 TemplateSpecializationTypes(this_()),
636 DependentTemplateSpecializationTypes(this_()),
637 SubstTemplateTemplateParmPacks(this_()),
638 GlobalNestedNameSpecifier(0),
639 Int128Decl(0), UInt128Decl(0),
640 BuiltinVaListDecl(0),
641 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
643 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
645 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
646 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
647 cudaConfigureCallDecl(0),
648 NullTypeSourceInfo(QualType()),
649 FirstLocalImport(), LastLocalImport(),
650 SourceMgr(SM), LangOpts(LOpts),
651 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
652 Idents(idents), Selectors(sels),
653 BuiltinInfo(builtins),
654 DeclarationNames(*this),
655 ExternalSource(0), Listener(0),
656 Comments(SM), CommentsLoaded(false),
657 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
659 UniqueBlockByRefTypeID(0)
661 if (size_reserve > 0) Types.reserve(size_reserve);
662 TUDecl = TranslationUnitDecl::Create(*this);
664 if (!DelayInitialization) {
665 assert(t && "No target supplied for ASTContext initialization");
666 InitBuiltinTypes(*t);
670 ASTContext::~ASTContext() {
671 // Release the DenseMaps associated with DeclContext objects.
672 // FIXME: Is this the ideal solution?
673 ReleaseDeclContextMaps();
675 // Call all of the deallocation functions.
676 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
677 Deallocations[I].first(Deallocations[I].second);
679 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
680 // because they can contain DenseMaps.
681 for (llvm::DenseMap<const ObjCContainerDecl*,
682 const ASTRecordLayout*>::iterator
683 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
684 // Increment in loop to prevent using deallocated memory.
685 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
688 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
689 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
690 // Increment in loop to prevent using deallocated memory.
691 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
695 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
696 AEnd = DeclAttrs.end();
698 A->second->~AttrVec();
701 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
702 Deallocations.push_back(std::make_pair(Callback, Data));
706 ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
707 ExternalSource.reset(Source.take());
710 void ASTContext::PrintStats() const {
711 llvm::errs() << "\n*** AST Context Stats:\n";
712 llvm::errs() << " " << Types.size() << " types total.\n";
714 unsigned counts[] = {
715 #define TYPE(Name, Parent) 0,
716 #define ABSTRACT_TYPE(Name, Parent)
717 #include "clang/AST/TypeNodes.def"
721 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
723 counts[(unsigned)T->getTypeClass()]++;
727 unsigned TotalBytes = 0;
728 #define TYPE(Name, Parent) \
730 llvm::errs() << " " << counts[Idx] << " " << #Name \
732 TotalBytes += counts[Idx] * sizeof(Name##Type); \
734 #define ABSTRACT_TYPE(Name, Parent)
735 #include "clang/AST/TypeNodes.def"
737 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
739 // Implicit special member functions.
740 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
741 << NumImplicitDefaultConstructors
742 << " implicit default constructors created\n";
743 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
744 << NumImplicitCopyConstructors
745 << " implicit copy constructors created\n";
746 if (getLangOpts().CPlusPlus)
747 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
748 << NumImplicitMoveConstructors
749 << " implicit move constructors created\n";
750 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
751 << NumImplicitCopyAssignmentOperators
752 << " implicit copy assignment operators created\n";
753 if (getLangOpts().CPlusPlus)
754 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
755 << NumImplicitMoveAssignmentOperators
756 << " implicit move assignment operators created\n";
757 llvm::errs() << NumImplicitDestructorsDeclared << "/"
758 << NumImplicitDestructors
759 << " implicit destructors created\n";
761 if (ExternalSource.get()) {
762 llvm::errs() << "\n";
763 ExternalSource->PrintStats();
766 BumpAlloc.PrintStats();
769 TypedefDecl *ASTContext::getInt128Decl() const {
771 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
772 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
773 getTranslationUnitDecl(),
776 &Idents.get("__int128_t"),
783 TypedefDecl *ASTContext::getUInt128Decl() const {
785 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
786 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
787 getTranslationUnitDecl(),
790 &Idents.get("__uint128_t"),
797 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
798 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
799 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
803 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
804 assert((!this->Target || this->Target == &Target) &&
805 "Incorrect target reinitialization");
806 assert(VoidTy.isNull() && "Context reinitialized?");
808 this->Target = &Target;
810 ABI.reset(createCXXABI(Target));
811 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
814 InitBuiltinType(VoidTy, BuiltinType::Void);
817 InitBuiltinType(BoolTy, BuiltinType::Bool);
819 if (LangOpts.CharIsSigned)
820 InitBuiltinType(CharTy, BuiltinType::Char_S);
822 InitBuiltinType(CharTy, BuiltinType::Char_U);
824 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
825 InitBuiltinType(ShortTy, BuiltinType::Short);
826 InitBuiltinType(IntTy, BuiltinType::Int);
827 InitBuiltinType(LongTy, BuiltinType::Long);
828 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
831 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
832 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
833 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
834 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
835 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
838 InitBuiltinType(FloatTy, BuiltinType::Float);
839 InitBuiltinType(DoubleTy, BuiltinType::Double);
840 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
842 // GNU extension, 128-bit integers.
843 InitBuiltinType(Int128Ty, BuiltinType::Int128);
844 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
846 if (LangOpts.CPlusPlus && LangOpts.WChar) { // C++ 3.9.1p5
847 if (TargetInfo::isTypeSigned(Target.getWCharType()))
848 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
849 else // -fshort-wchar makes wchar_t be unsigned.
850 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
851 } else // C99 (or C++ using -fno-wchar)
852 WCharTy = getFromTargetType(Target.getWCharType());
854 WIntTy = getFromTargetType(Target.getWIntType());
856 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
857 InitBuiltinType(Char16Ty, BuiltinType::Char16);
859 Char16Ty = getFromTargetType(Target.getChar16Type());
861 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
862 InitBuiltinType(Char32Ty, BuiltinType::Char32);
864 Char32Ty = getFromTargetType(Target.getChar32Type());
866 // Placeholder type for type-dependent expressions whose type is
867 // completely unknown. No code should ever check a type against
868 // DependentTy and users should never see it; however, it is here to
869 // help diagnose failures to properly check for type-dependent
871 InitBuiltinType(DependentTy, BuiltinType::Dependent);
873 // Placeholder type for functions.
874 InitBuiltinType(OverloadTy, BuiltinType::Overload);
876 // Placeholder type for bound members.
877 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
879 // Placeholder type for pseudo-objects.
880 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
882 // "any" type; useful for debugger-like clients.
883 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
885 // Placeholder type for unbridged ARC casts.
886 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
888 // Placeholder type for builtin functions.
889 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
892 FloatComplexTy = getComplexType(FloatTy);
893 DoubleComplexTy = getComplexType(DoubleTy);
894 LongDoubleComplexTy = getComplexType(LongDoubleTy);
896 // Builtin types for 'id', 'Class', and 'SEL'.
897 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
898 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
899 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
901 if (LangOpts.OpenCL) {
902 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
903 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
904 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
905 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
906 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
907 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
909 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
910 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
913 // Builtin type for __objc_yes and __objc_no
914 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
915 SignedCharTy : BoolTy);
917 ObjCConstantStringType = QualType();
919 ObjCSuperType = QualType();
922 VoidPtrTy = getPointerType(VoidTy);
924 // nullptr type (C++0x 2.14.7)
925 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
927 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
928 InitBuiltinType(HalfTy, BuiltinType::Half);
930 // Builtin type used to help define __builtin_va_list.
931 VaListTagTy = QualType();
934 DiagnosticsEngine &ASTContext::getDiagnostics() const {
935 return SourceMgr.getDiagnostics();
938 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
939 AttrVec *&Result = DeclAttrs[D];
941 void *Mem = Allocate(sizeof(AttrVec));
942 Result = new (Mem) AttrVec;
948 /// \brief Erase the attributes corresponding to the given declaration.
949 void ASTContext::eraseDeclAttrs(const Decl *D) {
950 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
951 if (Pos != DeclAttrs.end()) {
952 Pos->second->~AttrVec();
953 DeclAttrs.erase(Pos);
957 MemberSpecializationInfo *
958 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
959 assert(Var->isStaticDataMember() && "Not a static data member");
960 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
961 = InstantiatedFromStaticDataMember.find(Var);
962 if (Pos == InstantiatedFromStaticDataMember.end())
969 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
970 TemplateSpecializationKind TSK,
971 SourceLocation PointOfInstantiation) {
972 assert(Inst->isStaticDataMember() && "Not a static data member");
973 assert(Tmpl->isStaticDataMember() && "Not a static data member");
974 assert(!InstantiatedFromStaticDataMember[Inst] &&
975 "Already noted what static data member was instantiated from");
976 InstantiatedFromStaticDataMember[Inst]
977 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
980 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
981 const FunctionDecl *FD){
982 assert(FD && "Specialization is 0");
983 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
984 = ClassScopeSpecializationPattern.find(FD);
985 if (Pos == ClassScopeSpecializationPattern.end())
991 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
992 FunctionDecl *Pattern) {
993 assert(FD && "Specialization is 0");
994 assert(Pattern && "Class scope specialization pattern is 0");
995 ClassScopeSpecializationPattern[FD] = Pattern;
999 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
1000 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
1001 = InstantiatedFromUsingDecl.find(UUD);
1002 if (Pos == InstantiatedFromUsingDecl.end())
1009 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1010 assert((isa<UsingDecl>(Pattern) ||
1011 isa<UnresolvedUsingValueDecl>(Pattern) ||
1012 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1013 "pattern decl is not a using decl");
1014 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1015 InstantiatedFromUsingDecl[Inst] = Pattern;
1019 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1020 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1021 = InstantiatedFromUsingShadowDecl.find(Inst);
1022 if (Pos == InstantiatedFromUsingShadowDecl.end())
1029 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1030 UsingShadowDecl *Pattern) {
1031 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1032 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1035 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1036 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1037 = InstantiatedFromUnnamedFieldDecl.find(Field);
1038 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1044 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1046 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1047 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1048 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1049 "Already noted what unnamed field was instantiated from");
1051 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1054 bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
1055 const FieldDecl *LastFD) const {
1056 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
1057 FD->getBitWidthValue(*this) == 0);
1060 bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
1061 const FieldDecl *LastFD) const {
1062 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
1063 FD->getBitWidthValue(*this) == 0 &&
1064 LastFD->getBitWidthValue(*this) != 0);
1067 bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
1068 const FieldDecl *LastFD) const {
1069 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
1070 FD->getBitWidthValue(*this) &&
1071 LastFD->getBitWidthValue(*this));
1074 bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
1075 const FieldDecl *LastFD) const {
1076 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
1077 LastFD->getBitWidthValue(*this));
1080 bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
1081 const FieldDecl *LastFD) const {
1082 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
1083 FD->getBitWidthValue(*this));
1086 ASTContext::overridden_cxx_method_iterator
1087 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1088 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1089 = OverriddenMethods.find(Method->getCanonicalDecl());
1090 if (Pos == OverriddenMethods.end())
1093 return Pos->second.begin();
1096 ASTContext::overridden_cxx_method_iterator
1097 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1098 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1099 = OverriddenMethods.find(Method->getCanonicalDecl());
1100 if (Pos == OverriddenMethods.end())
1103 return Pos->second.end();
1107 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1108 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1109 = OverriddenMethods.find(Method->getCanonicalDecl());
1110 if (Pos == OverriddenMethods.end())
1113 return Pos->second.size();
1116 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1117 const CXXMethodDecl *Overridden) {
1118 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1119 OverriddenMethods[Method].push_back(Overridden);
1122 void ASTContext::getOverriddenMethods(
1124 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1127 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1128 Overridden.append(CXXMethod->begin_overridden_methods(),
1129 CXXMethod->end_overridden_methods());
1133 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1137 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1138 Method->getOverriddenMethods(OverDecls);
1139 Overridden.append(OverDecls.begin(), OverDecls.end());
1142 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1143 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1144 assert(!Import->isFromASTFile() && "Non-local import declaration");
1145 if (!FirstLocalImport) {
1146 FirstLocalImport = Import;
1147 LastLocalImport = Import;
1151 LastLocalImport->NextLocalImport = Import;
1152 LastLocalImport = Import;
1155 //===----------------------------------------------------------------------===//
1156 // Type Sizing and Analysis
1157 //===----------------------------------------------------------------------===//
1159 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1160 /// scalar floating point type.
1161 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1162 const BuiltinType *BT = T->getAs<BuiltinType>();
1163 assert(BT && "Not a floating point type!");
1164 switch (BT->getKind()) {
1165 default: llvm_unreachable("Not a floating point type!");
1166 case BuiltinType::Half: return Target->getHalfFormat();
1167 case BuiltinType::Float: return Target->getFloatFormat();
1168 case BuiltinType::Double: return Target->getDoubleFormat();
1169 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1173 /// getDeclAlign - Return a conservative estimate of the alignment of the
1174 /// specified decl. Note that bitfields do not have a valid alignment, so
1175 /// this method will assert on them.
1176 /// If @p RefAsPointee, references are treated like their underlying type
1177 /// (for alignof), else they're treated like pointers (for CodeGen).
1178 CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
1179 unsigned Align = Target->getCharWidth();
1181 bool UseAlignAttrOnly = false;
1182 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1183 Align = AlignFromAttr;
1185 // __attribute__((aligned)) can increase or decrease alignment
1186 // *except* on a struct or struct member, where it only increases
1187 // alignment unless 'packed' is also specified.
1189 // It is an error for alignas to decrease alignment, so we can
1190 // ignore that possibility; Sema should diagnose it.
1191 if (isa<FieldDecl>(D)) {
1192 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1193 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1195 UseAlignAttrOnly = true;
1198 else if (isa<FieldDecl>(D))
1200 D->hasAttr<PackedAttr>() ||
1201 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1203 // If we're using the align attribute only, just ignore everything
1204 // else about the declaration and its type.
1205 if (UseAlignAttrOnly) {
1208 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1209 QualType T = VD->getType();
1210 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
1212 T = RT->getPointeeType();
1214 T = getPointerType(RT->getPointeeType());
1216 if (!T->isIncompleteType() && !T->isFunctionType()) {
1217 // Adjust alignments of declarations with array type by the
1218 // large-array alignment on the target.
1219 unsigned MinWidth = Target->getLargeArrayMinWidth();
1220 const ArrayType *arrayType;
1221 if (MinWidth && (arrayType = getAsArrayType(T))) {
1222 if (isa<VariableArrayType>(arrayType))
1223 Align = std::max(Align, Target->getLargeArrayAlign());
1224 else if (isa<ConstantArrayType>(arrayType) &&
1225 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1226 Align = std::max(Align, Target->getLargeArrayAlign());
1228 // Walk through any array types while we're at it.
1229 T = getBaseElementType(arrayType);
1231 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1234 // Fields can be subject to extra alignment constraints, like if
1235 // the field is packed, the struct is packed, or the struct has a
1236 // a max-field-alignment constraint (#pragma pack). So calculate
1237 // the actual alignment of the field within the struct, and then
1238 // (as we're expected to) constrain that by the alignment of the type.
1239 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
1240 // So calculate the alignment of the field.
1241 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
1243 // Start with the record's overall alignment.
1244 unsigned fieldAlign = toBits(layout.getAlignment());
1246 // Use the GCD of that and the offset within the record.
1247 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
1249 // Alignment is always a power of 2, so the GCD will be a power of 2,
1250 // which means we get to do this crazy thing instead of Euclid's.
1251 uint64_t lowBitOfOffset = offset & (~offset + 1);
1252 if (lowBitOfOffset < fieldAlign)
1253 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
1256 Align = std::min(Align, fieldAlign);
1260 return toCharUnitsFromBits(Align);
1263 // getTypeInfoDataSizeInChars - Return the size of a type, in
1264 // chars. If the type is a record, its data size is returned. This is
1265 // the size of the memcpy that's performed when assigning this type
1266 // using a trivial copy/move assignment operator.
1267 std::pair<CharUnits, CharUnits>
1268 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1269 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1271 // In C++, objects can sometimes be allocated into the tail padding
1272 // of a base-class subobject. We decide whether that's possible
1273 // during class layout, so here we can just trust the layout results.
1274 if (getLangOpts().CPlusPlus) {
1275 if (const RecordType *RT = T->getAs<RecordType>()) {
1276 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1277 sizeAndAlign.first = layout.getDataSize();
1281 return sizeAndAlign;
1284 std::pair<CharUnits, CharUnits>
1285 ASTContext::getTypeInfoInChars(const Type *T) const {
1286 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
1287 return std::make_pair(toCharUnitsFromBits(Info.first),
1288 toCharUnitsFromBits(Info.second));
1291 std::pair<CharUnits, CharUnits>
1292 ASTContext::getTypeInfoInChars(QualType T) const {
1293 return getTypeInfoInChars(T.getTypePtr());
1296 std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
1297 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
1298 if (it != MemoizedTypeInfo.end())
1301 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
1302 MemoizedTypeInfo.insert(std::make_pair(T, Info));
1306 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1307 /// method does not work on incomplete types.
1309 /// FIXME: Pointers into different addr spaces could have different sizes and
1310 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1311 /// should take a QualType, &c.
1312 std::pair<uint64_t, unsigned>
1313 ASTContext::getTypeInfoImpl(const Type *T) const {
1316 switch (T->getTypeClass()) {
1317 #define TYPE(Class, Base)
1318 #define ABSTRACT_TYPE(Class, Base)
1319 #define NON_CANONICAL_TYPE(Class, Base)
1320 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1321 #include "clang/AST/TypeNodes.def"
1322 llvm_unreachable("Should not see dependent types");
1324 case Type::FunctionNoProto:
1325 case Type::FunctionProto:
1326 // GCC extension: alignof(function) = 32 bits
1331 case Type::IncompleteArray:
1332 case Type::VariableArray:
1334 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1337 case Type::ConstantArray: {
1338 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1340 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
1341 uint64_t Size = CAT->getSize().getZExtValue();
1342 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
1343 "Overflow in array type bit size evaluation");
1344 Width = EltInfo.first*Size;
1345 Align = EltInfo.second;
1346 Width = llvm::RoundUpToAlignment(Width, Align);
1349 case Type::ExtVector:
1350 case Type::Vector: {
1351 const VectorType *VT = cast<VectorType>(T);
1352 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
1353 Width = EltInfo.first*VT->getNumElements();
1355 // If the alignment is not a power of 2, round up to the next power of 2.
1356 // This happens for non-power-of-2 length vectors.
1357 if (Align & (Align-1)) {
1358 Align = llvm::NextPowerOf2(Align);
1359 Width = llvm::RoundUpToAlignment(Width, Align);
1361 // Adjust the alignment based on the target max.
1362 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1363 if (TargetVectorAlign && TargetVectorAlign < Align)
1364 Align = TargetVectorAlign;
1369 switch (cast<BuiltinType>(T)->getKind()) {
1370 default: llvm_unreachable("Unknown builtin type!");
1371 case BuiltinType::Void:
1372 // GCC extension: alignof(void) = 8 bits.
1377 case BuiltinType::Bool:
1378 Width = Target->getBoolWidth();
1379 Align = Target->getBoolAlign();
1381 case BuiltinType::Char_S:
1382 case BuiltinType::Char_U:
1383 case BuiltinType::UChar:
1384 case BuiltinType::SChar:
1385 Width = Target->getCharWidth();
1386 Align = Target->getCharAlign();
1388 case BuiltinType::WChar_S:
1389 case BuiltinType::WChar_U:
1390 Width = Target->getWCharWidth();
1391 Align = Target->getWCharAlign();
1393 case BuiltinType::Char16:
1394 Width = Target->getChar16Width();
1395 Align = Target->getChar16Align();
1397 case BuiltinType::Char32:
1398 Width = Target->getChar32Width();
1399 Align = Target->getChar32Align();
1401 case BuiltinType::UShort:
1402 case BuiltinType::Short:
1403 Width = Target->getShortWidth();
1404 Align = Target->getShortAlign();
1406 case BuiltinType::UInt:
1407 case BuiltinType::Int:
1408 Width = Target->getIntWidth();
1409 Align = Target->getIntAlign();
1411 case BuiltinType::ULong:
1412 case BuiltinType::Long:
1413 Width = Target->getLongWidth();
1414 Align = Target->getLongAlign();
1416 case BuiltinType::ULongLong:
1417 case BuiltinType::LongLong:
1418 Width = Target->getLongLongWidth();
1419 Align = Target->getLongLongAlign();
1421 case BuiltinType::Int128:
1422 case BuiltinType::UInt128:
1424 Align = 128; // int128_t is 128-bit aligned on all targets.
1426 case BuiltinType::Half:
1427 Width = Target->getHalfWidth();
1428 Align = Target->getHalfAlign();
1430 case BuiltinType::Float:
1431 Width = Target->getFloatWidth();
1432 Align = Target->getFloatAlign();
1434 case BuiltinType::Double:
1435 Width = Target->getDoubleWidth();
1436 Align = Target->getDoubleAlign();
1438 case BuiltinType::LongDouble:
1439 Width = Target->getLongDoubleWidth();
1440 Align = Target->getLongDoubleAlign();
1442 case BuiltinType::NullPtr:
1443 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1444 Align = Target->getPointerAlign(0); // == sizeof(void*)
1446 case BuiltinType::ObjCId:
1447 case BuiltinType::ObjCClass:
1448 case BuiltinType::ObjCSel:
1449 Width = Target->getPointerWidth(0);
1450 Align = Target->getPointerAlign(0);
1452 case BuiltinType::OCLSampler:
1453 // Samplers are modeled as integers.
1454 Width = Target->getIntWidth();
1455 Align = Target->getIntAlign();
1457 case BuiltinType::OCLEvent:
1458 case BuiltinType::OCLImage1d:
1459 case BuiltinType::OCLImage1dArray:
1460 case BuiltinType::OCLImage1dBuffer:
1461 case BuiltinType::OCLImage2d:
1462 case BuiltinType::OCLImage2dArray:
1463 case BuiltinType::OCLImage3d:
1464 // Currently these types are pointers to opaque types.
1465 Width = Target->getPointerWidth(0);
1466 Align = Target->getPointerAlign(0);
1470 case Type::ObjCObjectPointer:
1471 Width = Target->getPointerWidth(0);
1472 Align = Target->getPointerAlign(0);
1474 case Type::BlockPointer: {
1475 unsigned AS = getTargetAddressSpace(
1476 cast<BlockPointerType>(T)->getPointeeType());
1477 Width = Target->getPointerWidth(AS);
1478 Align = Target->getPointerAlign(AS);
1481 case Type::LValueReference:
1482 case Type::RValueReference: {
1483 // alignof and sizeof should never enter this code path here, so we go
1484 // the pointer route.
1485 unsigned AS = getTargetAddressSpace(
1486 cast<ReferenceType>(T)->getPointeeType());
1487 Width = Target->getPointerWidth(AS);
1488 Align = Target->getPointerAlign(AS);
1491 case Type::Pointer: {
1492 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1493 Width = Target->getPointerWidth(AS);
1494 Align = Target->getPointerAlign(AS);
1497 case Type::MemberPointer: {
1498 const MemberPointerType *MPT = cast<MemberPointerType>(T);
1499 llvm::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1502 case Type::Complex: {
1503 // Complex types have the same alignment as their elements, but twice the
1505 std::pair<uint64_t, unsigned> EltInfo =
1506 getTypeInfo(cast<ComplexType>(T)->getElementType());
1507 Width = EltInfo.first*2;
1508 Align = EltInfo.second;
1511 case Type::ObjCObject:
1512 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1513 case Type::ObjCInterface: {
1514 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1515 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1516 Width = toBits(Layout.getSize());
1517 Align = toBits(Layout.getAlignment());
1522 const TagType *TT = cast<TagType>(T);
1524 if (TT->getDecl()->isInvalidDecl()) {
1530 if (const EnumType *ET = dyn_cast<EnumType>(TT))
1531 return getTypeInfo(ET->getDecl()->getIntegerType());
1533 const RecordType *RT = cast<RecordType>(TT);
1534 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
1535 Width = toBits(Layout.getSize());
1536 Align = toBits(Layout.getAlignment());
1540 case Type::SubstTemplateTypeParm:
1541 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1542 getReplacementType().getTypePtr());
1545 const AutoType *A = cast<AutoType>(T);
1546 assert(A->isDeduced() && "Cannot request the size of a dependent type");
1547 return getTypeInfo(A->getDeducedType().getTypePtr());
1551 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1553 case Type::Typedef: {
1554 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1555 std::pair<uint64_t, unsigned> Info
1556 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1557 // If the typedef has an aligned attribute on it, it overrides any computed
1558 // alignment we have. This violates the GCC documentation (which says that
1559 // attribute(aligned) can only round up) but matches its implementation.
1560 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1563 Align = Info.second;
1568 case Type::TypeOfExpr:
1569 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1573 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1575 case Type::Decltype:
1576 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1579 case Type::UnaryTransform:
1580 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1582 case Type::Elaborated:
1583 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1585 case Type::Attributed:
1587 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1589 case Type::TemplateSpecialization: {
1590 assert(getCanonicalType(T) != T &&
1591 "Cannot request the size of a dependent type");
1592 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1593 // A type alias template specialization may refer to a typedef with the
1594 // aligned attribute on it.
1595 if (TST->isTypeAlias())
1596 return getTypeInfo(TST->getAliasedType().getTypePtr());
1598 return getTypeInfo(getCanonicalType(T));
1601 case Type::Atomic: {
1602 // Start with the base type information.
1603 std::pair<uint64_t, unsigned> Info
1604 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1606 Align = Info.second;
1608 // If the size of the type doesn't exceed the platform's max
1609 // atomic promotion width, make the size and alignment more
1610 // favorable to atomic operations:
1611 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1612 // Round the size up to a power of 2.
1613 if (!llvm::isPowerOf2_64(Width))
1614 Width = llvm::NextPowerOf2(Width);
1616 // Set the alignment equal to the size.
1617 Align = static_cast<unsigned>(Width);
1623 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1624 return std::make_pair(Width, Align);
1627 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1628 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1629 return CharUnits::fromQuantity(BitSize / getCharWidth());
1632 /// toBits - Convert a size in characters to a size in characters.
1633 int64_t ASTContext::toBits(CharUnits CharSize) const {
1634 return CharSize.getQuantity() * getCharWidth();
1637 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1638 /// This method does not work on incomplete types.
1639 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1640 return toCharUnitsFromBits(getTypeSize(T));
1642 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1643 return toCharUnitsFromBits(getTypeSize(T));
1646 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1647 /// characters. This method does not work on incomplete types.
1648 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1649 return toCharUnitsFromBits(getTypeAlign(T));
1651 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1652 return toCharUnitsFromBits(getTypeAlign(T));
1655 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1656 /// type for the current target in bits. This can be different than the ABI
1657 /// alignment in cases where it is beneficial for performance to overalign
1659 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1660 unsigned ABIAlign = getTypeAlign(T);
1662 // Double and long long should be naturally aligned if possible.
1663 if (const ComplexType* CT = T->getAs<ComplexType>())
1664 T = CT->getElementType().getTypePtr();
1665 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1666 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1667 T->isSpecificBuiltinType(BuiltinType::ULongLong))
1668 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1673 /// DeepCollectObjCIvars -
1674 /// This routine first collects all declared, but not synthesized, ivars in
1675 /// super class and then collects all ivars, including those synthesized for
1676 /// current class. This routine is used for implementation of current class
1677 /// when all ivars, declared and synthesized are known.
1679 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1681 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1682 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1683 DeepCollectObjCIvars(SuperClass, false, Ivars);
1685 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1686 E = OI->ivar_end(); I != E; ++I)
1687 Ivars.push_back(*I);
1689 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1690 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1691 Iv= Iv->getNextIvar())
1692 Ivars.push_back(Iv);
1696 /// CollectInheritedProtocols - Collect all protocols in current class and
1697 /// those inherited by it.
1698 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1699 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1700 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1701 // We can use protocol_iterator here instead of
1702 // all_referenced_protocol_iterator since we are walking all categories.
1703 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1704 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
1705 ObjCProtocolDecl *Proto = (*P);
1706 Protocols.insert(Proto->getCanonicalDecl());
1707 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1708 PE = Proto->protocol_end(); P != PE; ++P) {
1709 Protocols.insert((*P)->getCanonicalDecl());
1710 CollectInheritedProtocols(*P, Protocols);
1714 // Categories of this Interface.
1715 for (ObjCInterfaceDecl::visible_categories_iterator
1716 Cat = OI->visible_categories_begin(),
1717 CatEnd = OI->visible_categories_end();
1718 Cat != CatEnd; ++Cat) {
1719 CollectInheritedProtocols(*Cat, Protocols);
1722 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1724 CollectInheritedProtocols(SD, Protocols);
1725 SD = SD->getSuperClass();
1727 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1728 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
1729 PE = OC->protocol_end(); P != PE; ++P) {
1730 ObjCProtocolDecl *Proto = (*P);
1731 Protocols.insert(Proto->getCanonicalDecl());
1732 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1733 PE = Proto->protocol_end(); P != PE; ++P)
1734 CollectInheritedProtocols(*P, Protocols);
1736 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1737 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1738 PE = OP->protocol_end(); P != PE; ++P) {
1739 ObjCProtocolDecl *Proto = (*P);
1740 Protocols.insert(Proto->getCanonicalDecl());
1741 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1742 PE = Proto->protocol_end(); P != PE; ++P)
1743 CollectInheritedProtocols(*P, Protocols);
1748 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1750 // Count ivars declared in class extension.
1751 for (ObjCInterfaceDecl::known_extensions_iterator
1752 Ext = OI->known_extensions_begin(),
1753 ExtEnd = OI->known_extensions_end();
1754 Ext != ExtEnd; ++Ext) {
1755 count += Ext->ivar_size();
1758 // Count ivar defined in this class's implementation. This
1759 // includes synthesized ivars.
1760 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1761 count += ImplDecl->ivar_size();
1766 bool ASTContext::isSentinelNullExpr(const Expr *E) {
1770 // nullptr_t is always treated as null.
1771 if (E->getType()->isNullPtrType()) return true;
1773 if (E->getType()->isAnyPointerType() &&
1774 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1775 Expr::NPC_ValueDependentIsNull))
1778 // Unfortunately, __null has type 'int'.
1779 if (isa<GNUNullExpr>(E)) return true;
1784 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1785 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1786 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1787 I = ObjCImpls.find(D);
1788 if (I != ObjCImpls.end())
1789 return cast<ObjCImplementationDecl>(I->second);
1792 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1793 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1794 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1795 I = ObjCImpls.find(D);
1796 if (I != ObjCImpls.end())
1797 return cast<ObjCCategoryImplDecl>(I->second);
1801 /// \brief Set the implementation of ObjCInterfaceDecl.
1802 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1803 ObjCImplementationDecl *ImplD) {
1804 assert(IFaceD && ImplD && "Passed null params");
1805 ObjCImpls[IFaceD] = ImplD;
1807 /// \brief Set the implementation of ObjCCategoryDecl.
1808 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1809 ObjCCategoryImplDecl *ImplD) {
1810 assert(CatD && ImplD && "Passed null params");
1811 ObjCImpls[CatD] = ImplD;
1814 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
1815 const NamedDecl *ND) const {
1816 if (const ObjCInterfaceDecl *ID =
1817 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1819 if (const ObjCCategoryDecl *CD =
1820 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1821 return CD->getClassInterface();
1822 if (const ObjCImplDecl *IMD =
1823 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1824 return IMD->getClassInterface();
1829 /// \brief Get the copy initialization expression of VarDecl,or NULL if
1831 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1832 assert(VD && "Passed null params");
1833 assert(VD->hasAttr<BlocksAttr>() &&
1834 "getBlockVarCopyInits - not __block var");
1835 llvm::DenseMap<const VarDecl*, Expr*>::iterator
1836 I = BlockVarCopyInits.find(VD);
1837 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1840 /// \brief Set the copy inialization expression of a block var decl.
1841 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1842 assert(VD && Init && "Passed null params");
1843 assert(VD->hasAttr<BlocksAttr>() &&
1844 "setBlockVarCopyInits - not __block var");
1845 BlockVarCopyInits[VD] = Init;
1848 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1849 unsigned DataSize) const {
1851 DataSize = TypeLoc::getFullDataSizeForType(T);
1853 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1854 "incorrect data size provided to CreateTypeSourceInfo!");
1856 TypeSourceInfo *TInfo =
1857 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1858 new (TInfo) TypeSourceInfo(T);
1862 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1863 SourceLocation L) const {
1864 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1865 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1869 const ASTRecordLayout &
1870 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1871 return getObjCLayout(D, 0);
1874 const ASTRecordLayout &
1875 ASTContext::getASTObjCImplementationLayout(
1876 const ObjCImplementationDecl *D) const {
1877 return getObjCLayout(D->getClassInterface(), D);
1880 //===----------------------------------------------------------------------===//
1881 // Type creation/memoization methods
1882 //===----------------------------------------------------------------------===//
1885 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1886 unsigned fastQuals = quals.getFastQualifiers();
1887 quals.removeFastQualifiers();
1889 // Check if we've already instantiated this type.
1890 llvm::FoldingSetNodeID ID;
1891 ExtQuals::Profile(ID, baseType, quals);
1892 void *insertPos = 0;
1893 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1894 assert(eq->getQualifiers() == quals);
1895 return QualType(eq, fastQuals);
1898 // If the base type is not canonical, make the appropriate canonical type.
1900 if (!baseType->isCanonicalUnqualified()) {
1901 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1902 canonSplit.Quals.addConsistentQualifiers(quals);
1903 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
1905 // Re-find the insert position.
1906 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1909 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1910 ExtQualNodes.InsertNode(eq, insertPos);
1911 return QualType(eq, fastQuals);
1915 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
1916 QualType CanT = getCanonicalType(T);
1917 if (CanT.getAddressSpace() == AddressSpace)
1920 // If we are composing extended qualifiers together, merge together
1921 // into one ExtQuals node.
1922 QualifierCollector Quals;
1923 const Type *TypeNode = Quals.strip(T);
1925 // If this type already has an address space specified, it cannot get
1927 assert(!Quals.hasAddressSpace() &&
1928 "Type cannot be in multiple addr spaces!");
1929 Quals.addAddressSpace(AddressSpace);
1931 return getExtQualType(TypeNode, Quals);
1934 QualType ASTContext::getObjCGCQualType(QualType T,
1935 Qualifiers::GC GCAttr) const {
1936 QualType CanT = getCanonicalType(T);
1937 if (CanT.getObjCGCAttr() == GCAttr)
1940 if (const PointerType *ptr = T->getAs<PointerType>()) {
1941 QualType Pointee = ptr->getPointeeType();
1942 if (Pointee->isAnyPointerType()) {
1943 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1944 return getPointerType(ResultType);
1948 // If we are composing extended qualifiers together, merge together
1949 // into one ExtQuals node.
1950 QualifierCollector Quals;
1951 const Type *TypeNode = Quals.strip(T);
1953 // If this type already has an ObjCGC specified, it cannot get
1955 assert(!Quals.hasObjCGCAttr() &&
1956 "Type cannot have multiple ObjCGCs!");
1957 Quals.addObjCGCAttr(GCAttr);
1959 return getExtQualType(TypeNode, Quals);
1962 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1963 FunctionType::ExtInfo Info) {
1964 if (T->getExtInfo() == Info)
1968 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1969 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1971 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1972 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1974 Result = getFunctionType(FPT->getResultType(),
1975 ArrayRef<QualType>(FPT->arg_type_begin(),
1980 return cast<FunctionType>(Result.getTypePtr());
1983 /// getComplexType - Return the uniqued reference to the type for a complex
1984 /// number with the specified element type.
1985 QualType ASTContext::getComplexType(QualType T) const {
1986 // Unique pointers, to guarantee there is only one pointer of a particular
1988 llvm::FoldingSetNodeID ID;
1989 ComplexType::Profile(ID, T);
1991 void *InsertPos = 0;
1992 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1993 return QualType(CT, 0);
1995 // If the pointee type isn't canonical, this won't be a canonical type either,
1996 // so fill in the canonical type field.
1998 if (!T.isCanonical()) {
1999 Canonical = getComplexType(getCanonicalType(T));
2001 // Get the new insert position for the node we care about.
2002 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2003 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2005 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2006 Types.push_back(New);
2007 ComplexTypes.InsertNode(New, InsertPos);
2008 return QualType(New, 0);
2011 /// getPointerType - Return the uniqued reference to the type for a pointer to
2012 /// the specified type.
2013 QualType ASTContext::getPointerType(QualType T) const {
2014 // Unique pointers, to guarantee there is only one pointer of a particular
2016 llvm::FoldingSetNodeID ID;
2017 PointerType::Profile(ID, T);
2019 void *InsertPos = 0;
2020 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2021 return QualType(PT, 0);
2023 // If the pointee type isn't canonical, this won't be a canonical type either,
2024 // so fill in the canonical type field.
2026 if (!T.isCanonical()) {
2027 Canonical = getPointerType(getCanonicalType(T));
2029 // Get the new insert position for the node we care about.
2030 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2031 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2033 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2034 Types.push_back(New);
2035 PointerTypes.InsertNode(New, InsertPos);
2036 return QualType(New, 0);
2039 /// getBlockPointerType - Return the uniqued reference to the type for
2040 /// a pointer to the specified block.
2041 QualType ASTContext::getBlockPointerType(QualType T) const {
2042 assert(T->isFunctionType() && "block of function types only");
2043 // Unique pointers, to guarantee there is only one block of a particular
2045 llvm::FoldingSetNodeID ID;
2046 BlockPointerType::Profile(ID, T);
2048 void *InsertPos = 0;
2049 if (BlockPointerType *PT =
2050 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2051 return QualType(PT, 0);
2053 // If the block pointee type isn't canonical, this won't be a canonical
2054 // type either so fill in the canonical type field.
2056 if (!T.isCanonical()) {
2057 Canonical = getBlockPointerType(getCanonicalType(T));
2059 // Get the new insert position for the node we care about.
2060 BlockPointerType *NewIP =
2061 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2062 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2064 BlockPointerType *New
2065 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2066 Types.push_back(New);
2067 BlockPointerTypes.InsertNode(New, InsertPos);
2068 return QualType(New, 0);
2071 /// getLValueReferenceType - Return the uniqued reference to the type for an
2072 /// lvalue reference to the specified type.
2074 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2075 assert(getCanonicalType(T) != OverloadTy &&
2076 "Unresolved overloaded function type");
2078 // Unique pointers, to guarantee there is only one pointer of a particular
2080 llvm::FoldingSetNodeID ID;
2081 ReferenceType::Profile(ID, T, SpelledAsLValue);
2083 void *InsertPos = 0;
2084 if (LValueReferenceType *RT =
2085 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2086 return QualType(RT, 0);
2088 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2090 // If the referencee type isn't canonical, this won't be a canonical type
2091 // either, so fill in the canonical type field.
2093 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2094 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2095 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2097 // Get the new insert position for the node we care about.
2098 LValueReferenceType *NewIP =
2099 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2100 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2103 LValueReferenceType *New
2104 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2106 Types.push_back(New);
2107 LValueReferenceTypes.InsertNode(New, InsertPos);
2109 return QualType(New, 0);
2112 /// getRValueReferenceType - Return the uniqued reference to the type for an
2113 /// rvalue reference to the specified type.
2114 QualType ASTContext::getRValueReferenceType(QualType T) const {
2115 // Unique pointers, to guarantee there is only one pointer of a particular
2117 llvm::FoldingSetNodeID ID;
2118 ReferenceType::Profile(ID, T, false);
2120 void *InsertPos = 0;
2121 if (RValueReferenceType *RT =
2122 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2123 return QualType(RT, 0);
2125 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2127 // If the referencee type isn't canonical, this won't be a canonical type
2128 // either, so fill in the canonical type field.
2130 if (InnerRef || !T.isCanonical()) {
2131 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2132 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2134 // Get the new insert position for the node we care about.
2135 RValueReferenceType *NewIP =
2136 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2137 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2140 RValueReferenceType *New
2141 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2142 Types.push_back(New);
2143 RValueReferenceTypes.InsertNode(New, InsertPos);
2144 return QualType(New, 0);
2147 /// getMemberPointerType - Return the uniqued reference to the type for a
2148 /// member pointer to the specified type, in the specified class.
2149 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2150 // Unique pointers, to guarantee there is only one pointer of a particular
2152 llvm::FoldingSetNodeID ID;
2153 MemberPointerType::Profile(ID, T, Cls);
2155 void *InsertPos = 0;
2156 if (MemberPointerType *PT =
2157 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2158 return QualType(PT, 0);
2160 // If the pointee or class type isn't canonical, this won't be a canonical
2161 // type either, so fill in the canonical type field.
2163 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2164 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2166 // Get the new insert position for the node we care about.
2167 MemberPointerType *NewIP =
2168 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2169 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2171 MemberPointerType *New
2172 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2173 Types.push_back(New);
2174 MemberPointerTypes.InsertNode(New, InsertPos);
2175 return QualType(New, 0);
2178 /// getConstantArrayType - Return the unique reference to the type for an
2179 /// array of the specified element type.
2180 QualType ASTContext::getConstantArrayType(QualType EltTy,
2181 const llvm::APInt &ArySizeIn,
2182 ArrayType::ArraySizeModifier ASM,
2183 unsigned IndexTypeQuals) const {
2184 assert((EltTy->isDependentType() ||
2185 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2186 "Constant array of VLAs is illegal!");
2188 // Convert the array size into a canonical width matching the pointer size for
2190 llvm::APInt ArySize(ArySizeIn);
2192 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2194 llvm::FoldingSetNodeID ID;
2195 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2197 void *InsertPos = 0;
2198 if (ConstantArrayType *ATP =
2199 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2200 return QualType(ATP, 0);
2202 // If the element type isn't canonical or has qualifiers, this won't
2203 // be a canonical type either, so fill in the canonical type field.
2205 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2206 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2207 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2208 ASM, IndexTypeQuals);
2209 Canon = getQualifiedType(Canon, canonSplit.Quals);
2211 // Get the new insert position for the node we care about.
2212 ConstantArrayType *NewIP =
2213 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2214 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2217 ConstantArrayType *New = new(*this,TypeAlignment)
2218 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2219 ConstantArrayTypes.InsertNode(New, InsertPos);
2220 Types.push_back(New);
2221 return QualType(New, 0);
2224 /// getVariableArrayDecayedType - Turns the given type, which may be
2225 /// variably-modified, into the corresponding type with all the known
2226 /// sizes replaced with [*].
2227 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2228 // Vastly most common case.
2229 if (!type->isVariablyModifiedType()) return type;
2233 SplitQualType split = type.getSplitDesugaredType();
2234 const Type *ty = split.Ty;
2235 switch (ty->getTypeClass()) {
2236 #define TYPE(Class, Base)
2237 #define ABSTRACT_TYPE(Class, Base)
2238 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2239 #include "clang/AST/TypeNodes.def"
2240 llvm_unreachable("didn't desugar past all non-canonical types?");
2242 // These types should never be variably-modified.
2246 case Type::ExtVector:
2247 case Type::DependentSizedExtVector:
2248 case Type::ObjCObject:
2249 case Type::ObjCInterface:
2250 case Type::ObjCObjectPointer:
2253 case Type::UnresolvedUsing:
2254 case Type::TypeOfExpr:
2256 case Type::Decltype:
2257 case Type::UnaryTransform:
2258 case Type::DependentName:
2259 case Type::InjectedClassName:
2260 case Type::TemplateSpecialization:
2261 case Type::DependentTemplateSpecialization:
2262 case Type::TemplateTypeParm:
2263 case Type::SubstTemplateTypeParmPack:
2265 case Type::PackExpansion:
2266 llvm_unreachable("type should never be variably-modified");
2268 // These types can be variably-modified but should never need to
2270 case Type::FunctionNoProto:
2271 case Type::FunctionProto:
2272 case Type::BlockPointer:
2273 case Type::MemberPointer:
2276 // These types can be variably-modified. All these modifications
2277 // preserve structure except as noted by comments.
2278 // TODO: if we ever care about optimizing VLAs, there are no-op
2279 // optimizations available here.
2281 result = getPointerType(getVariableArrayDecayedType(
2282 cast<PointerType>(ty)->getPointeeType()));
2285 case Type::LValueReference: {
2286 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2287 result = getLValueReferenceType(
2288 getVariableArrayDecayedType(lv->getPointeeType()),
2289 lv->isSpelledAsLValue());
2293 case Type::RValueReference: {
2294 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2295 result = getRValueReferenceType(
2296 getVariableArrayDecayedType(lv->getPointeeType()));
2300 case Type::Atomic: {
2301 const AtomicType *at = cast<AtomicType>(ty);
2302 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2306 case Type::ConstantArray: {
2307 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2308 result = getConstantArrayType(
2309 getVariableArrayDecayedType(cat->getElementType()),
2311 cat->getSizeModifier(),
2312 cat->getIndexTypeCVRQualifiers());
2316 case Type::DependentSizedArray: {
2317 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2318 result = getDependentSizedArrayType(
2319 getVariableArrayDecayedType(dat->getElementType()),
2321 dat->getSizeModifier(),
2322 dat->getIndexTypeCVRQualifiers(),
2323 dat->getBracketsRange());
2327 // Turn incomplete types into [*] types.
2328 case Type::IncompleteArray: {
2329 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2330 result = getVariableArrayType(
2331 getVariableArrayDecayedType(iat->getElementType()),
2334 iat->getIndexTypeCVRQualifiers(),
2339 // Turn VLA types into [*] types.
2340 case Type::VariableArray: {
2341 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2342 result = getVariableArrayType(
2343 getVariableArrayDecayedType(vat->getElementType()),
2346 vat->getIndexTypeCVRQualifiers(),
2347 vat->getBracketsRange());
2352 // Apply the top-level qualifiers from the original.
2353 return getQualifiedType(result, split.Quals);
2356 /// getVariableArrayType - Returns a non-unique reference to the type for a
2357 /// variable array of the specified element type.
2358 QualType ASTContext::getVariableArrayType(QualType EltTy,
2360 ArrayType::ArraySizeModifier ASM,
2361 unsigned IndexTypeQuals,
2362 SourceRange Brackets) const {
2363 // Since we don't unique expressions, it isn't possible to unique VLA's
2364 // that have an expression provided for their size.
2367 // Be sure to pull qualifiers off the element type.
2368 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2369 SplitQualType canonSplit = getCanonicalType(EltTy).split();
2370 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2371 IndexTypeQuals, Brackets);
2372 Canon = getQualifiedType(Canon, canonSplit.Quals);
2375 VariableArrayType *New = new(*this, TypeAlignment)
2376 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2378 VariableArrayTypes.push_back(New);
2379 Types.push_back(New);
2380 return QualType(New, 0);
2383 /// getDependentSizedArrayType - Returns a non-unique reference to
2384 /// the type for a dependently-sized array of the specified element
2386 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2388 ArrayType::ArraySizeModifier ASM,
2389 unsigned elementTypeQuals,
2390 SourceRange brackets) const {
2391 assert((!numElements || numElements->isTypeDependent() ||
2392 numElements->isValueDependent()) &&
2393 "Size must be type- or value-dependent!");
2395 // Dependently-sized array types that do not have a specified number
2396 // of elements will have their sizes deduced from a dependent
2397 // initializer. We do no canonicalization here at all, which is okay
2398 // because they can't be used in most locations.
2400 DependentSizedArrayType *newType
2401 = new (*this, TypeAlignment)
2402 DependentSizedArrayType(*this, elementType, QualType(),
2403 numElements, ASM, elementTypeQuals,
2405 Types.push_back(newType);
2406 return QualType(newType, 0);
2409 // Otherwise, we actually build a new type every time, but we
2410 // also build a canonical type.
2412 SplitQualType canonElementType = getCanonicalType(elementType).split();
2414 void *insertPos = 0;
2415 llvm::FoldingSetNodeID ID;
2416 DependentSizedArrayType::Profile(ID, *this,
2417 QualType(canonElementType.Ty, 0),
2418 ASM, elementTypeQuals, numElements);
2420 // Look for an existing type with these properties.
2421 DependentSizedArrayType *canonTy =
2422 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2424 // If we don't have one, build one.
2426 canonTy = new (*this, TypeAlignment)
2427 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2428 QualType(), numElements, ASM, elementTypeQuals,
2430 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2431 Types.push_back(canonTy);
2434 // Apply qualifiers from the element type to the array.
2435 QualType canon = getQualifiedType(QualType(canonTy,0),
2436 canonElementType.Quals);
2438 // If we didn't need extra canonicalization for the element type,
2439 // then just use that as our result.
2440 if (QualType(canonElementType.Ty, 0) == elementType)
2443 // Otherwise, we need to build a type which follows the spelling
2444 // of the element type.
2445 DependentSizedArrayType *sugaredType
2446 = new (*this, TypeAlignment)
2447 DependentSizedArrayType(*this, elementType, canon, numElements,
2448 ASM, elementTypeQuals, brackets);
2449 Types.push_back(sugaredType);
2450 return QualType(sugaredType, 0);
2453 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2454 ArrayType::ArraySizeModifier ASM,
2455 unsigned elementTypeQuals) const {
2456 llvm::FoldingSetNodeID ID;
2457 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2459 void *insertPos = 0;
2460 if (IncompleteArrayType *iat =
2461 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2462 return QualType(iat, 0);
2464 // If the element type isn't canonical, this won't be a canonical type
2465 // either, so fill in the canonical type field. We also have to pull
2466 // qualifiers off the element type.
2469 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2470 SplitQualType canonSplit = getCanonicalType(elementType).split();
2471 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2472 ASM, elementTypeQuals);
2473 canon = getQualifiedType(canon, canonSplit.Quals);
2475 // Get the new insert position for the node we care about.
2476 IncompleteArrayType *existing =
2477 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2478 assert(!existing && "Shouldn't be in the map!"); (void) existing;
2481 IncompleteArrayType *newType = new (*this, TypeAlignment)
2482 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2484 IncompleteArrayTypes.InsertNode(newType, insertPos);
2485 Types.push_back(newType);
2486 return QualType(newType, 0);
2489 /// getVectorType - Return the unique reference to a vector type of
2490 /// the specified element type and size. VectorType must be a built-in type.
2491 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2492 VectorType::VectorKind VecKind) const {
2493 assert(vecType->isBuiltinType());
2495 // Check if we've already instantiated a vector of this type.
2496 llvm::FoldingSetNodeID ID;
2497 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2499 void *InsertPos = 0;
2500 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2501 return QualType(VTP, 0);
2503 // If the element type isn't canonical, this won't be a canonical type either,
2504 // so fill in the canonical type field.
2506 if (!vecType.isCanonical()) {
2507 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2509 // Get the new insert position for the node we care about.
2510 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2511 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2513 VectorType *New = new (*this, TypeAlignment)
2514 VectorType(vecType, NumElts, Canonical, VecKind);
2515 VectorTypes.InsertNode(New, InsertPos);
2516 Types.push_back(New);
2517 return QualType(New, 0);
2520 /// getExtVectorType - Return the unique reference to an extended vector type of
2521 /// the specified element type and size. VectorType must be a built-in type.
2523 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2524 assert(vecType->isBuiltinType() || vecType->isDependentType());
2526 // Check if we've already instantiated a vector of this type.
2527 llvm::FoldingSetNodeID ID;
2528 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2529 VectorType::GenericVector);
2530 void *InsertPos = 0;
2531 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2532 return QualType(VTP, 0);
2534 // If the element type isn't canonical, this won't be a canonical type either,
2535 // so fill in the canonical type field.
2537 if (!vecType.isCanonical()) {
2538 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2540 // Get the new insert position for the node we care about.
2541 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2542 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2544 ExtVectorType *New = new (*this, TypeAlignment)
2545 ExtVectorType(vecType, NumElts, Canonical);
2546 VectorTypes.InsertNode(New, InsertPos);
2547 Types.push_back(New);
2548 return QualType(New, 0);
2552 ASTContext::getDependentSizedExtVectorType(QualType vecType,
2554 SourceLocation AttrLoc) const {
2555 llvm::FoldingSetNodeID ID;
2556 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2559 void *InsertPos = 0;
2560 DependentSizedExtVectorType *Canon
2561 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2562 DependentSizedExtVectorType *New;
2564 // We already have a canonical version of this array type; use it as
2565 // the canonical type for a newly-built type.
2566 New = new (*this, TypeAlignment)
2567 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2570 QualType CanonVecTy = getCanonicalType(vecType);
2571 if (CanonVecTy == vecType) {
2572 New = new (*this, TypeAlignment)
2573 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2576 DependentSizedExtVectorType *CanonCheck
2577 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2578 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2580 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2582 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2584 New = new (*this, TypeAlignment)
2585 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2589 Types.push_back(New);
2590 return QualType(New, 0);
2593 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2596 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2597 const FunctionType::ExtInfo &Info) const {
2598 const CallingConv DefaultCC = Info.getCC();
2599 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2600 CC_X86StdCall : DefaultCC;
2601 // Unique functions, to guarantee there is only one function of a particular
2603 llvm::FoldingSetNodeID ID;
2604 FunctionNoProtoType::Profile(ID, ResultTy, Info);
2606 void *InsertPos = 0;
2607 if (FunctionNoProtoType *FT =
2608 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2609 return QualType(FT, 0);
2612 if (!ResultTy.isCanonical() ||
2613 getCanonicalCallConv(CallConv) != CallConv) {
2615 getFunctionNoProtoType(getCanonicalType(ResultTy),
2616 Info.withCallingConv(getCanonicalCallConv(CallConv)));
2618 // Get the new insert position for the node we care about.
2619 FunctionNoProtoType *NewIP =
2620 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2621 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2624 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
2625 FunctionNoProtoType *New = new (*this, TypeAlignment)
2626 FunctionNoProtoType(ResultTy, Canonical, newInfo);
2627 Types.push_back(New);
2628 FunctionNoProtoTypes.InsertNode(New, InsertPos);
2629 return QualType(New, 0);
2632 /// \brief Determine whether \p T is canonical as the result type of a function.
2633 static bool isCanonicalResultType(QualType T) {
2634 return T.isCanonical() &&
2635 (T.getObjCLifetime() == Qualifiers::OCL_None ||
2636 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2639 /// getFunctionType - Return a normal function type with a typed argument
2640 /// list. isVariadic indicates whether the argument list includes '...'.
2642 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
2643 const FunctionProtoType::ExtProtoInfo &EPI) const {
2644 size_t NumArgs = ArgArray.size();
2646 // Unique functions, to guarantee there is only one function of a particular
2648 llvm::FoldingSetNodeID ID;
2649 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2652 void *InsertPos = 0;
2653 if (FunctionProtoType *FTP =
2654 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2655 return QualType(FTP, 0);
2657 // Determine whether the type being created is already canonical or not.
2659 EPI.ExceptionSpecType == EST_None && isCanonicalResultType(ResultTy) &&
2660 !EPI.HasTrailingReturn;
2661 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2662 if (!ArgArray[i].isCanonicalAsParam())
2663 isCanonical = false;
2665 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2666 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2667 CC_X86StdCall : DefaultCC;
2669 // If this type isn't canonical, get the canonical version of it.
2670 // The exception spec is not part of the canonical type.
2672 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
2673 SmallVector<QualType, 16> CanonicalArgs;
2674 CanonicalArgs.reserve(NumArgs);
2675 for (unsigned i = 0; i != NumArgs; ++i)
2676 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2678 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2679 CanonicalEPI.HasTrailingReturn = false;
2680 CanonicalEPI.ExceptionSpecType = EST_None;
2681 CanonicalEPI.NumExceptions = 0;
2682 CanonicalEPI.ExtInfo
2683 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2685 // Result types do not have ARC lifetime qualifiers.
2686 QualType CanResultTy = getCanonicalType(ResultTy);
2687 if (ResultTy.getQualifiers().hasObjCLifetime()) {
2688 Qualifiers Qs = CanResultTy.getQualifiers();
2689 Qs.removeObjCLifetime();
2690 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
2693 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
2695 // Get the new insert position for the node we care about.
2696 FunctionProtoType *NewIP =
2697 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2698 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2701 // FunctionProtoType objects are allocated with extra bytes after
2702 // them for three variable size arrays at the end:
2703 // - parameter types
2704 // - exception types
2705 // - consumed-arguments flags
2706 // Instead of the exception types, there could be a noexcept
2707 // expression, or information used to resolve the exception
2709 size_t Size = sizeof(FunctionProtoType) +
2710 NumArgs * sizeof(QualType);
2711 if (EPI.ExceptionSpecType == EST_Dynamic) {
2712 Size += EPI.NumExceptions * sizeof(QualType);
2713 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2714 Size += sizeof(Expr*);
2715 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
2716 Size += 2 * sizeof(FunctionDecl*);
2717 } else if (EPI.ExceptionSpecType == EST_Unevaluated) {
2718 Size += sizeof(FunctionDecl*);
2720 if (EPI.ConsumedArguments)
2721 Size += NumArgs * sizeof(bool);
2723 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2724 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2725 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
2726 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
2727 Types.push_back(FTP);
2728 FunctionProtoTypes.InsertNode(FTP, InsertPos);
2729 return QualType(FTP, 0);
2733 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2734 if (!isa<CXXRecordDecl>(D)) return false;
2735 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2736 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2738 if (RD->getDescribedClassTemplate() &&
2739 !isa<ClassTemplateSpecializationDecl>(RD))
2745 /// getInjectedClassNameType - Return the unique reference to the
2746 /// injected class name type for the specified templated declaration.
2747 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2748 QualType TST) const {
2749 assert(NeedsInjectedClassNameType(Decl));
2750 if (Decl->TypeForDecl) {
2751 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2752 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
2753 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2754 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2755 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2758 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2759 Decl->TypeForDecl = newType;
2760 Types.push_back(newType);
2762 return QualType(Decl->TypeForDecl, 0);
2765 /// getTypeDeclType - Return the unique reference to the type for the
2766 /// specified type declaration.
2767 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
2768 assert(Decl && "Passed null for Decl param");
2769 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
2771 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
2772 return getTypedefType(Typedef);
2774 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2775 "Template type parameter types are always available.");
2777 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
2778 assert(!Record->getPreviousDecl() &&
2779 "struct/union has previous declaration");
2780 assert(!NeedsInjectedClassNameType(Record));
2781 return getRecordType(Record);
2782 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
2783 assert(!Enum->getPreviousDecl() &&
2784 "enum has previous declaration");
2785 return getEnumType(Enum);
2786 } else if (const UnresolvedUsingTypenameDecl *Using =
2787 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
2788 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2789 Decl->TypeForDecl = newType;
2790 Types.push_back(newType);
2792 llvm_unreachable("TypeDecl without a type?");
2794 return QualType(Decl->TypeForDecl, 0);
2797 /// getTypedefType - Return the unique reference to the type for the
2798 /// specified typedef name decl.
2800 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2801 QualType Canonical) const {
2802 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2804 if (Canonical.isNull())
2805 Canonical = getCanonicalType(Decl->getUnderlyingType());
2806 TypedefType *newType = new(*this, TypeAlignment)
2807 TypedefType(Type::Typedef, Decl, Canonical);
2808 Decl->TypeForDecl = newType;
2809 Types.push_back(newType);
2810 return QualType(newType, 0);
2813 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
2814 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2816 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
2817 if (PrevDecl->TypeForDecl)
2818 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2820 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2821 Decl->TypeForDecl = newType;
2822 Types.push_back(newType);
2823 return QualType(newType, 0);
2826 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
2827 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2829 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
2830 if (PrevDecl->TypeForDecl)
2831 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2833 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2834 Decl->TypeForDecl = newType;
2835 Types.push_back(newType);
2836 return QualType(newType, 0);
2839 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2840 QualType modifiedType,
2841 QualType equivalentType) {
2842 llvm::FoldingSetNodeID id;
2843 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2845 void *insertPos = 0;
2846 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2847 if (type) return QualType(type, 0);
2849 QualType canon = getCanonicalType(equivalentType);
2850 type = new (*this, TypeAlignment)
2851 AttributedType(canon, attrKind, modifiedType, equivalentType);
2853 Types.push_back(type);
2854 AttributedTypes.InsertNode(type, insertPos);
2856 return QualType(type, 0);
2860 /// \brief Retrieve a substitution-result type.
2862 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
2863 QualType Replacement) const {
2864 assert(Replacement.isCanonical()
2865 && "replacement types must always be canonical");
2867 llvm::FoldingSetNodeID ID;
2868 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2869 void *InsertPos = 0;
2870 SubstTemplateTypeParmType *SubstParm
2871 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2874 SubstParm = new (*this, TypeAlignment)
2875 SubstTemplateTypeParmType(Parm, Replacement);
2876 Types.push_back(SubstParm);
2877 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2880 return QualType(SubstParm, 0);
2883 /// \brief Retrieve a
2884 QualType ASTContext::getSubstTemplateTypeParmPackType(
2885 const TemplateTypeParmType *Parm,
2886 const TemplateArgument &ArgPack) {
2888 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2889 PEnd = ArgPack.pack_end();
2891 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2892 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2896 llvm::FoldingSetNodeID ID;
2897 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2898 void *InsertPos = 0;
2899 if (SubstTemplateTypeParmPackType *SubstParm
2900 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2901 return QualType(SubstParm, 0);
2904 if (!Parm->isCanonicalUnqualified()) {
2905 Canon = getCanonicalType(QualType(Parm, 0));
2906 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2908 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2911 SubstTemplateTypeParmPackType *SubstParm
2912 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2914 Types.push_back(SubstParm);
2915 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2916 return QualType(SubstParm, 0);
2919 /// \brief Retrieve the template type parameter type for a template
2920 /// parameter or parameter pack with the given depth, index, and (optionally)
2922 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
2924 TemplateTypeParmDecl *TTPDecl) const {
2925 llvm::FoldingSetNodeID ID;
2926 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
2927 void *InsertPos = 0;
2928 TemplateTypeParmType *TypeParm
2929 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2932 return QualType(TypeParm, 0);
2935 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
2936 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
2938 TemplateTypeParmType *TypeCheck
2939 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2940 assert(!TypeCheck && "Template type parameter canonical type broken");
2943 TypeParm = new (*this, TypeAlignment)
2944 TemplateTypeParmType(Depth, Index, ParameterPack);
2946 Types.push_back(TypeParm);
2947 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2949 return QualType(TypeParm, 0);
2953 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2954 SourceLocation NameLoc,
2955 const TemplateArgumentListInfo &Args,
2956 QualType Underlying) const {
2957 assert(!Name.getAsDependentTemplateName() &&
2958 "No dependent template names here!");
2959 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
2961 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2962 TemplateSpecializationTypeLoc TL =
2963 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
2964 TL.setTemplateKeywordLoc(SourceLocation());
2965 TL.setTemplateNameLoc(NameLoc);
2966 TL.setLAngleLoc(Args.getLAngleLoc());
2967 TL.setRAngleLoc(Args.getRAngleLoc());
2968 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2969 TL.setArgLocInfo(i, Args[i].getLocInfo());
2974 ASTContext::getTemplateSpecializationType(TemplateName Template,
2975 const TemplateArgumentListInfo &Args,
2976 QualType Underlying) const {
2977 assert(!Template.getAsDependentTemplateName() &&
2978 "No dependent template names here!");
2980 unsigned NumArgs = Args.size();
2982 SmallVector<TemplateArgument, 4> ArgVec;
2983 ArgVec.reserve(NumArgs);
2984 for (unsigned i = 0; i != NumArgs; ++i)
2985 ArgVec.push_back(Args[i].getArgument());
2987 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
2992 static bool hasAnyPackExpansions(const TemplateArgument *Args,
2994 for (unsigned I = 0; I != NumArgs; ++I)
2995 if (Args[I].isPackExpansion())
3003 ASTContext::getTemplateSpecializationType(TemplateName Template,
3004 const TemplateArgument *Args,
3006 QualType Underlying) const {
3007 assert(!Template.getAsDependentTemplateName() &&
3008 "No dependent template names here!");
3009 // Look through qualified template names.
3010 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3011 Template = TemplateName(QTN->getTemplateDecl());
3014 Template.getAsTemplateDecl() &&
3015 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3017 if (!Underlying.isNull())
3018 CanonType = getCanonicalType(Underlying);
3020 // We can get here with an alias template when the specialization contains
3021 // a pack expansion that does not match up with a parameter pack.
3022 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3023 "Caller must compute aliased type");
3024 IsTypeAlias = false;
3025 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3029 // Allocate the (non-canonical) template specialization type, but don't
3030 // try to unique it: these types typically have location information that
3031 // we don't unique and don't want to lose.
3032 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3033 sizeof(TemplateArgument) * NumArgs +
3034 (IsTypeAlias? sizeof(QualType) : 0),
3036 TemplateSpecializationType *Spec
3037 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3038 IsTypeAlias ? Underlying : QualType());
3040 Types.push_back(Spec);
3041 return QualType(Spec, 0);
3045 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3046 const TemplateArgument *Args,
3047 unsigned NumArgs) const {
3048 assert(!Template.getAsDependentTemplateName() &&
3049 "No dependent template names here!");
3051 // Look through qualified template names.
3052 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3053 Template = TemplateName(QTN->getTemplateDecl());
3055 // Build the canonical template specialization type.
3056 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3057 SmallVector<TemplateArgument, 4> CanonArgs;
3058 CanonArgs.reserve(NumArgs);
3059 for (unsigned I = 0; I != NumArgs; ++I)
3060 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3062 // Determine whether this canonical template specialization type already
3064 llvm::FoldingSetNodeID ID;
3065 TemplateSpecializationType::Profile(ID, CanonTemplate,
3066 CanonArgs.data(), NumArgs, *this);
3068 void *InsertPos = 0;
3069 TemplateSpecializationType *Spec
3070 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3073 // Allocate a new canonical template specialization type.
3074 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3075 sizeof(TemplateArgument) * NumArgs),
3077 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3078 CanonArgs.data(), NumArgs,
3079 QualType(), QualType());
3080 Types.push_back(Spec);
3081 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3084 assert(Spec->isDependentType() &&
3085 "Non-dependent template-id type must have a canonical type");
3086 return QualType(Spec, 0);
3090 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3091 NestedNameSpecifier *NNS,
3092 QualType NamedType) const {
3093 llvm::FoldingSetNodeID ID;
3094 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3096 void *InsertPos = 0;
3097 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3099 return QualType(T, 0);
3101 QualType Canon = NamedType;
3102 if (!Canon.isCanonical()) {
3103 Canon = getCanonicalType(NamedType);
3104 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3105 assert(!CheckT && "Elaborated canonical type broken");
3109 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
3111 ElaboratedTypes.InsertNode(T, InsertPos);
3112 return QualType(T, 0);
3116 ASTContext::getParenType(QualType InnerType) const {
3117 llvm::FoldingSetNodeID ID;
3118 ParenType::Profile(ID, InnerType);
3120 void *InsertPos = 0;
3121 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3123 return QualType(T, 0);
3125 QualType Canon = InnerType;
3126 if (!Canon.isCanonical()) {
3127 Canon = getCanonicalType(InnerType);
3128 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3129 assert(!CheckT && "Paren canonical type broken");
3133 T = new (*this) ParenType(InnerType, Canon);
3135 ParenTypes.InsertNode(T, InsertPos);
3136 return QualType(T, 0);
3139 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3140 NestedNameSpecifier *NNS,
3141 const IdentifierInfo *Name,
3142 QualType Canon) const {
3143 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
3145 if (Canon.isNull()) {
3146 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3147 ElaboratedTypeKeyword CanonKeyword = Keyword;
3148 if (Keyword == ETK_None)
3149 CanonKeyword = ETK_Typename;
3151 if (CanonNNS != NNS || CanonKeyword != Keyword)
3152 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3155 llvm::FoldingSetNodeID ID;
3156 DependentNameType::Profile(ID, Keyword, NNS, Name);
3158 void *InsertPos = 0;
3159 DependentNameType *T
3160 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3162 return QualType(T, 0);
3164 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
3166 DependentNameTypes.InsertNode(T, InsertPos);
3167 return QualType(T, 0);
3171 ASTContext::getDependentTemplateSpecializationType(
3172 ElaboratedTypeKeyword Keyword,
3173 NestedNameSpecifier *NNS,
3174 const IdentifierInfo *Name,
3175 const TemplateArgumentListInfo &Args) const {
3176 // TODO: avoid this copy
3177 SmallVector<TemplateArgument, 16> ArgCopy;
3178 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3179 ArgCopy.push_back(Args[I].getArgument());
3180 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3186 ASTContext::getDependentTemplateSpecializationType(
3187 ElaboratedTypeKeyword Keyword,
3188 NestedNameSpecifier *NNS,
3189 const IdentifierInfo *Name,
3191 const TemplateArgument *Args) const {
3192 assert((!NNS || NNS->isDependent()) &&
3193 "nested-name-specifier must be dependent");
3195 llvm::FoldingSetNodeID ID;
3196 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3197 Name, NumArgs, Args);
3199 void *InsertPos = 0;
3200 DependentTemplateSpecializationType *T
3201 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3203 return QualType(T, 0);
3205 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3207 ElaboratedTypeKeyword CanonKeyword = Keyword;
3208 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3210 bool AnyNonCanonArgs = false;
3211 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3212 for (unsigned I = 0; I != NumArgs; ++I) {
3213 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3214 if (!CanonArgs[I].structurallyEquals(Args[I]))
3215 AnyNonCanonArgs = true;
3219 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3220 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3224 // Find the insert position again.
3225 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3228 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3229 sizeof(TemplateArgument) * NumArgs),
3231 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3232 Name, NumArgs, Args, Canon);
3234 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3235 return QualType(T, 0);
3238 QualType ASTContext::getPackExpansionType(QualType Pattern,
3239 Optional<unsigned> NumExpansions) {
3240 llvm::FoldingSetNodeID ID;
3241 PackExpansionType::Profile(ID, Pattern, NumExpansions);
3243 assert(Pattern->containsUnexpandedParameterPack() &&
3244 "Pack expansions must expand one or more parameter packs");
3245 void *InsertPos = 0;
3246 PackExpansionType *T
3247 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3249 return QualType(T, 0);
3252 if (!Pattern.isCanonical()) {
3253 Canon = getCanonicalType(Pattern);
3254 // The canonical type might not contain an unexpanded parameter pack, if it
3255 // contains an alias template specialization which ignores one of its
3257 if (Canon->containsUnexpandedParameterPack()) {
3258 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
3260 // Find the insert position again, in case we inserted an element into
3261 // PackExpansionTypes and invalidated our insert position.
3262 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3266 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
3268 PackExpansionTypes.InsertNode(T, InsertPos);
3269 return QualType(T, 0);
3272 /// CmpProtocolNames - Comparison predicate for sorting protocols
3274 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
3275 const ObjCProtocolDecl *RHS) {
3276 return LHS->getDeclName() < RHS->getDeclName();
3279 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
3280 unsigned NumProtocols) {
3281 if (NumProtocols == 0) return true;
3283 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3286 for (unsigned i = 1; i != NumProtocols; ++i)
3287 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
3288 Protocols[i]->getCanonicalDecl() != Protocols[i])
3293 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
3294 unsigned &NumProtocols) {
3295 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
3297 // Sort protocols, keyed by name.
3298 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
3301 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3302 Protocols[I] = Protocols[I]->getCanonicalDecl();
3304 // Remove duplicates.
3305 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3306 NumProtocols = ProtocolsEnd-Protocols;
3309 QualType ASTContext::getObjCObjectType(QualType BaseType,
3310 ObjCProtocolDecl * const *Protocols,
3311 unsigned NumProtocols) const {
3312 // If the base type is an interface and there aren't any protocols
3313 // to add, then the interface type will do just fine.
3314 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
3317 // Look in the folding set for an existing type.
3318 llvm::FoldingSetNodeID ID;
3319 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
3320 void *InsertPos = 0;
3321 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3322 return QualType(QT, 0);
3324 // Build the canonical type, which has the canonical base type and
3325 // a sorted-and-uniqued list of protocols.
3327 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
3328 if (!ProtocolsSorted || !BaseType.isCanonical()) {
3329 if (!ProtocolsSorted) {
3330 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
3331 Protocols + NumProtocols);
3332 unsigned UniqueCount = NumProtocols;
3334 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
3335 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3336 &Sorted[0], UniqueCount);
3338 Canonical = getObjCObjectType(getCanonicalType(BaseType),
3339 Protocols, NumProtocols);
3342 // Regenerate InsertPos.
3343 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3346 unsigned Size = sizeof(ObjCObjectTypeImpl);
3347 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
3348 void *Mem = Allocate(Size, TypeAlignment);
3349 ObjCObjectTypeImpl *T =
3350 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
3353 ObjCObjectTypes.InsertNode(T, InsertPos);
3354 return QualType(T, 0);
3357 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3358 /// the given object type.
3359 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
3360 llvm::FoldingSetNodeID ID;
3361 ObjCObjectPointerType::Profile(ID, ObjectT);
3363 void *InsertPos = 0;
3364 if (ObjCObjectPointerType *QT =
3365 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3366 return QualType(QT, 0);
3368 // Find the canonical object type.
3370 if (!ObjectT.isCanonical()) {
3371 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3373 // Regenerate InsertPos.
3374 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3378 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3379 ObjCObjectPointerType *QType =
3380 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
3382 Types.push_back(QType);
3383 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
3384 return QualType(QType, 0);
3387 /// getObjCInterfaceType - Return the unique reference to the type for the
3388 /// specified ObjC interface decl. The list of protocols is optional.
3389 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3390 ObjCInterfaceDecl *PrevDecl) const {
3391 if (Decl->TypeForDecl)
3392 return QualType(Decl->TypeForDecl, 0);
3395 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3396 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3397 return QualType(PrevDecl->TypeForDecl, 0);
3400 // Prefer the definition, if there is one.
3401 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3404 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3405 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3406 Decl->TypeForDecl = T;
3408 return QualType(T, 0);
3411 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3412 /// TypeOfExprType AST's (since expression's are never shared). For example,
3413 /// multiple declarations that refer to "typeof(x)" all contain different
3414 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
3415 /// on canonical type's (which are always unique).
3416 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
3417 TypeOfExprType *toe;
3418 if (tofExpr->isTypeDependent()) {
3419 llvm::FoldingSetNodeID ID;
3420 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3422 void *InsertPos = 0;
3423 DependentTypeOfExprType *Canon
3424 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3426 // We already have a "canonical" version of an identical, dependent
3427 // typeof(expr) type. Use that as our canonical type.
3428 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3429 QualType((TypeOfExprType*)Canon, 0));
3431 // Build a new, canonical typeof(expr) type.
3433 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3434 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3438 QualType Canonical = getCanonicalType(tofExpr->getType());
3439 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3441 Types.push_back(toe);
3442 return QualType(toe, 0);
3445 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
3446 /// TypeOfType AST's. The only motivation to unique these nodes would be
3447 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3448 /// an issue. This doesn't effect the type checker, since it operates
3449 /// on canonical type's (which are always unique).
3450 QualType ASTContext::getTypeOfType(QualType tofType) const {
3451 QualType Canonical = getCanonicalType(tofType);
3452 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3453 Types.push_back(tot);
3454 return QualType(tot, 0);
3458 /// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
3459 /// DecltypeType AST's. The only motivation to unique these nodes would be
3460 /// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
3461 /// an issue. This doesn't effect the type checker, since it operates
3462 /// on canonical types (which are always unique).
3463 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3466 // C++0x [temp.type]p2:
3467 // If an expression e involves a template parameter, decltype(e) denotes a
3468 // unique dependent type. Two such decltype-specifiers refer to the same
3469 // type only if their expressions are equivalent (14.5.6.1).
3470 if (e->isInstantiationDependent()) {
3471 llvm::FoldingSetNodeID ID;
3472 DependentDecltypeType::Profile(ID, *this, e);
3474 void *InsertPos = 0;
3475 DependentDecltypeType *Canon
3476 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3478 // We already have a "canonical" version of an equivalent, dependent
3479 // decltype type. Use that as our canonical type.
3480 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3481 QualType((DecltypeType*)Canon, 0));
3483 // Build a new, canonical typeof(expr) type.
3484 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3485 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3489 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3490 getCanonicalType(UnderlyingType));
3492 Types.push_back(dt);
3493 return QualType(dt, 0);
3496 /// getUnaryTransformationType - We don't unique these, since the memory
3497 /// savings are minimal and these are rare.
3498 QualType ASTContext::getUnaryTransformType(QualType BaseType,
3499 QualType UnderlyingType,
3500 UnaryTransformType::UTTKind Kind)
3502 UnaryTransformType *Ty =
3503 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3505 UnderlyingType->isDependentType() ?
3506 QualType() : getCanonicalType(UnderlyingType));
3507 Types.push_back(Ty);
3508 return QualType(Ty, 0);
3511 /// getAutoType - We only unique auto types after they've been deduced.
3512 QualType ASTContext::getAutoType(QualType DeducedType) const {
3513 void *InsertPos = 0;
3514 if (!DeducedType.isNull()) {
3515 // Look in the folding set for an existing type.
3516 llvm::FoldingSetNodeID ID;
3517 AutoType::Profile(ID, DeducedType);
3518 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3519 return QualType(AT, 0);
3522 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3523 Types.push_back(AT);
3525 AutoTypes.InsertNode(AT, InsertPos);
3526 return QualType(AT, 0);
3529 /// getAtomicType - Return the uniqued reference to the atomic type for
3530 /// the given value type.
3531 QualType ASTContext::getAtomicType(QualType T) const {
3532 // Unique pointers, to guarantee there is only one pointer of a particular
3534 llvm::FoldingSetNodeID ID;
3535 AtomicType::Profile(ID, T);
3537 void *InsertPos = 0;
3538 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3539 return QualType(AT, 0);
3541 // If the atomic value type isn't canonical, this won't be a canonical type
3542 // either, so fill in the canonical type field.
3544 if (!T.isCanonical()) {
3545 Canonical = getAtomicType(getCanonicalType(T));
3547 // Get the new insert position for the node we care about.
3548 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3549 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3551 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3552 Types.push_back(New);
3553 AtomicTypes.InsertNode(New, InsertPos);
3554 return QualType(New, 0);
3557 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
3558 QualType ASTContext::getAutoDeductType() const {
3559 if (AutoDeductTy.isNull())
3560 AutoDeductTy = getAutoType(QualType());
3561 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3562 return AutoDeductTy;
3565 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3566 QualType ASTContext::getAutoRRefDeductType() const {
3567 if (AutoRRefDeductTy.isNull())
3568 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3569 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3570 return AutoRRefDeductTy;
3573 /// getTagDeclType - Return the unique reference to the type for the
3574 /// specified TagDecl (struct/union/class/enum) decl.
3575 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
3577 // FIXME: What is the design on getTagDeclType when it requires casting
3578 // away const? mutable?
3579 return getTypeDeclType(const_cast<TagDecl*>(Decl));
3582 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3583 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3584 /// needs to agree with the definition in <stddef.h>.
3585 CanQualType ASTContext::getSizeType() const {
3586 return getFromTargetType(Target->getSizeType());
3589 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3590 CanQualType ASTContext::getIntMaxType() const {
3591 return getFromTargetType(Target->getIntMaxType());
3594 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3595 CanQualType ASTContext::getUIntMaxType() const {
3596 return getFromTargetType(Target->getUIntMaxType());
3599 /// getSignedWCharType - Return the type of "signed wchar_t".
3600 /// Used when in C++, as a GCC extension.
3601 QualType ASTContext::getSignedWCharType() const {
3602 // FIXME: derive from "Target" ?
3606 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3607 /// Used when in C++, as a GCC extension.
3608 QualType ASTContext::getUnsignedWCharType() const {
3609 // FIXME: derive from "Target" ?
3610 return UnsignedIntTy;
3613 QualType ASTContext::getIntPtrType() const {
3614 return getFromTargetType(Target->getIntPtrType());
3617 QualType ASTContext::getUIntPtrType() const {
3618 return getCorrespondingUnsignedType(getIntPtrType());
3621 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
3622 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3623 QualType ASTContext::getPointerDiffType() const {
3624 return getFromTargetType(Target->getPtrDiffType(0));
3627 /// \brief Return the unique type for "pid_t" defined in
3628 /// <sys/types.h>. We need this to compute the correct type for vfork().
3629 QualType ASTContext::getProcessIDType() const {
3630 return getFromTargetType(Target->getProcessIDType());
3633 //===----------------------------------------------------------------------===//
3635 //===----------------------------------------------------------------------===//
3637 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
3638 // Push qualifiers into arrays, and then discard any remaining
3640 T = getCanonicalType(T);
3641 T = getVariableArrayDecayedType(T);
3642 const Type *Ty = T.getTypePtr();
3644 if (isa<ArrayType>(Ty)) {
3645 Result = getArrayDecayedType(QualType(Ty,0));
3646 } else if (isa<FunctionType>(Ty)) {
3647 Result = getPointerType(QualType(Ty, 0));
3649 Result = QualType(Ty, 0);
3652 return CanQualType::CreateUnsafe(Result);
3655 QualType ASTContext::getUnqualifiedArrayType(QualType type,
3656 Qualifiers &quals) {
3657 SplitQualType splitType = type.getSplitUnqualifiedType();
3659 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3660 // the unqualified desugared type and then drops it on the floor.
3661 // We then have to strip that sugar back off with
3662 // getUnqualifiedDesugaredType(), which is silly.
3663 const ArrayType *AT =
3664 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
3666 // If we don't have an array, just use the results in splitType.
3668 quals = splitType.Quals;
3669 return QualType(splitType.Ty, 0);
3672 // Otherwise, recurse on the array's element type.
3673 QualType elementType = AT->getElementType();
3674 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3676 // If that didn't change the element type, AT has no qualifiers, so we
3677 // can just use the results in splitType.
3678 if (elementType == unqualElementType) {
3679 assert(quals.empty()); // from the recursive call
3680 quals = splitType.Quals;
3681 return QualType(splitType.Ty, 0);
3684 // Otherwise, add in the qualifiers from the outermost type, then
3685 // build the type back up.
3686 quals.addConsistentQualifiers(splitType.Quals);
3688 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3689 return getConstantArrayType(unqualElementType, CAT->getSize(),
3690 CAT->getSizeModifier(), 0);
3693 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
3694 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
3697 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
3698 return getVariableArrayType(unqualElementType,
3700 VAT->getSizeModifier(),
3701 VAT->getIndexTypeCVRQualifiers(),
3702 VAT->getBracketsRange());
3705 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
3706 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
3707 DSAT->getSizeModifier(), 0,
3711 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3712 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3713 /// they point to and return true. If T1 and T2 aren't pointer types
3714 /// or pointer-to-member types, or if they are not similar at this
3715 /// level, returns false and leaves T1 and T2 unchanged. Top-level
3716 /// qualifiers on T1 and T2 are ignored. This function will typically
3717 /// be called in a loop that successively "unwraps" pointer and
3718 /// pointer-to-member types to compare them at each level.
3719 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3720 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3721 *T2PtrType = T2->getAs<PointerType>();
3722 if (T1PtrType && T2PtrType) {
3723 T1 = T1PtrType->getPointeeType();
3724 T2 = T2PtrType->getPointeeType();
3728 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3729 *T2MPType = T2->getAs<MemberPointerType>();
3730 if (T1MPType && T2MPType &&
3731 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3732 QualType(T2MPType->getClass(), 0))) {
3733 T1 = T1MPType->getPointeeType();
3734 T2 = T2MPType->getPointeeType();
3738 if (getLangOpts().ObjC1) {
3739 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3740 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3741 if (T1OPType && T2OPType) {
3742 T1 = T1OPType->getPointeeType();
3743 T2 = T2OPType->getPointeeType();
3748 // FIXME: Block pointers, too?
3754 ASTContext::getNameForTemplate(TemplateName Name,
3755 SourceLocation NameLoc) const {
3756 switch (Name.getKind()) {
3757 case TemplateName::QualifiedTemplate:
3758 case TemplateName::Template:
3759 // DNInfo work in progress: CHECKME: what about DNLoc?
3760 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3763 case TemplateName::OverloadedTemplate: {
3764 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3765 // DNInfo work in progress: CHECKME: what about DNLoc?
3766 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3769 case TemplateName::DependentTemplate: {
3770 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3771 DeclarationName DName;
3772 if (DTN->isIdentifier()) {
3773 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3774 return DeclarationNameInfo(DName, NameLoc);
3776 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3777 // DNInfo work in progress: FIXME: source locations?
3778 DeclarationNameLoc DNLoc;
3779 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3780 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3781 return DeclarationNameInfo(DName, NameLoc, DNLoc);
3785 case TemplateName::SubstTemplateTemplateParm: {
3786 SubstTemplateTemplateParmStorage *subst
3787 = Name.getAsSubstTemplateTemplateParm();
3788 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3792 case TemplateName::SubstTemplateTemplateParmPack: {
3793 SubstTemplateTemplateParmPackStorage *subst
3794 = Name.getAsSubstTemplateTemplateParmPack();
3795 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3800 llvm_unreachable("bad template name kind!");
3803 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
3804 switch (Name.getKind()) {
3805 case TemplateName::QualifiedTemplate:
3806 case TemplateName::Template: {
3807 TemplateDecl *Template = Name.getAsTemplateDecl();
3808 if (TemplateTemplateParmDecl *TTP
3809 = dyn_cast<TemplateTemplateParmDecl>(Template))
3810 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3812 // The canonical template name is the canonical template declaration.
3813 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
3816 case TemplateName::OverloadedTemplate:
3817 llvm_unreachable("cannot canonicalize overloaded template");
3819 case TemplateName::DependentTemplate: {
3820 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3821 assert(DTN && "Non-dependent template names must refer to template decls.");
3822 return DTN->CanonicalTemplateName;
3825 case TemplateName::SubstTemplateTemplateParm: {
3826 SubstTemplateTemplateParmStorage *subst
3827 = Name.getAsSubstTemplateTemplateParm();
3828 return getCanonicalTemplateName(subst->getReplacement());
3831 case TemplateName::SubstTemplateTemplateParmPack: {
3832 SubstTemplateTemplateParmPackStorage *subst
3833 = Name.getAsSubstTemplateTemplateParmPack();
3834 TemplateTemplateParmDecl *canonParameter
3835 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3836 TemplateArgument canonArgPack
3837 = getCanonicalTemplateArgument(subst->getArgumentPack());
3838 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3842 llvm_unreachable("bad template name!");
3845 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3846 X = getCanonicalTemplateName(X);
3847 Y = getCanonicalTemplateName(Y);
3848 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3852 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
3853 switch (Arg.getKind()) {
3854 case TemplateArgument::Null:
3857 case TemplateArgument::Expression:
3860 case TemplateArgument::Declaration: {
3861 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
3862 return TemplateArgument(D, Arg.isDeclForReferenceParam());
3865 case TemplateArgument::NullPtr:
3866 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
3869 case TemplateArgument::Template:
3870 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
3872 case TemplateArgument::TemplateExpansion:
3873 return TemplateArgument(getCanonicalTemplateName(
3874 Arg.getAsTemplateOrTemplatePattern()),
3875 Arg.getNumTemplateExpansions());
3877 case TemplateArgument::Integral:
3878 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
3880 case TemplateArgument::Type:
3881 return TemplateArgument(getCanonicalType(Arg.getAsType()));
3883 case TemplateArgument::Pack: {
3884 if (Arg.pack_size() == 0)
3887 TemplateArgument *CanonArgs
3888 = new (*this) TemplateArgument[Arg.pack_size()];
3890 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
3891 AEnd = Arg.pack_end();
3892 A != AEnd; (void)++A, ++Idx)
3893 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
3895 return TemplateArgument(CanonArgs, Arg.pack_size());
3899 // Silence GCC warning
3900 llvm_unreachable("Unhandled template argument kind");
3903 NestedNameSpecifier *
3904 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
3908 switch (NNS->getKind()) {
3909 case NestedNameSpecifier::Identifier:
3910 // Canonicalize the prefix but keep the identifier the same.
3911 return NestedNameSpecifier::Create(*this,
3912 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3913 NNS->getAsIdentifier());
3915 case NestedNameSpecifier::Namespace:
3916 // A namespace is canonical; build a nested-name-specifier with
3917 // this namespace and no prefix.
3918 return NestedNameSpecifier::Create(*this, 0,
3919 NNS->getAsNamespace()->getOriginalNamespace());
3921 case NestedNameSpecifier::NamespaceAlias:
3922 // A namespace is canonical; build a nested-name-specifier with
3923 // this namespace and no prefix.
3924 return NestedNameSpecifier::Create(*this, 0,
3925 NNS->getAsNamespaceAlias()->getNamespace()
3926 ->getOriginalNamespace());
3928 case NestedNameSpecifier::TypeSpec:
3929 case NestedNameSpecifier::TypeSpecWithTemplate: {
3930 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
3932 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3933 // break it apart into its prefix and identifier, then reconsititute those
3934 // as the canonical nested-name-specifier. This is required to canonicalize
3935 // a dependent nested-name-specifier involving typedefs of dependent-name
3937 // typedef typename T::type T1;
3938 // typedef typename T1::type T2;
3939 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3940 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
3941 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3943 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3944 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3946 return NestedNameSpecifier::Create(*this, 0, false,
3947 const_cast<Type*>(T.getTypePtr()));
3950 case NestedNameSpecifier::Global:
3951 // The global specifier is canonical and unique.
3955 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
3959 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
3960 // Handle the non-qualified case efficiently.
3961 if (!T.hasLocalQualifiers()) {
3962 // Handle the common positive case fast.
3963 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3967 // Handle the common negative case fast.
3968 if (!isa<ArrayType>(T.getCanonicalType()))
3971 // Apply any qualifiers from the array type to the element type. This
3972 // implements C99 6.7.3p8: "If the specification of an array type includes
3973 // any type qualifiers, the element type is so qualified, not the array type."
3975 // If we get here, we either have type qualifiers on the type, or we have
3976 // sugar such as a typedef in the way. If we have type qualifiers on the type
3977 // we must propagate them down into the element type.
3979 SplitQualType split = T.getSplitDesugaredType();
3980 Qualifiers qs = split.Quals;
3982 // If we have a simple case, just return now.
3983 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
3984 if (ATy == 0 || qs.empty())
3987 // Otherwise, we have an array and we have qualifiers on it. Push the
3988 // qualifiers into the array element type and return a new array type.
3989 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
3991 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3992 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3993 CAT->getSizeModifier(),
3994 CAT->getIndexTypeCVRQualifiers()));
3995 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3996 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3997 IAT->getSizeModifier(),
3998 IAT->getIndexTypeCVRQualifiers()));
4000 if (const DependentSizedArrayType *DSAT
4001 = dyn_cast<DependentSizedArrayType>(ATy))
4002 return cast<ArrayType>(
4003 getDependentSizedArrayType(NewEltTy,
4004 DSAT->getSizeExpr(),
4005 DSAT->getSizeModifier(),
4006 DSAT->getIndexTypeCVRQualifiers(),
4007 DSAT->getBracketsRange()));
4009 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4010 return cast<ArrayType>(getVariableArrayType(NewEltTy,
4012 VAT->getSizeModifier(),
4013 VAT->getIndexTypeCVRQualifiers(),
4014 VAT->getBracketsRange()));
4017 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4019 // A declaration of a parameter as "array of type" shall be
4020 // adjusted to "qualified pointer to type", where the type
4021 // qualifiers (if any) are those specified within the [ and ] of
4022 // the array type derivation.
4023 if (T->isArrayType())
4024 return getArrayDecayedType(T);
4027 // A declaration of a parameter as "function returning type"
4028 // shall be adjusted to "pointer to function returning type", as
4030 if (T->isFunctionType())
4031 return getPointerType(T);
4036 QualType ASTContext::getSignatureParameterType(QualType T) const {
4037 T = getVariableArrayDecayedType(T);
4038 T = getAdjustedParameterType(T);
4039 return T.getUnqualifiedType();
4042 /// getArrayDecayedType - Return the properly qualified result of decaying the
4043 /// specified array type to a pointer. This operation is non-trivial when
4044 /// handling typedefs etc. The canonical type of "T" must be an array type,
4045 /// this returns a pointer to a properly qualified element of the array.
4047 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
4048 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4049 // Get the element type with 'getAsArrayType' so that we don't lose any
4050 // typedefs in the element type of the array. This also handles propagation
4051 // of type qualifiers from the array type into the element type if present
4053 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4054 assert(PrettyArrayType && "Not an array type!");
4056 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4058 // int x[restrict 4] -> int *restrict
4059 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
4062 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4063 return getBaseElementType(array->getElementType());
4066 QualType ASTContext::getBaseElementType(QualType type) const {
4069 SplitQualType split = type.getSplitDesugaredType();
4070 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4073 type = array->getElementType();
4074 qs.addConsistentQualifiers(split.Quals);
4077 return getQualifiedType(type, qs);
4080 /// getConstantArrayElementCount - Returns number of constant array elements.
4082 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
4083 uint64_t ElementCount = 1;
4085 ElementCount *= CA->getSize().getZExtValue();
4086 CA = dyn_cast_or_null<ConstantArrayType>(
4087 CA->getElementType()->getAsArrayTypeUnsafe());
4089 return ElementCount;
4092 /// getFloatingRank - Return a relative rank for floating point types.
4093 /// This routine will assert if passed a built-in type that isn't a float.
4094 static FloatingRank getFloatingRank(QualType T) {
4095 if (const ComplexType *CT = T->getAs<ComplexType>())
4096 return getFloatingRank(CT->getElementType());
4098 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4099 switch (T->getAs<BuiltinType>()->getKind()) {
4100 default: llvm_unreachable("getFloatingRank(): not a floating type");
4101 case BuiltinType::Half: return HalfRank;
4102 case BuiltinType::Float: return FloatRank;
4103 case BuiltinType::Double: return DoubleRank;
4104 case BuiltinType::LongDouble: return LongDoubleRank;
4108 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4109 /// point or a complex type (based on typeDomain/typeSize).
4110 /// 'typeDomain' is a real floating point or complex type.
4111 /// 'typeSize' is a real floating point or complex type.
4112 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4113 QualType Domain) const {
4114 FloatingRank EltRank = getFloatingRank(Size);
4115 if (Domain->isComplexType()) {
4117 case HalfRank: llvm_unreachable("Complex half is not supported");
4118 case FloatRank: return FloatComplexTy;
4119 case DoubleRank: return DoubleComplexTy;
4120 case LongDoubleRank: return LongDoubleComplexTy;
4124 assert(Domain->isRealFloatingType() && "Unknown domain!");
4126 case HalfRank: return HalfTy;
4127 case FloatRank: return FloatTy;
4128 case DoubleRank: return DoubleTy;
4129 case LongDoubleRank: return LongDoubleTy;
4131 llvm_unreachable("getFloatingRank(): illegal value for rank");
4134 /// getFloatingTypeOrder - Compare the rank of the two specified floating
4135 /// point types, ignoring the domain of the type (i.e. 'double' ==
4136 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
4137 /// LHS < RHS, return -1.
4138 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
4139 FloatingRank LHSR = getFloatingRank(LHS);
4140 FloatingRank RHSR = getFloatingRank(RHS);
4149 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4150 /// routine will assert if passed a built-in type that isn't an integer or enum,
4151 /// or if it is not canonicalized.
4152 unsigned ASTContext::getIntegerRank(const Type *T) const {
4153 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
4155 switch (cast<BuiltinType>(T)->getKind()) {
4156 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
4157 case BuiltinType::Bool:
4158 return 1 + (getIntWidth(BoolTy) << 3);
4159 case BuiltinType::Char_S:
4160 case BuiltinType::Char_U:
4161 case BuiltinType::SChar:
4162 case BuiltinType::UChar:
4163 return 2 + (getIntWidth(CharTy) << 3);
4164 case BuiltinType::Short:
4165 case BuiltinType::UShort:
4166 return 3 + (getIntWidth(ShortTy) << 3);
4167 case BuiltinType::Int:
4168 case BuiltinType::UInt:
4169 return 4 + (getIntWidth(IntTy) << 3);
4170 case BuiltinType::Long:
4171 case BuiltinType::ULong:
4172 return 5 + (getIntWidth(LongTy) << 3);
4173 case BuiltinType::LongLong:
4174 case BuiltinType::ULongLong:
4175 return 6 + (getIntWidth(LongLongTy) << 3);
4176 case BuiltinType::Int128:
4177 case BuiltinType::UInt128:
4178 return 7 + (getIntWidth(Int128Ty) << 3);
4182 /// \brief Whether this is a promotable bitfield reference according
4183 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4185 /// \returns the type this bit-field will promote to, or NULL if no
4186 /// promotion occurs.
4187 QualType ASTContext::isPromotableBitField(Expr *E) const {
4188 if (E->isTypeDependent() || E->isValueDependent())
4191 FieldDecl *Field = E->getBitField();
4195 QualType FT = Field->getType();
4197 uint64_t BitWidth = Field->getBitWidthValue(*this);
4198 uint64_t IntSize = getTypeSize(IntTy);
4199 // GCC extension compatibility: if the bit-field size is less than or equal
4200 // to the size of int, it gets promoted no matter what its type is.
4201 // For instance, unsigned long bf : 4 gets promoted to signed int.
4202 if (BitWidth < IntSize)
4205 if (BitWidth == IntSize)
4206 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4208 // Types bigger than int are not subject to promotions, and therefore act
4209 // like the base type.
4210 // FIXME: This doesn't quite match what gcc does, but what gcc does here
4215 /// getPromotedIntegerType - Returns the type that Promotable will
4216 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4218 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
4219 assert(!Promotable.isNull());
4220 assert(Promotable->isPromotableIntegerType());
4221 if (const EnumType *ET = Promotable->getAs<EnumType>())
4222 return ET->getDecl()->getPromotionType();
4224 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4225 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4226 // (3.9.1) can be converted to a prvalue of the first of the following
4227 // types that can represent all the values of its underlying type:
4228 // int, unsigned int, long int, unsigned long int, long long int, or
4229 // unsigned long long int [...]
4230 // FIXME: Is there some better way to compute this?
4231 if (BT->getKind() == BuiltinType::WChar_S ||
4232 BT->getKind() == BuiltinType::WChar_U ||
4233 BT->getKind() == BuiltinType::Char16 ||
4234 BT->getKind() == BuiltinType::Char32) {
4235 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4236 uint64_t FromSize = getTypeSize(BT);
4237 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4238 LongLongTy, UnsignedLongLongTy };
4239 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4240 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4241 if (FromSize < ToSize ||
4242 (FromSize == ToSize &&
4243 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4244 return PromoteTypes[Idx];
4246 llvm_unreachable("char type should fit into long long");
4250 // At this point, we should have a signed or unsigned integer type.
4251 if (Promotable->isSignedIntegerType())
4253 uint64_t PromotableSize = getIntWidth(Promotable);
4254 uint64_t IntSize = getIntWidth(IntTy);
4255 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4256 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4259 /// \brief Recurses in pointer/array types until it finds an objc retainable
4260 /// type and returns its ownership.
4261 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4262 while (!T.isNull()) {
4263 if (T.getObjCLifetime() != Qualifiers::OCL_None)
4264 return T.getObjCLifetime();
4265 if (T->isArrayType())
4266 T = getBaseElementType(T);
4267 else if (const PointerType *PT = T->getAs<PointerType>())
4268 T = PT->getPointeeType();
4269 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4270 T = RT->getPointeeType();
4275 return Qualifiers::OCL_None;
4278 /// getIntegerTypeOrder - Returns the highest ranked integer type:
4279 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
4280 /// LHS < RHS, return -1.
4281 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
4282 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4283 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
4284 if (LHSC == RHSC) return 0;
4286 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4287 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
4289 unsigned LHSRank = getIntegerRank(LHSC);
4290 unsigned RHSRank = getIntegerRank(RHSC);
4292 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
4293 if (LHSRank == RHSRank) return 0;
4294 return LHSRank > RHSRank ? 1 : -1;
4297 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4299 // If the unsigned [LHS] type is larger, return it.
4300 if (LHSRank >= RHSRank)
4303 // If the signed type can represent all values of the unsigned type, it
4304 // wins. Because we are dealing with 2's complement and types that are
4305 // powers of two larger than each other, this is always safe.
4309 // If the unsigned [RHS] type is larger, return it.
4310 if (RHSRank >= LHSRank)
4313 // If the signed type can represent all values of the unsigned type, it
4314 // wins. Because we are dealing with 2's complement and types that are
4315 // powers of two larger than each other, this is always safe.
4320 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
4321 DeclContext *DC, IdentifierInfo *Id) {
4323 if (Ctx.getLangOpts().CPlusPlus)
4324 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
4326 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
4329 // getCFConstantStringType - Return the type used for constant CFStrings.
4330 QualType ASTContext::getCFConstantStringType() const {
4331 if (!CFConstantStringTypeDecl) {
4332 CFConstantStringTypeDecl =
4333 CreateRecordDecl(*this, TTK_Struct, TUDecl,
4334 &Idents.get("NSConstantString"));
4335 CFConstantStringTypeDecl->startDefinition();
4337 QualType FieldTypes[4];
4340 FieldTypes[0] = getPointerType(IntTy.withConst());
4342 FieldTypes[1] = IntTy;
4344 FieldTypes[2] = getPointerType(CharTy.withConst());
4346 FieldTypes[3] = LongTy;
4349 for (unsigned i = 0; i < 4; ++i) {
4350 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
4352 SourceLocation(), 0,
4353 FieldTypes[i], /*TInfo=*/0,
4357 Field->setAccess(AS_public);
4358 CFConstantStringTypeDecl->addDecl(Field);
4361 CFConstantStringTypeDecl->completeDefinition();
4364 return getTagDeclType(CFConstantStringTypeDecl);
4367 QualType ASTContext::getObjCSuperType() const {
4368 if (ObjCSuperType.isNull()) {
4369 RecordDecl *ObjCSuperTypeDecl =
4370 CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get("objc_super"));
4371 TUDecl->addDecl(ObjCSuperTypeDecl);
4372 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4374 return ObjCSuperType;
4377 void ASTContext::setCFConstantStringType(QualType T) {
4378 const RecordType *Rec = T->getAs<RecordType>();
4379 assert(Rec && "Invalid CFConstantStringType");
4380 CFConstantStringTypeDecl = Rec->getDecl();
4383 QualType ASTContext::getBlockDescriptorType() const {
4384 if (BlockDescriptorType)
4385 return getTagDeclType(BlockDescriptorType);
4388 // FIXME: Needs the FlagAppleBlock bit.
4389 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
4390 &Idents.get("__block_descriptor"));
4391 T->startDefinition();
4393 QualType FieldTypes[] = {
4398 const char *FieldNames[] = {
4403 for (size_t i = 0; i < 2; ++i) {
4404 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
4406 &Idents.get(FieldNames[i]),
4407 FieldTypes[i], /*TInfo=*/0,
4411 Field->setAccess(AS_public);
4415 T->completeDefinition();
4417 BlockDescriptorType = T;
4419 return getTagDeclType(BlockDescriptorType);
4422 QualType ASTContext::getBlockDescriptorExtendedType() const {
4423 if (BlockDescriptorExtendedType)
4424 return getTagDeclType(BlockDescriptorExtendedType);
4427 // FIXME: Needs the FlagAppleBlock bit.
4428 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
4429 &Idents.get("__block_descriptor_withcopydispose"));
4430 T->startDefinition();
4432 QualType FieldTypes[] = {
4435 getPointerType(VoidPtrTy),
4436 getPointerType(VoidPtrTy)
4439 const char *FieldNames[] = {
4446 for (size_t i = 0; i < 4; ++i) {
4447 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
4449 &Idents.get(FieldNames[i]),
4450 FieldTypes[i], /*TInfo=*/0,
4454 Field->setAccess(AS_public);
4458 T->completeDefinition();
4460 BlockDescriptorExtendedType = T;
4462 return getTagDeclType(BlockDescriptorExtendedType);
4465 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4466 /// requires copy/dispose. Note that this must match the logic
4467 /// in buildByrefHelpers.
4468 bool ASTContext::BlockRequiresCopying(QualType Ty,
4470 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4471 const Expr *copyExpr = getBlockVarCopyInits(D);
4472 if (!copyExpr && record->hasTrivialDestructor()) return false;
4477 if (!Ty->isObjCRetainableType()) return false;
4479 Qualifiers qs = Ty.getQualifiers();
4481 // If we have lifetime, that dominates.
4482 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4483 assert(getLangOpts().ObjCAutoRefCount);
4486 case Qualifiers::OCL_None: llvm_unreachable("impossible");
4488 // These are just bits as far as the runtime is concerned.
4489 case Qualifiers::OCL_ExplicitNone:
4490 case Qualifiers::OCL_Autoreleasing:
4493 // Tell the runtime that this is ARC __weak, called by the
4495 case Qualifiers::OCL_Weak:
4496 // ARC __strong __block variables need to be retained.
4497 case Qualifiers::OCL_Strong:
4500 llvm_unreachable("fell out of lifetime switch!");
4502 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4503 Ty->isObjCObjectPointerType());
4506 bool ASTContext::getByrefLifetime(QualType Ty,
4507 Qualifiers::ObjCLifetime &LifeTime,
4508 bool &HasByrefExtendedLayout) const {
4510 if (!getLangOpts().ObjC1 ||
4511 getLangOpts().getGC() != LangOptions::NonGC)
4514 HasByrefExtendedLayout = false;
4515 if (Ty->isRecordType()) {
4516 HasByrefExtendedLayout = true;
4517 LifeTime = Qualifiers::OCL_None;
4519 else if (getLangOpts().ObjCAutoRefCount)
4520 LifeTime = Ty.getObjCLifetime();
4522 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4523 LifeTime = Qualifiers::OCL_ExplicitNone;
4525 LifeTime = Qualifiers::OCL_None;
4529 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4530 if (!ObjCInstanceTypeDecl)
4531 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4532 getTranslationUnitDecl(),
4535 &Idents.get("instancetype"),
4536 getTrivialTypeSourceInfo(getObjCIdType()));
4537 return ObjCInstanceTypeDecl;
4540 // This returns true if a type has been typedefed to BOOL:
4541 // typedef <type> BOOL;
4542 static bool isTypeTypedefedAsBOOL(QualType T) {
4543 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
4544 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4545 return II->isStr("BOOL");
4550 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
4552 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
4553 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4554 return CharUnits::Zero();
4556 CharUnits sz = getTypeSizeInChars(type);
4558 // Make all integer and enum types at least as large as an int
4559 if (sz.isPositive() && type->isIntegralOrEnumerationType())
4560 sz = std::max(sz, getTypeSizeInChars(IntTy));
4561 // Treat arrays as pointers, since that's how they're passed in.
4562 else if (type->isArrayType())
4563 sz = getTypeSizeInChars(VoidPtrTy);
4568 std::string charUnitsToString(const CharUnits &CU) {
4569 return llvm::itostr(CU.getQuantity());
4572 /// getObjCEncodingForBlock - Return the encoded type for this block
4574 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4577 const BlockDecl *Decl = Expr->getBlockDecl();
4579 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4580 // Encode result type.
4581 if (getLangOpts().EncodeExtendedBlockSig)
4582 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None,
4583 BlockTy->getAs<FunctionType>()->getResultType(),
4584 S, true /*Extended*/);
4586 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(),
4588 // Compute size of all parameters.
4589 // Start with computing size of a pointer in number of bytes.
4590 // FIXME: There might(should) be a better way of doing this computation!
4592 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4593 CharUnits ParmOffset = PtrSize;
4594 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
4595 E = Decl->param_end(); PI != E; ++PI) {
4596 QualType PType = (*PI)->getType();
4597 CharUnits sz = getObjCEncodingTypeSize(PType);
4600 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
4603 // Size of the argument frame
4604 S += charUnitsToString(ParmOffset);
4605 // Block pointer and offset.
4609 ParmOffset = PtrSize;
4610 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4611 Decl->param_end(); PI != E; ++PI) {
4612 ParmVarDecl *PVDecl = *PI;
4613 QualType PType = PVDecl->getOriginalType();
4614 if (const ArrayType *AT =
4615 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4616 // Use array's original type only if it has known number of
4618 if (!isa<ConstantArrayType>(AT))
4619 PType = PVDecl->getType();
4620 } else if (PType->isFunctionType())
4621 PType = PVDecl->getType();
4622 if (getLangOpts().EncodeExtendedBlockSig)
4623 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
4624 S, true /*Extended*/);
4626 getObjCEncodingForType(PType, S);
4627 S += charUnitsToString(ParmOffset);
4628 ParmOffset += getObjCEncodingTypeSize(PType);
4634 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
4636 // Encode result type.
4637 getObjCEncodingForType(Decl->getResultType(), S);
4638 CharUnits ParmOffset;
4639 // Compute size of all parameters.
4640 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4641 E = Decl->param_end(); PI != E; ++PI) {
4642 QualType PType = (*PI)->getType();
4643 CharUnits sz = getObjCEncodingTypeSize(PType);
4647 assert (sz.isPositive() &&
4648 "getObjCEncodingForFunctionDecl - Incomplete param type");
4651 S += charUnitsToString(ParmOffset);
4652 ParmOffset = CharUnits::Zero();
4655 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4656 E = Decl->param_end(); PI != E; ++PI) {
4657 ParmVarDecl *PVDecl = *PI;
4658 QualType PType = PVDecl->getOriginalType();
4659 if (const ArrayType *AT =
4660 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4661 // Use array's original type only if it has known number of
4663 if (!isa<ConstantArrayType>(AT))
4664 PType = PVDecl->getType();
4665 } else if (PType->isFunctionType())
4666 PType = PVDecl->getType();
4667 getObjCEncodingForType(PType, S);
4668 S += charUnitsToString(ParmOffset);
4669 ParmOffset += getObjCEncodingTypeSize(PType);
4675 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
4676 /// method parameter or return type. If Extended, include class names and
4677 /// block object types.
4678 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4679 QualType T, std::string& S,
4680 bool Extended) const {
4681 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4682 getObjCEncodingForTypeQualifier(QT, S);
4683 // Encode parameter type.
4684 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4685 true /*OutermostType*/,
4686 false /*EncodingProperty*/,
4687 false /*StructField*/,
4688 Extended /*EncodeBlockParameters*/,
4689 Extended /*EncodeClassNames*/);
4692 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
4694 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
4696 bool Extended) const {
4697 // FIXME: This is not very efficient.
4698 // Encode return type.
4699 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4700 Decl->getResultType(), S, Extended);
4701 // Compute size of all parameters.
4702 // Start with computing size of a pointer in number of bytes.
4703 // FIXME: There might(should) be a better way of doing this computation!
4705 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4706 // The first two arguments (self and _cmd) are pointers; account for
4708 CharUnits ParmOffset = 2 * PtrSize;
4709 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4710 E = Decl->sel_param_end(); PI != E; ++PI) {
4711 QualType PType = (*PI)->getType();
4712 CharUnits sz = getObjCEncodingTypeSize(PType);
4716 assert (sz.isPositive() &&
4717 "getObjCEncodingForMethodDecl - Incomplete param type");
4720 S += charUnitsToString(ParmOffset);
4722 S += charUnitsToString(PtrSize);
4725 ParmOffset = 2 * PtrSize;
4726 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4727 E = Decl->sel_param_end(); PI != E; ++PI) {
4728 const ParmVarDecl *PVDecl = *PI;
4729 QualType PType = PVDecl->getOriginalType();
4730 if (const ArrayType *AT =
4731 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4732 // Use array's original type only if it has known number of
4734 if (!isa<ConstantArrayType>(AT))
4735 PType = PVDecl->getType();
4736 } else if (PType->isFunctionType())
4737 PType = PVDecl->getType();
4738 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4739 PType, S, Extended);
4740 S += charUnitsToString(ParmOffset);
4741 ParmOffset += getObjCEncodingTypeSize(PType);
4747 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
4748 /// property declaration. If non-NULL, Container must be either an
4749 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4750 /// NULL when getting encodings for protocol properties.
4751 /// Property attributes are stored as a comma-delimited C string. The simple
4752 /// attributes readonly and bycopy are encoded as single characters. The
4753 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
4754 /// encoded as single characters, followed by an identifier. Property types
4755 /// are also encoded as a parametrized attribute. The characters used to encode
4756 /// these attributes are defined by the following enumeration:
4758 /// enum PropertyAttributes {
4759 /// kPropertyReadOnly = 'R', // property is read-only.
4760 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4761 /// kPropertyByref = '&', // property is a reference to the value last assigned
4762 /// kPropertyDynamic = 'D', // property is dynamic
4763 /// kPropertyGetter = 'G', // followed by getter selector name
4764 /// kPropertySetter = 'S', // followed by setter selector name
4765 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
4766 /// kPropertyType = 'T' // followed by old-style type encoding.
4767 /// kPropertyWeak = 'W' // 'weak' property
4768 /// kPropertyStrong = 'P' // property GC'able
4769 /// kPropertyNonAtomic = 'N' // property non-atomic
4772 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
4773 const Decl *Container,
4774 std::string& S) const {
4775 // Collect information from the property implementation decl(s).
4776 bool Dynamic = false;
4777 ObjCPropertyImplDecl *SynthesizePID = 0;
4779 // FIXME: Duplicated code due to poor abstraction.
4781 if (const ObjCCategoryImplDecl *CID =
4782 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4783 for (ObjCCategoryImplDecl::propimpl_iterator
4784 i = CID->propimpl_begin(), e = CID->propimpl_end();
4786 ObjCPropertyImplDecl *PID = *i;
4787 if (PID->getPropertyDecl() == PD) {
4788 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4791 SynthesizePID = PID;
4796 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4797 for (ObjCCategoryImplDecl::propimpl_iterator
4798 i = OID->propimpl_begin(), e = OID->propimpl_end();
4800 ObjCPropertyImplDecl *PID = *i;
4801 if (PID->getPropertyDecl() == PD) {
4802 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4805 SynthesizePID = PID;
4812 // FIXME: This is not very efficient.
4815 // Encode result type.
4816 // GCC has some special rules regarding encoding of properties which
4817 // closely resembles encoding of ivars.
4818 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
4819 true /* outermost type */,
4820 true /* encoding for property */);
4822 if (PD->isReadOnly()) {
4825 switch (PD->getSetterKind()) {
4826 case ObjCPropertyDecl::Assign: break;
4827 case ObjCPropertyDecl::Copy: S += ",C"; break;
4828 case ObjCPropertyDecl::Retain: S += ",&"; break;
4829 case ObjCPropertyDecl::Weak: S += ",W"; break;
4833 // It really isn't clear at all what this means, since properties
4834 // are "dynamic by default".
4838 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4841 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4843 S += PD->getGetterName().getAsString();
4846 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4848 S += PD->getSetterName().getAsString();
4851 if (SynthesizePID) {
4852 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4854 S += OID->getNameAsString();
4857 // FIXME: OBJCGC: weak & strong
4860 /// getLegacyIntegralTypeEncoding -
4861 /// Another legacy compatibility encoding: 32-bit longs are encoded as
4862 /// 'l' or 'L' , but not always. For typedefs, we need to use
4863 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
4865 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
4866 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
4867 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
4868 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
4869 PointeeTy = UnsignedIntTy;
4871 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
4877 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
4878 const FieldDecl *Field) const {
4879 // We follow the behavior of gcc, expanding structures which are
4880 // directly pointed to, and expanding embedded structures. Note that
4881 // these rules are sufficient to prevent recursive encoding of the
4883 getObjCEncodingForTypeImpl(T, S, true, true, Field,
4884 true /* outermost type */);
4887 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
4888 BuiltinType::Kind kind) {
4890 case BuiltinType::Void: return 'v';
4891 case BuiltinType::Bool: return 'B';
4892 case BuiltinType::Char_U:
4893 case BuiltinType::UChar: return 'C';
4894 case BuiltinType::Char16:
4895 case BuiltinType::UShort: return 'S';
4896 case BuiltinType::Char32:
4897 case BuiltinType::UInt: return 'I';
4898 case BuiltinType::ULong:
4899 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
4900 case BuiltinType::UInt128: return 'T';
4901 case BuiltinType::ULongLong: return 'Q';
4902 case BuiltinType::Char_S:
4903 case BuiltinType::SChar: return 'c';
4904 case BuiltinType::Short: return 's';
4905 case BuiltinType::WChar_S:
4906 case BuiltinType::WChar_U:
4907 case BuiltinType::Int: return 'i';
4908 case BuiltinType::Long:
4909 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
4910 case BuiltinType::LongLong: return 'q';
4911 case BuiltinType::Int128: return 't';
4912 case BuiltinType::Float: return 'f';
4913 case BuiltinType::Double: return 'd';
4914 case BuiltinType::LongDouble: return 'D';
4915 case BuiltinType::NullPtr: return '*'; // like char*
4917 case BuiltinType::Half:
4918 // FIXME: potentially need @encodes for these!
4921 case BuiltinType::ObjCId:
4922 case BuiltinType::ObjCClass:
4923 case BuiltinType::ObjCSel:
4924 llvm_unreachable("@encoding ObjC primitive type");
4926 // OpenCL and placeholder types don't need @encodings.
4927 case BuiltinType::OCLImage1d:
4928 case BuiltinType::OCLImage1dArray:
4929 case BuiltinType::OCLImage1dBuffer:
4930 case BuiltinType::OCLImage2d:
4931 case BuiltinType::OCLImage2dArray:
4932 case BuiltinType::OCLImage3d:
4933 case BuiltinType::OCLEvent:
4934 case BuiltinType::OCLSampler:
4935 case BuiltinType::Dependent:
4936 #define BUILTIN_TYPE(KIND, ID)
4937 #define PLACEHOLDER_TYPE(KIND, ID) \
4938 case BuiltinType::KIND:
4939 #include "clang/AST/BuiltinTypes.def"
4940 llvm_unreachable("invalid builtin type for @encode");
4942 llvm_unreachable("invalid BuiltinType::Kind value");
4945 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4946 EnumDecl *Enum = ET->getDecl();
4948 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4949 if (!Enum->isFixed())
4952 // The encoding of a fixed enum type matches its fixed underlying type.
4953 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
4954 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
4957 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
4958 QualType T, const FieldDecl *FD) {
4959 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
4961 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4962 // The GNU runtime requires more information; bitfields are encoded as b,
4963 // then the offset (in bits) of the first element, then the type of the
4964 // bitfield, then the size in bits. For example, in this structure:
4971 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4972 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4973 // information is not especially sensible, but we're stuck with it for
4974 // compatibility with GCC, although providing it breaks anything that
4975 // actually uses runtime introspection and wants to work on both runtimes...
4976 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
4977 const RecordDecl *RD = FD->getParent();
4978 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4979 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
4980 if (const EnumType *ET = T->getAs<EnumType>())
4981 S += ObjCEncodingForEnumType(Ctx, ET);
4983 const BuiltinType *BT = T->castAs<BuiltinType>();
4984 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
4987 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
4990 // FIXME: Use SmallString for accumulating string.
4991 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4992 bool ExpandPointedToStructures,
4993 bool ExpandStructures,
4994 const FieldDecl *FD,
4996 bool EncodingProperty,
4998 bool EncodeBlockParameters,
4999 bool EncodeClassNames,
5000 bool EncodePointerToObjCTypedef) const {
5001 CanQualType CT = getCanonicalType(T);
5002 switch (CT->getTypeClass()) {
5005 if (FD && FD->isBitField())
5006 return EncodeBitField(this, S, T, FD);
5007 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5008 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5010 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5013 case Type::Complex: {
5014 const ComplexType *CT = T->castAs<ComplexType>();
5016 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
5021 case Type::Atomic: {
5022 const AtomicType *AT = T->castAs<AtomicType>();
5024 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, 0,
5029 // encoding for pointer or reference types.
5031 case Type::LValueReference:
5032 case Type::RValueReference: {
5034 if (isa<PointerType>(CT)) {
5035 const PointerType *PT = T->castAs<PointerType>();
5036 if (PT->isObjCSelType()) {
5040 PointeeTy = PT->getPointeeType();
5042 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5045 bool isReadOnly = false;
5046 // For historical/compatibility reasons, the read-only qualifier of the
5047 // pointee gets emitted _before_ the '^'. The read-only qualifier of
5048 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5049 // Also, do not emit the 'r' for anything but the outermost type!
5050 if (isa<TypedefType>(T.getTypePtr())) {
5051 if (OutermostType && T.isConstQualified()) {
5055 } else if (OutermostType) {
5056 QualType P = PointeeTy;
5057 while (P->getAs<PointerType>())
5058 P = P->getAs<PointerType>()->getPointeeType();
5059 if (P.isConstQualified()) {
5065 // Another legacy compatibility encoding. Some ObjC qualifier and type
5066 // combinations need to be rearranged.
5067 // Rewrite "in const" from "nr" to "rn"
5068 if (StringRef(S).endswith("nr"))
5069 S.replace(S.end()-2, S.end(), "rn");
5072 if (PointeeTy->isCharType()) {
5073 // char pointer types should be encoded as '*' unless it is a
5074 // type that has been typedef'd to 'BOOL'.
5075 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5079 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5080 // GCC binary compat: Need to convert "struct objc_class *" to "#".
5081 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5085 // GCC binary compat: Need to convert "struct objc_object *" to "@".
5086 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5093 getLegacyIntegralTypeEncoding(PointeeTy);
5095 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5100 case Type::ConstantArray:
5101 case Type::IncompleteArray:
5102 case Type::VariableArray: {
5103 const ArrayType *AT = cast<ArrayType>(CT);
5105 if (isa<IncompleteArrayType>(AT) && !StructField) {
5106 // Incomplete arrays are encoded as a pointer to the array element.
5109 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5110 false, ExpandStructures, FD);
5114 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
5115 if (getTypeSize(CAT->getElementType()) == 0)
5118 S += llvm::utostr(CAT->getSize().getZExtValue());
5120 //Variable length arrays are encoded as a regular array with 0 elements.
5121 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5122 "Unknown array type!");
5126 getObjCEncodingForTypeImpl(AT->getElementType(), S,
5127 false, ExpandStructures, FD);
5133 case Type::FunctionNoProto:
5134 case Type::FunctionProto:
5138 case Type::Record: {
5139 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5140 S += RDecl->isUnion() ? '(' : '{';
5141 // Anonymous structures print as '?'
5142 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5144 if (ClassTemplateSpecializationDecl *Spec
5145 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5146 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5147 llvm::raw_string_ostream OS(S);
5148 TemplateSpecializationType::PrintTemplateArgumentList(OS,
5149 TemplateArgs.data(),
5150 TemplateArgs.size(),
5151 (*this).getPrintingPolicy());
5156 if (ExpandStructures) {
5158 if (!RDecl->isUnion()) {
5159 getObjCEncodingForStructureImpl(RDecl, S, FD);
5161 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5162 FieldEnd = RDecl->field_end();
5163 Field != FieldEnd; ++Field) {
5166 S += Field->getNameAsString();
5170 // Special case bit-fields.
5171 if (Field->isBitField()) {
5172 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5175 QualType qt = Field->getType();
5176 getLegacyIntegralTypeEncoding(qt);
5177 getObjCEncodingForTypeImpl(qt, S, false, true,
5178 FD, /*OutermostType*/false,
5179 /*EncodingProperty*/false,
5180 /*StructField*/true);
5185 S += RDecl->isUnion() ? ')' : '}';
5189 case Type::BlockPointer: {
5190 const BlockPointerType *BT = T->castAs<BlockPointerType>();
5191 S += "@?"; // Unlike a pointer-to-function, which is "^?".
5192 if (EncodeBlockParameters) {
5193 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5196 // Block return type
5197 getObjCEncodingForTypeImpl(FT->getResultType(), S,
5198 ExpandPointedToStructures, ExpandStructures,
5200 false /* OutermostType */,
5202 false /* StructField */,
5203 EncodeBlockParameters,
5208 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5209 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
5210 E = FPT->arg_type_end(); I && (I != E); ++I) {
5211 getObjCEncodingForTypeImpl(*I, S,
5212 ExpandPointedToStructures,
5215 false /* OutermostType */,
5217 false /* StructField */,
5218 EncodeBlockParameters,
5227 case Type::ObjCObject:
5228 case Type::ObjCInterface: {
5229 // Ignore protocol qualifiers when mangling at this level.
5230 T = T->castAs<ObjCObjectType>()->getBaseType();
5232 // The assumption seems to be that this assert will succeed
5233 // because nested levels will have filtered out 'id' and 'Class'.
5234 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>();
5235 // @encode(class_name)
5236 ObjCInterfaceDecl *OI = OIT->getDecl();
5238 const IdentifierInfo *II = OI->getIdentifier();
5241 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5242 DeepCollectObjCIvars(OI, true, Ivars);
5243 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5244 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5245 if (Field->isBitField())
5246 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5248 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5249 false, false, false, false, false,
5250 EncodePointerToObjCTypedef);
5256 case Type::ObjCObjectPointer: {
5257 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5258 if (OPT->isObjCIdType()) {
5263 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5264 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5265 // Since this is a binary compatibility issue, need to consult with runtime
5266 // folks. Fortunately, this is a *very* obsure construct.
5271 if (OPT->isObjCQualifiedIdType()) {
5272 getObjCEncodingForTypeImpl(getObjCIdType(), S,
5273 ExpandPointedToStructures,
5274 ExpandStructures, FD);
5275 if (FD || EncodingProperty || EncodeClassNames) {
5276 // Note that we do extended encoding of protocol qualifer list
5277 // Only when doing ivar or property encoding.
5279 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5280 E = OPT->qual_end(); I != E; ++I) {
5282 S += (*I)->getNameAsString();
5290 QualType PointeeTy = OPT->getPointeeType();
5291 if (!EncodingProperty &&
5292 isa<TypedefType>(PointeeTy.getTypePtr()) &&
5293 !EncodePointerToObjCTypedef) {
5294 // Another historical/compatibility reason.
5295 // We encode the underlying type which comes out as
5298 getObjCEncodingForTypeImpl(PointeeTy, S,
5299 false, ExpandPointedToStructures,
5301 false, false, false, false, false,
5302 /*EncodePointerToObjCTypedef*/true);
5307 if (OPT->getInterfaceDecl() &&
5308 (FD || EncodingProperty || EncodeClassNames)) {
5310 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
5311 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
5312 E = OPT->qual_end(); I != E; ++I) {
5314 S += (*I)->getNameAsString();
5322 // gcc just blithely ignores member pointers.
5323 // FIXME: we shoul do better than that. 'M' is available.
5324 case Type::MemberPointer:
5328 case Type::ExtVector:
5329 // This matches gcc's encoding, even though technically it is
5331 // FIXME. We should do a better job than gcc.
5334 #define ABSTRACT_TYPE(KIND, BASE)
5335 #define TYPE(KIND, BASE)
5336 #define DEPENDENT_TYPE(KIND, BASE) \
5338 #define NON_CANONICAL_TYPE(KIND, BASE) \
5340 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5342 #include "clang/AST/TypeNodes.def"
5343 llvm_unreachable("@encode for dependent type!");
5345 llvm_unreachable("bad type kind!");
5348 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5350 const FieldDecl *FD,
5351 bool includeVBases) const {
5352 assert(RDecl && "Expected non-null RecordDecl");
5353 assert(!RDecl->isUnion() && "Should not be called for unions");
5354 if (!RDecl->getDefinition())
5357 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5358 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5359 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5362 for (CXXRecordDecl::base_class_iterator
5363 BI = CXXRec->bases_begin(),
5364 BE = CXXRec->bases_end(); BI != BE; ++BI) {
5365 if (!BI->isVirtual()) {
5366 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
5367 if (base->isEmpty())
5369 uint64_t offs = toBits(layout.getBaseClassOffset(base));
5370 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5371 std::make_pair(offs, base));
5377 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
5378 FieldEnd = RDecl->field_end();
5379 Field != FieldEnd; ++Field, ++i) {
5380 uint64_t offs = layout.getFieldOffset(i);
5381 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5382 std::make_pair(offs, *Field));
5385 if (CXXRec && includeVBases) {
5386 for (CXXRecordDecl::base_class_iterator
5387 BI = CXXRec->vbases_begin(),
5388 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
5389 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
5390 if (base->isEmpty())
5392 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
5393 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5394 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5395 std::make_pair(offs, base));
5401 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5403 size = layout.getSize();
5406 uint64_t CurOffs = 0;
5407 std::multimap<uint64_t, NamedDecl *>::iterator
5408 CurLayObj = FieldOrBaseOffsets.begin();
5410 if (CXXRec && CXXRec->isDynamicClass() &&
5411 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
5414 std::string recname = CXXRec->getNameAsString();
5415 if (recname.empty()) recname = "?";
5420 CurOffs += getTypeSize(VoidPtrTy);
5423 if (!RDecl->hasFlexibleArrayMember()) {
5424 // Mark the end of the structure.
5425 uint64_t offs = toBits(size);
5426 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5427 std::make_pair(offs, (NamedDecl*)0));
5430 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5431 assert(CurOffs <= CurLayObj->first);
5433 if (CurOffs < CurLayObj->first) {
5434 uint64_t padding = CurLayObj->first - CurOffs;
5435 // FIXME: There doesn't seem to be a way to indicate in the encoding that
5436 // packing/alignment of members is different that normal, in which case
5437 // the encoding will be out-of-sync with the real layout.
5438 // If the runtime switches to just consider the size of types without
5439 // taking into account alignment, we could make padding explicit in the
5440 // encoding (e.g. using arrays of chars). The encoding strings would be
5441 // longer then though.
5445 NamedDecl *dcl = CurLayObj->second;
5447 break; // reached end of structure.
5449 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5450 // We expand the bases without their virtual bases since those are going
5451 // in the initial structure. Note that this differs from gcc which
5452 // expands virtual bases each time one is encountered in the hierarchy,
5453 // making the encoding type bigger than it really is.
5454 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
5455 assert(!base->isEmpty());
5456 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
5458 FieldDecl *field = cast<FieldDecl>(dcl);
5461 S += field->getNameAsString();
5465 if (field->isBitField()) {
5466 EncodeBitField(this, S, field->getType(), field);
5467 CurOffs += field->getBitWidthValue(*this);
5469 QualType qt = field->getType();
5470 getLegacyIntegralTypeEncoding(qt);
5471 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5472 /*OutermostType*/false,
5473 /*EncodingProperty*/false,
5474 /*StructField*/true);
5475 CurOffs += getTypeSize(field->getType());
5481 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
5482 std::string& S) const {
5483 if (QT & Decl::OBJC_TQ_In)
5485 if (QT & Decl::OBJC_TQ_Inout)
5487 if (QT & Decl::OBJC_TQ_Out)
5489 if (QT & Decl::OBJC_TQ_Bycopy)
5491 if (QT & Decl::OBJC_TQ_Byref)
5493 if (QT & Decl::OBJC_TQ_Oneway)
5497 TypedefDecl *ASTContext::getObjCIdDecl() const {
5499 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
5500 T = getObjCObjectPointerType(T);
5501 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
5502 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5503 getTranslationUnitDecl(),
5504 SourceLocation(), SourceLocation(),
5505 &Idents.get("id"), IdInfo);
5511 TypedefDecl *ASTContext::getObjCSelDecl() const {
5513 QualType SelT = getPointerType(ObjCBuiltinSelTy);
5514 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
5515 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5516 getTranslationUnitDecl(),
5517 SourceLocation(), SourceLocation(),
5518 &Idents.get("SEL"), SelInfo);
5523 TypedefDecl *ASTContext::getObjCClassDecl() const {
5524 if (!ObjCClassDecl) {
5525 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5526 T = getObjCObjectPointerType(T);
5527 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5528 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5529 getTranslationUnitDecl(),
5530 SourceLocation(), SourceLocation(),
5531 &Idents.get("Class"), ClassInfo);
5534 return ObjCClassDecl;
5537 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5538 if (!ObjCProtocolClassDecl) {
5539 ObjCProtocolClassDecl
5540 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5542 &Idents.get("Protocol"),
5544 SourceLocation(), true);
5547 return ObjCProtocolClassDecl;
5550 //===----------------------------------------------------------------------===//
5551 // __builtin_va_list Construction Functions
5552 //===----------------------------------------------------------------------===//
5554 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5555 // typedef char* __builtin_va_list;
5556 QualType CharPtrType = Context->getPointerType(Context->CharTy);
5557 TypeSourceInfo *TInfo
5558 = Context->getTrivialTypeSourceInfo(CharPtrType);
5560 TypedefDecl *VaListTypeDecl
5561 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5562 Context->getTranslationUnitDecl(),
5563 SourceLocation(), SourceLocation(),
5564 &Context->Idents.get("__builtin_va_list"),
5566 return VaListTypeDecl;
5569 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5570 // typedef void* __builtin_va_list;
5571 QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5572 TypeSourceInfo *TInfo
5573 = Context->getTrivialTypeSourceInfo(VoidPtrType);
5575 TypedefDecl *VaListTypeDecl
5576 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5577 Context->getTranslationUnitDecl(),
5578 SourceLocation(), SourceLocation(),
5579 &Context->Idents.get("__builtin_va_list"),
5581 return VaListTypeDecl;
5584 static TypedefDecl *
5585 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
5586 RecordDecl *VaListTagDecl;
5587 if (Context->getLangOpts().CPlusPlus) {
5588 // namespace std { struct __va_list {
5590 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5591 Context->getTranslationUnitDecl(),
5592 /*Inline*/false, SourceLocation(),
5593 SourceLocation(), &Context->Idents.get("std"),
5596 VaListTagDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5597 Context->getTranslationUnitDecl(),
5598 SourceLocation(), SourceLocation(),
5599 &Context->Idents.get("__va_list"));
5600 VaListTagDecl->setDeclContext(NS);
5603 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5604 Context->getTranslationUnitDecl(),
5605 &Context->Idents.get("__va_list"));
5608 VaListTagDecl->startDefinition();
5610 const size_t NumFields = 5;
5611 QualType FieldTypes[NumFields];
5612 const char *FieldNames[NumFields];
5615 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
5616 FieldNames[0] = "__stack";
5619 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
5620 FieldNames[1] = "__gr_top";
5623 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5624 FieldNames[2] = "__vr_top";
5627 FieldTypes[3] = Context->IntTy;
5628 FieldNames[3] = "__gr_offs";
5631 FieldTypes[4] = Context->IntTy;
5632 FieldNames[4] = "__vr_offs";
5635 for (unsigned i = 0; i < NumFields; ++i) {
5636 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5640 &Context->Idents.get(FieldNames[i]),
5641 FieldTypes[i], /*TInfo=*/0,
5645 Field->setAccess(AS_public);
5646 VaListTagDecl->addDecl(Field);
5648 VaListTagDecl->completeDefinition();
5649 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5650 Context->VaListTagTy = VaListTagType;
5652 // } __builtin_va_list;
5653 TypedefDecl *VaListTypedefDecl
5654 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5655 Context->getTranslationUnitDecl(),
5656 SourceLocation(), SourceLocation(),
5657 &Context->Idents.get("__builtin_va_list"),
5658 Context->getTrivialTypeSourceInfo(VaListTagType));
5660 return VaListTypedefDecl;
5663 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5664 // typedef struct __va_list_tag {
5665 RecordDecl *VaListTagDecl;
5667 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5668 Context->getTranslationUnitDecl(),
5669 &Context->Idents.get("__va_list_tag"));
5670 VaListTagDecl->startDefinition();
5672 const size_t NumFields = 5;
5673 QualType FieldTypes[NumFields];
5674 const char *FieldNames[NumFields];
5676 // unsigned char gpr;
5677 FieldTypes[0] = Context->UnsignedCharTy;
5678 FieldNames[0] = "gpr";
5680 // unsigned char fpr;
5681 FieldTypes[1] = Context->UnsignedCharTy;
5682 FieldNames[1] = "fpr";
5684 // unsigned short reserved;
5685 FieldTypes[2] = Context->UnsignedShortTy;
5686 FieldNames[2] = "reserved";
5688 // void* overflow_arg_area;
5689 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5690 FieldNames[3] = "overflow_arg_area";
5692 // void* reg_save_area;
5693 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5694 FieldNames[4] = "reg_save_area";
5697 for (unsigned i = 0; i < NumFields; ++i) {
5698 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5701 &Context->Idents.get(FieldNames[i]),
5702 FieldTypes[i], /*TInfo=*/0,
5706 Field->setAccess(AS_public);
5707 VaListTagDecl->addDecl(Field);
5709 VaListTagDecl->completeDefinition();
5710 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5711 Context->VaListTagTy = VaListTagType;
5714 TypedefDecl *VaListTagTypedefDecl
5715 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5716 Context->getTranslationUnitDecl(),
5717 SourceLocation(), SourceLocation(),
5718 &Context->Idents.get("__va_list_tag"),
5719 Context->getTrivialTypeSourceInfo(VaListTagType));
5720 QualType VaListTagTypedefType =
5721 Context->getTypedefType(VaListTagTypedefDecl);
5723 // typedef __va_list_tag __builtin_va_list[1];
5724 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5725 QualType VaListTagArrayType
5726 = Context->getConstantArrayType(VaListTagTypedefType,
5727 Size, ArrayType::Normal, 0);
5728 TypeSourceInfo *TInfo
5729 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5730 TypedefDecl *VaListTypedefDecl
5731 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5732 Context->getTranslationUnitDecl(),
5733 SourceLocation(), SourceLocation(),
5734 &Context->Idents.get("__builtin_va_list"),
5737 return VaListTypedefDecl;
5740 static TypedefDecl *
5741 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5742 // typedef struct __va_list_tag {
5743 RecordDecl *VaListTagDecl;
5744 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5745 Context->getTranslationUnitDecl(),
5746 &Context->Idents.get("__va_list_tag"));
5747 VaListTagDecl->startDefinition();
5749 const size_t NumFields = 4;
5750 QualType FieldTypes[NumFields];
5751 const char *FieldNames[NumFields];
5753 // unsigned gp_offset;
5754 FieldTypes[0] = Context->UnsignedIntTy;
5755 FieldNames[0] = "gp_offset";
5757 // unsigned fp_offset;
5758 FieldTypes[1] = Context->UnsignedIntTy;
5759 FieldNames[1] = "fp_offset";
5761 // void* overflow_arg_area;
5762 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5763 FieldNames[2] = "overflow_arg_area";
5765 // void* reg_save_area;
5766 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5767 FieldNames[3] = "reg_save_area";
5770 for (unsigned i = 0; i < NumFields; ++i) {
5771 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5775 &Context->Idents.get(FieldNames[i]),
5776 FieldTypes[i], /*TInfo=*/0,
5780 Field->setAccess(AS_public);
5781 VaListTagDecl->addDecl(Field);
5783 VaListTagDecl->completeDefinition();
5784 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5785 Context->VaListTagTy = VaListTagType;
5788 TypedefDecl *VaListTagTypedefDecl
5789 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5790 Context->getTranslationUnitDecl(),
5791 SourceLocation(), SourceLocation(),
5792 &Context->Idents.get("__va_list_tag"),
5793 Context->getTrivialTypeSourceInfo(VaListTagType));
5794 QualType VaListTagTypedefType =
5795 Context->getTypedefType(VaListTagTypedefDecl);
5797 // typedef __va_list_tag __builtin_va_list[1];
5798 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5799 QualType VaListTagArrayType
5800 = Context->getConstantArrayType(VaListTagTypedefType,
5801 Size, ArrayType::Normal,0);
5802 TypeSourceInfo *TInfo
5803 = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5804 TypedefDecl *VaListTypedefDecl
5805 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5806 Context->getTranslationUnitDecl(),
5807 SourceLocation(), SourceLocation(),
5808 &Context->Idents.get("__builtin_va_list"),
5811 return VaListTypedefDecl;
5814 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5815 // typedef int __builtin_va_list[4];
5816 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5817 QualType IntArrayType
5818 = Context->getConstantArrayType(Context->IntTy,
5819 Size, ArrayType::Normal, 0);
5820 TypedefDecl *VaListTypedefDecl
5821 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5822 Context->getTranslationUnitDecl(),
5823 SourceLocation(), SourceLocation(),
5824 &Context->Idents.get("__builtin_va_list"),
5825 Context->getTrivialTypeSourceInfo(IntArrayType));
5827 return VaListTypedefDecl;
5830 static TypedefDecl *
5831 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
5832 RecordDecl *VaListDecl;
5833 if (Context->getLangOpts().CPlusPlus) {
5834 // namespace std { struct __va_list {
5836 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
5837 Context->getTranslationUnitDecl(),
5838 /*Inline*/false, SourceLocation(),
5839 SourceLocation(), &Context->Idents.get("std"),
5842 VaListDecl = CXXRecordDecl::Create(*Context, TTK_Struct,
5843 Context->getTranslationUnitDecl(),
5844 SourceLocation(), SourceLocation(),
5845 &Context->Idents.get("__va_list"));
5847 VaListDecl->setDeclContext(NS);
5850 // struct __va_list {
5851 VaListDecl = CreateRecordDecl(*Context, TTK_Struct,
5852 Context->getTranslationUnitDecl(),
5853 &Context->Idents.get("__va_list"));
5856 VaListDecl->startDefinition();
5859 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5863 &Context->Idents.get("__ap"),
5864 Context->getPointerType(Context->VoidTy),
5869 Field->setAccess(AS_public);
5870 VaListDecl->addDecl(Field);
5873 VaListDecl->completeDefinition();
5875 // typedef struct __va_list __builtin_va_list;
5876 TypeSourceInfo *TInfo
5877 = Context->getTrivialTypeSourceInfo(Context->getRecordType(VaListDecl));
5879 TypedefDecl *VaListTypeDecl
5880 = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5881 Context->getTranslationUnitDecl(),
5882 SourceLocation(), SourceLocation(),
5883 &Context->Idents.get("__builtin_va_list"),
5886 return VaListTypeDecl;
5889 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5890 TargetInfo::BuiltinVaListKind Kind) {
5892 case TargetInfo::CharPtrBuiltinVaList:
5893 return CreateCharPtrBuiltinVaListDecl(Context);
5894 case TargetInfo::VoidPtrBuiltinVaList:
5895 return CreateVoidPtrBuiltinVaListDecl(Context);
5896 case TargetInfo::AArch64ABIBuiltinVaList:
5897 return CreateAArch64ABIBuiltinVaListDecl(Context);
5898 case TargetInfo::PowerABIBuiltinVaList:
5899 return CreatePowerABIBuiltinVaListDecl(Context);
5900 case TargetInfo::X86_64ABIBuiltinVaList:
5901 return CreateX86_64ABIBuiltinVaListDecl(Context);
5902 case TargetInfo::PNaClABIBuiltinVaList:
5903 return CreatePNaClABIBuiltinVaListDecl(Context);
5904 case TargetInfo::AAPCSABIBuiltinVaList:
5905 return CreateAAPCSABIBuiltinVaListDecl(Context);
5908 llvm_unreachable("Unhandled __builtin_va_list type kind");
5911 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5912 if (!BuiltinVaListDecl)
5913 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5915 return BuiltinVaListDecl;
5918 QualType ASTContext::getVaListTagType() const {
5919 // Force the creation of VaListTagTy by building the __builtin_va_list
5921 if (VaListTagTy.isNull())
5922 (void) getBuiltinVaListDecl();
5927 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
5928 assert(ObjCConstantStringType.isNull() &&
5929 "'NSConstantString' type already set!");
5931 ObjCConstantStringType = getObjCInterfaceType(Decl);
5934 /// \brief Retrieve the template name that corresponds to a non-empty
5937 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5938 UnresolvedSetIterator End) const {
5939 unsigned size = End - Begin;
5940 assert(size > 1 && "set is not overloaded!");
5942 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5943 size * sizeof(FunctionTemplateDecl*));
5944 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5946 NamedDecl **Storage = OT->getStorage();
5947 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
5949 assert(isa<FunctionTemplateDecl>(D) ||
5950 (isa<UsingShadowDecl>(D) &&
5951 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5955 return TemplateName(OT);
5958 /// \brief Retrieve the template name that represents a qualified
5959 /// template name such as \c std::vector.
5961 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5962 bool TemplateKeyword,
5963 TemplateDecl *Template) const {
5964 assert(NNS && "Missing nested-name-specifier in qualified template name");
5966 // FIXME: Canonicalization?
5967 llvm::FoldingSetNodeID ID;
5968 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5970 void *InsertPos = 0;
5971 QualifiedTemplateName *QTN =
5972 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5974 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
5975 QualifiedTemplateName(NNS, TemplateKeyword, Template);
5976 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5979 return TemplateName(QTN);
5982 /// \brief Retrieve the template name that represents a dependent
5983 /// template name such as \c MetaFun::template apply.
5985 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5986 const IdentifierInfo *Name) const {
5987 assert((!NNS || NNS->isDependent()) &&
5988 "Nested name specifier must be dependent");
5990 llvm::FoldingSetNodeID ID;
5991 DependentTemplateName::Profile(ID, NNS, Name);
5993 void *InsertPos = 0;
5994 DependentTemplateName *QTN =
5995 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5998 return TemplateName(QTN);
6000 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6001 if (CanonNNS == NNS) {
6002 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6003 DependentTemplateName(NNS, Name);
6005 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6006 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6007 DependentTemplateName(NNS, Name, Canon);
6008 DependentTemplateName *CheckQTN =
6009 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6010 assert(!CheckQTN && "Dependent type name canonicalization broken");
6014 DependentTemplateNames.InsertNode(QTN, InsertPos);
6015 return TemplateName(QTN);
6018 /// \brief Retrieve the template name that represents a dependent
6019 /// template name such as \c MetaFun::template operator+.
6021 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6022 OverloadedOperatorKind Operator) const {
6023 assert((!NNS || NNS->isDependent()) &&
6024 "Nested name specifier must be dependent");
6026 llvm::FoldingSetNodeID ID;
6027 DependentTemplateName::Profile(ID, NNS, Operator);
6029 void *InsertPos = 0;
6030 DependentTemplateName *QTN
6031 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6034 return TemplateName(QTN);
6036 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6037 if (CanonNNS == NNS) {
6038 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6039 DependentTemplateName(NNS, Operator);
6041 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6042 QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6043 DependentTemplateName(NNS, Operator, Canon);
6045 DependentTemplateName *CheckQTN
6046 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6047 assert(!CheckQTN && "Dependent template name canonicalization broken");
6051 DependentTemplateNames.InsertNode(QTN, InsertPos);
6052 return TemplateName(QTN);
6056 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6057 TemplateName replacement) const {
6058 llvm::FoldingSetNodeID ID;
6059 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6061 void *insertPos = 0;
6062 SubstTemplateTemplateParmStorage *subst
6063 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6066 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6067 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6070 return TemplateName(subst);
6074 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6075 const TemplateArgument &ArgPack) const {
6076 ASTContext &Self = const_cast<ASTContext &>(*this);
6077 llvm::FoldingSetNodeID ID;
6078 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6080 void *InsertPos = 0;
6081 SubstTemplateTemplateParmPackStorage *Subst
6082 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6085 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6086 ArgPack.pack_size(),
6087 ArgPack.pack_begin());
6088 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6091 return TemplateName(Subst);
6094 /// getFromTargetType - Given one of the integer types provided by
6095 /// TargetInfo, produce the corresponding type. The unsigned @p Type
6096 /// is actually a value of type @c TargetInfo::IntType.
6097 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6099 case TargetInfo::NoInt: return CanQualType();
6100 case TargetInfo::SignedShort: return ShortTy;
6101 case TargetInfo::UnsignedShort: return UnsignedShortTy;
6102 case TargetInfo::SignedInt: return IntTy;
6103 case TargetInfo::UnsignedInt: return UnsignedIntTy;
6104 case TargetInfo::SignedLong: return LongTy;
6105 case TargetInfo::UnsignedLong: return UnsignedLongTy;
6106 case TargetInfo::SignedLongLong: return LongLongTy;
6107 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6110 llvm_unreachable("Unhandled TargetInfo::IntType value");
6113 //===----------------------------------------------------------------------===//
6115 //===----------------------------------------------------------------------===//
6117 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6118 /// garbage collection attribute.
6120 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6121 if (getLangOpts().getGC() == LangOptions::NonGC)
6122 return Qualifiers::GCNone;
6124 assert(getLangOpts().ObjC1);
6125 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6127 // Default behaviour under objective-C's gc is for ObjC pointers
6128 // (or pointers to them) be treated as though they were declared
6130 if (GCAttrs == Qualifiers::GCNone) {
6131 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6132 return Qualifiers::Strong;
6133 else if (Ty->isPointerType())
6134 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6136 // It's not valid to set GC attributes on anything that isn't a
6139 QualType CT = Ty->getCanonicalTypeInternal();
6140 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6141 CT = AT->getElementType();
6142 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6148 //===----------------------------------------------------------------------===//
6149 // Type Compatibility Testing
6150 //===----------------------------------------------------------------------===//
6152 /// areCompatVectorTypes - Return true if the two specified vector types are
6154 static bool areCompatVectorTypes(const VectorType *LHS,
6155 const VectorType *RHS) {
6156 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6157 return LHS->getElementType() == RHS->getElementType() &&
6158 LHS->getNumElements() == RHS->getNumElements();
6161 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6162 QualType SecondVec) {
6163 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6164 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6166 if (hasSameUnqualifiedType(FirstVec, SecondVec))
6169 // Treat Neon vector types and most AltiVec vector types as if they are the
6170 // equivalent GCC vector types.
6171 const VectorType *First = FirstVec->getAs<VectorType>();
6172 const VectorType *Second = SecondVec->getAs<VectorType>();
6173 if (First->getNumElements() == Second->getNumElements() &&
6174 hasSameType(First->getElementType(), Second->getElementType()) &&
6175 First->getVectorKind() != VectorType::AltiVecPixel &&
6176 First->getVectorKind() != VectorType::AltiVecBool &&
6177 Second->getVectorKind() != VectorType::AltiVecPixel &&
6178 Second->getVectorKind() != VectorType::AltiVecBool)
6184 //===----------------------------------------------------------------------===//
6185 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6186 //===----------------------------------------------------------------------===//
6188 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6189 /// inheritance hierarchy of 'rProto'.
6191 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6192 ObjCProtocolDecl *rProto) const {
6193 if (declaresSameEntity(lProto, rProto))
6195 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
6196 E = rProto->protocol_end(); PI != E; ++PI)
6197 if (ProtocolCompatibleWithProtocol(lProto, *PI))
6202 /// QualifiedIdConformsQualifiedId - compare id<pr,...> with id<pr1,...>
6203 /// return true if lhs's protocols conform to rhs's protocol; false
6205 bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
6206 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
6207 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
6211 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
6212 /// Class<pr1, ...>.
6213 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6215 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6216 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6217 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6219 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6220 E = lhsQID->qual_end(); I != E; ++I) {
6222 ObjCProtocolDecl *lhsProto = *I;
6223 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6224 E = rhsOPT->qual_end(); J != E; ++J) {
6225 ObjCProtocolDecl *rhsProto = *J;
6226 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6237 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6238 /// ObjCQualifiedIDType.
6239 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6241 // Allow id<P..> and an 'id' or void* type in all cases.
6242 if (lhs->isVoidPointerType() ||
6243 lhs->isObjCIdType() || lhs->isObjCClassType())
6245 else if (rhs->isVoidPointerType() ||
6246 rhs->isObjCIdType() || rhs->isObjCClassType())
6249 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6250 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6252 if (!rhsOPT) return false;
6254 if (rhsOPT->qual_empty()) {
6255 // If the RHS is a unqualified interface pointer "NSString*",
6256 // make sure we check the class hierarchy.
6257 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6258 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6259 E = lhsQID->qual_end(); I != E; ++I) {
6260 // when comparing an id<P> on lhs with a static type on rhs,
6261 // see if static class implements all of id's protocols, directly or
6262 // through its super class and categories.
6263 if (!rhsID->ClassImplementsProtocol(*I, true))
6267 // If there are no qualifiers and no interface, we have an 'id'.
6270 // Both the right and left sides have qualifiers.
6271 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6272 E = lhsQID->qual_end(); I != E; ++I) {
6273 ObjCProtocolDecl *lhsProto = *I;
6276 // when comparing an id<P> on lhs with a static type on rhs,
6277 // see if static class implements all of id's protocols, directly or
6278 // through its super class and categories.
6279 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
6280 E = rhsOPT->qual_end(); J != E; ++J) {
6281 ObjCProtocolDecl *rhsProto = *J;
6282 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6283 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6288 // If the RHS is a qualified interface pointer "NSString<P>*",
6289 // make sure we check the class hierarchy.
6290 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6291 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
6292 E = lhsQID->qual_end(); I != E; ++I) {
6293 // when comparing an id<P> on lhs with a static type on rhs,
6294 // see if static class implements all of id's protocols, directly or
6295 // through its super class and categories.
6296 if (rhsID->ClassImplementsProtocol(*I, true)) {
6309 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6310 assert(rhsQID && "One of the LHS/RHS should be id<x>");
6312 if (const ObjCObjectPointerType *lhsOPT =
6313 lhs->getAsObjCInterfacePointerType()) {
6314 // If both the right and left sides have qualifiers.
6315 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
6316 E = lhsOPT->qual_end(); I != E; ++I) {
6317 ObjCProtocolDecl *lhsProto = *I;
6320 // when comparing an id<P> on rhs with a static type on lhs,
6321 // see if static class implements all of id's protocols, directly or
6322 // through its super class and categories.
6323 // First, lhs protocols in the qualifier list must be found, direct
6324 // or indirect in rhs's qualifier list or it is a mismatch.
6325 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6326 E = rhsQID->qual_end(); J != E; ++J) {
6327 ObjCProtocolDecl *rhsProto = *J;
6328 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6329 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6338 // Static class's protocols, or its super class or category protocols
6339 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6340 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6341 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6342 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6343 // This is rather dubious but matches gcc's behavior. If lhs has
6344 // no type qualifier and its class has no static protocol(s)
6345 // assume that it is mismatch.
6346 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6348 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6349 LHSInheritedProtocols.begin(),
6350 E = LHSInheritedProtocols.end(); I != E; ++I) {
6352 ObjCProtocolDecl *lhsProto = (*I);
6353 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
6354 E = rhsQID->qual_end(); J != E; ++J) {
6355 ObjCProtocolDecl *rhsProto = *J;
6356 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6357 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6371 /// canAssignObjCInterfaces - Return true if the two interface types are
6372 /// compatible for assignment from RHS to LHS. This handles validation of any
6373 /// protocol qualifiers on the LHS or RHS.
6375 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6376 const ObjCObjectPointerType *RHSOPT) {
6377 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6378 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6380 // If either type represents the built-in 'id' or 'Class' types, return true.
6381 if (LHS->isObjCUnqualifiedIdOrClass() ||
6382 RHS->isObjCUnqualifiedIdOrClass())
6385 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
6386 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6390 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
6391 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6392 QualType(RHSOPT,0));
6394 // If we have 2 user-defined types, fall into that path.
6395 if (LHS->getInterface() && RHS->getInterface())
6396 return canAssignObjCInterfaces(LHS, RHS);
6401 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6402 /// for providing type-safety for objective-c pointers used to pass/return
6403 /// arguments in block literals. When passed as arguments, passing 'A*' where
6404 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6405 /// not OK. For the return type, the opposite is not OK.
6406 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6407 const ObjCObjectPointerType *LHSOPT,
6408 const ObjCObjectPointerType *RHSOPT,
6409 bool BlockReturnType) {
6410 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
6413 if (LHSOPT->isObjCBuiltinType()) {
6414 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
6417 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
6418 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6422 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6423 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6424 if (LHS && RHS) { // We have 2 user-defined types.
6426 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
6427 return BlockReturnType;
6428 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
6429 return !BlockReturnType;
6437 /// getIntersectionOfProtocols - This routine finds the intersection of set
6438 /// of protocols inherited from two distinct objective-c pointer objects.
6439 /// It is used to build composite qualifier list of the composite type of
6440 /// the conditional expression involving two objective-c pointer objects.
6442 void getIntersectionOfProtocols(ASTContext &Context,
6443 const ObjCObjectPointerType *LHSOPT,
6444 const ObjCObjectPointerType *RHSOPT,
6445 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
6447 const ObjCObjectType* LHS = LHSOPT->getObjectType();
6448 const ObjCObjectType* RHS = RHSOPT->getObjectType();
6449 assert(LHS->getInterface() && "LHS must have an interface base");
6450 assert(RHS->getInterface() && "RHS must have an interface base");
6452 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
6453 unsigned LHSNumProtocols = LHS->getNumProtocols();
6454 if (LHSNumProtocols > 0)
6455 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
6457 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6458 Context.CollectInheritedProtocols(LHS->getInterface(),
6459 LHSInheritedProtocols);
6460 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
6461 LHSInheritedProtocols.end());
6464 unsigned RHSNumProtocols = RHS->getNumProtocols();
6465 if (RHSNumProtocols > 0) {
6466 ObjCProtocolDecl **RHSProtocols =
6467 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
6468 for (unsigned i = 0; i < RHSNumProtocols; ++i)
6469 if (InheritedProtocolSet.count(RHSProtocols[i]))
6470 IntersectionOfProtocols.push_back(RHSProtocols[i]);
6472 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
6473 Context.CollectInheritedProtocols(RHS->getInterface(),
6474 RHSInheritedProtocols);
6475 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6476 RHSInheritedProtocols.begin(),
6477 E = RHSInheritedProtocols.end(); I != E; ++I)
6478 if (InheritedProtocolSet.count((*I)))
6479 IntersectionOfProtocols.push_back((*I));
6483 /// areCommonBaseCompatible - Returns common base class of the two classes if
6484 /// one found. Note that this is O'2 algorithm. But it will be called as the
6485 /// last type comparison in a ?-exp of ObjC pointer types before a
6486 /// warning is issued. So, its invokation is extremely rare.
6487 QualType ASTContext::areCommonBaseCompatible(
6488 const ObjCObjectPointerType *Lptr,
6489 const ObjCObjectPointerType *Rptr) {
6490 const ObjCObjectType *LHS = Lptr->getObjectType();
6491 const ObjCObjectType *RHS = Rptr->getObjectType();
6492 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
6493 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
6494 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
6498 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
6499 if (canAssignObjCInterfaces(LHS, RHS)) {
6500 SmallVector<ObjCProtocolDecl *, 8> Protocols;
6501 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
6503 QualType Result = QualType(LHS, 0);
6504 if (!Protocols.empty())
6505 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
6506 Result = getObjCObjectPointerType(Result);
6509 } while ((LDecl = LDecl->getSuperClass()));
6514 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
6515 const ObjCObjectType *RHS) {
6516 assert(LHS->getInterface() && "LHS is not an interface type");
6517 assert(RHS->getInterface() && "RHS is not an interface type");
6519 // Verify that the base decls are compatible: the RHS must be a subclass of
6521 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
6524 // RHS must have a superset of the protocols in the LHS. If the LHS is not
6525 // protocol qualified at all, then we are good.
6526 if (LHS->getNumProtocols() == 0)
6529 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
6530 // more detailed analysis is required.
6531 if (RHS->getNumProtocols() == 0) {
6532 // OK, if LHS is a superclass of RHS *and*
6533 // this superclass is assignment compatible with LHS.
6536 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
6538 // OK if conversion of LHS to SuperClass results in narrowing of types
6539 // ; i.e., SuperClass may implement at least one of the protocols
6540 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
6541 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
6542 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
6543 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
6544 // If super class has no protocols, it is not a match.
6545 if (SuperClassInheritedProtocols.empty())
6548 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6549 LHSPE = LHS->qual_end();
6550 LHSPI != LHSPE; LHSPI++) {
6551 bool SuperImplementsProtocol = false;
6552 ObjCProtocolDecl *LHSProto = (*LHSPI);
6554 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
6555 SuperClassInheritedProtocols.begin(),
6556 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
6557 ObjCProtocolDecl *SuperClassProto = (*I);
6558 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
6559 SuperImplementsProtocol = true;
6563 if (!SuperImplementsProtocol)
6571 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
6572 LHSPE = LHS->qual_end();
6573 LHSPI != LHSPE; LHSPI++) {
6574 bool RHSImplementsProtocol = false;
6576 // If the RHS doesn't implement the protocol on the left, the types
6577 // are incompatible.
6578 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
6579 RHSPE = RHS->qual_end();
6580 RHSPI != RHSPE; RHSPI++) {
6581 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
6582 RHSImplementsProtocol = true;
6586 // FIXME: For better diagnostics, consider passing back the protocol name.
6587 if (!RHSImplementsProtocol)
6590 // The RHS implements all protocols listed on the LHS.
6594 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
6595 // get the "pointed to" types
6596 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
6597 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
6599 if (!LHSOPT || !RHSOPT)
6602 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
6603 canAssignObjCInterfaces(RHSOPT, LHSOPT);
6606 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
6607 return canAssignObjCInterfaces(
6608 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
6609 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
6612 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
6613 /// both shall have the identically qualified version of a compatible type.
6614 /// C99 6.2.7p1: Two types have compatible types if their types are the
6615 /// same. See 6.7.[2,3,5] for additional rules.
6616 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
6617 bool CompareUnqualified) {
6618 if (getLangOpts().CPlusPlus)
6619 return hasSameType(LHS, RHS);
6621 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
6624 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
6625 return typesAreCompatible(LHS, RHS);
6628 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
6629 return !mergeTypes(LHS, RHS, true).isNull();
6632 /// mergeTransparentUnionType - if T is a transparent union type and a member
6633 /// of T is compatible with SubType, return the merged type, else return
6635 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
6636 bool OfBlockPointer,
6638 if (const RecordType *UT = T->getAsUnionType()) {
6639 RecordDecl *UD = UT->getDecl();
6640 if (UD->hasAttr<TransparentUnionAttr>()) {
6641 for (RecordDecl::field_iterator it = UD->field_begin(),
6642 itend = UD->field_end(); it != itend; ++it) {
6643 QualType ET = it->getType().getUnqualifiedType();
6644 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
6654 /// mergeFunctionArgumentTypes - merge two types which appear as function
6656 QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
6657 bool OfBlockPointer,
6659 // GNU extension: two types are compatible if they appear as a function
6660 // argument, one of the types is a transparent union type and the other
6661 // type is compatible with a union member
6662 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
6664 if (!lmerge.isNull())
6667 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
6669 if (!rmerge.isNull())
6672 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
6675 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
6676 bool OfBlockPointer,
6678 const FunctionType *lbase = lhs->getAs<FunctionType>();
6679 const FunctionType *rbase = rhs->getAs<FunctionType>();
6680 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6681 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
6682 bool allLTypes = true;
6683 bool allRTypes = true;
6685 // Check return type
6687 if (OfBlockPointer) {
6688 QualType RHS = rbase->getResultType();
6689 QualType LHS = lbase->getResultType();
6690 bool UnqualifiedResult = Unqualified;
6691 if (!UnqualifiedResult)
6692 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
6693 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
6696 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6698 if (retType.isNull()) return QualType();
6701 retType = retType.getUnqualifiedType();
6703 CanQualType LRetType = getCanonicalType(lbase->getResultType());
6704 CanQualType RRetType = getCanonicalType(rbase->getResultType());
6706 LRetType = LRetType.getUnqualifiedType();
6707 RRetType = RRetType.getUnqualifiedType();
6710 if (getCanonicalType(retType) != LRetType)
6712 if (getCanonicalType(retType) != RRetType)
6715 // FIXME: double check this
6716 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6717 // rbase->getRegParmAttr() != 0 &&
6718 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
6719 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6720 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
6722 // Compatible functions must have compatible calling conventions
6723 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
6726 // Regparm is part of the calling convention.
6727 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6729 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6732 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6735 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6736 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
6738 if (lbaseInfo.getNoReturn() != NoReturn)
6740 if (rbaseInfo.getNoReturn() != NoReturn)
6743 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
6745 if (lproto && rproto) { // two C99 style function prototypes
6746 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6747 "C++ shouldn't be here");
6748 unsigned lproto_nargs = lproto->getNumArgs();
6749 unsigned rproto_nargs = rproto->getNumArgs();
6751 // Compatible functions must have the same number of arguments
6752 if (lproto_nargs != rproto_nargs)
6755 // Variadic and non-variadic functions aren't compatible
6756 if (lproto->isVariadic() != rproto->isVariadic())
6759 if (lproto->getTypeQuals() != rproto->getTypeQuals())
6762 if (LangOpts.ObjCAutoRefCount &&
6763 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6766 // Check argument compatibility
6767 SmallVector<QualType, 10> types;
6768 for (unsigned i = 0; i < lproto_nargs; i++) {
6769 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6770 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
6771 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6774 if (argtype.isNull()) return QualType();
6777 argtype = argtype.getUnqualifiedType();
6779 types.push_back(argtype);
6781 largtype = largtype.getUnqualifiedType();
6782 rargtype = rargtype.getUnqualifiedType();
6785 if (getCanonicalType(argtype) != getCanonicalType(largtype))
6787 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6791 if (allLTypes) return lhs;
6792 if (allRTypes) return rhs;
6794 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6795 EPI.ExtInfo = einfo;
6796 return getFunctionType(retType, types, EPI);
6799 if (lproto) allRTypes = false;
6800 if (rproto) allLTypes = false;
6802 const FunctionProtoType *proto = lproto ? lproto : rproto;
6804 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
6805 if (proto->isVariadic()) return QualType();
6806 // Check that the types are compatible with the types that
6807 // would result from default argument promotions (C99 6.7.5.3p15).
6808 // The only types actually affected are promotable integer
6809 // types and floats, which would be passed as a different
6810 // type depending on whether the prototype is visible.
6811 unsigned proto_nargs = proto->getNumArgs();
6812 for (unsigned i = 0; i < proto_nargs; ++i) {
6813 QualType argTy = proto->getArgType(i);
6815 // Look at the converted type of enum types, since that is the type used
6816 // to pass enum values.
6817 if (const EnumType *Enum = argTy->getAs<EnumType>()) {
6818 argTy = Enum->getDecl()->getIntegerType();
6823 if (argTy->isPromotableIntegerType() ||
6824 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6828 if (allLTypes) return lhs;
6829 if (allRTypes) return rhs;
6831 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6832 EPI.ExtInfo = einfo;
6833 return getFunctionType(retType,
6834 ArrayRef<QualType>(proto->arg_type_begin(),
6835 proto->getNumArgs()),
6839 if (allLTypes) return lhs;
6840 if (allRTypes) return rhs;
6841 return getFunctionNoProtoType(retType, einfo);
6844 /// Given that we have an enum type and a non-enum type, try to merge them.
6845 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
6846 QualType other, bool isBlockReturnType) {
6847 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
6848 // a signed integer type, or an unsigned integer type.
6849 // Compatibility is based on the underlying type, not the promotion
6851 QualType underlyingType = ET->getDecl()->getIntegerType();
6852 if (underlyingType.isNull()) return QualType();
6853 if (Context.hasSameType(underlyingType, other))
6856 // In block return types, we're more permissive and accept any
6857 // integral type of the same size.
6858 if (isBlockReturnType && other->isIntegerType() &&
6859 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
6865 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
6866 bool OfBlockPointer,
6867 bool Unqualified, bool BlockReturnType) {
6868 // C++ [expr]: If an expression initially has the type "reference to T", the
6869 // type is adjusted to "T" prior to any further analysis, the expression
6870 // designates the object or function denoted by the reference, and the
6871 // expression is an lvalue unless the reference is an rvalue reference and
6872 // the expression is a function call (possibly inside parentheses).
6873 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6874 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
6877 LHS = LHS.getUnqualifiedType();
6878 RHS = RHS.getUnqualifiedType();
6881 QualType LHSCan = getCanonicalType(LHS),
6882 RHSCan = getCanonicalType(RHS);
6884 // If two types are identical, they are compatible.
6885 if (LHSCan == RHSCan)
6888 // If the qualifiers are different, the types aren't compatible... mostly.
6889 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6890 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6891 if (LQuals != RQuals) {
6892 // If any of these qualifiers are different, we have a type
6894 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6895 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6896 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
6899 // Exactly one GC qualifier difference is allowed: __strong is
6900 // okay if the other type has no GC qualifier but is an Objective
6901 // C object pointer (i.e. implicitly strong by default). We fix
6902 // this by pretending that the unqualified type was actually
6903 // qualified __strong.
6904 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6905 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6906 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6908 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6911 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6912 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6914 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6915 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6920 // Okay, qualifiers are equal.
6922 Type::TypeClass LHSClass = LHSCan->getTypeClass();
6923 Type::TypeClass RHSClass = RHSCan->getTypeClass();
6925 // We want to consider the two function types to be the same for these
6926 // comparisons, just force one to the other.
6927 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6928 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
6930 // Same as above for arrays
6931 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6932 LHSClass = Type::ConstantArray;
6933 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6934 RHSClass = Type::ConstantArray;
6936 // ObjCInterfaces are just specialized ObjCObjects.
6937 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6938 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6940 // Canonicalize ExtVector -> Vector.
6941 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6942 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
6944 // If the canonical type classes don't match.
6945 if (LHSClass != RHSClass) {
6946 // Note that we only have special rules for turning block enum
6947 // returns into block int returns, not vice-versa.
6948 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
6949 return mergeEnumWithInteger(*this, ETy, RHS, false);
6951 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
6952 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
6954 // allow block pointer type to match an 'id' type.
6955 if (OfBlockPointer && !BlockReturnType) {
6956 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6958 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6965 // The canonical type classes match.
6967 #define TYPE(Class, Base)
6968 #define ABSTRACT_TYPE(Class, Base)
6969 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
6970 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6971 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
6972 #include "clang/AST/TypeNodes.def"
6973 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
6975 case Type::LValueReference:
6976 case Type::RValueReference:
6977 case Type::MemberPointer:
6978 llvm_unreachable("C++ should never be in mergeTypes");
6980 case Type::ObjCInterface:
6981 case Type::IncompleteArray:
6982 case Type::VariableArray:
6983 case Type::FunctionProto:
6984 case Type::ExtVector:
6985 llvm_unreachable("Types are eliminated above");
6989 // Merge two pointer types, while trying to preserve typedef info
6990 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6991 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
6993 LHSPointee = LHSPointee.getUnqualifiedType();
6994 RHSPointee = RHSPointee.getUnqualifiedType();
6996 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6998 if (ResultType.isNull()) return QualType();
6999 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7001 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7003 return getPointerType(ResultType);
7005 case Type::BlockPointer:
7007 // Merge two block pointer types, while trying to preserve typedef info
7008 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7009 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7011 LHSPointee = LHSPointee.getUnqualifiedType();
7012 RHSPointee = RHSPointee.getUnqualifiedType();
7014 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7016 if (ResultType.isNull()) return QualType();
7017 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7019 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7021 return getBlockPointerType(ResultType);
7025 // Merge two pointer types, while trying to preserve typedef info
7026 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7027 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7029 LHSValue = LHSValue.getUnqualifiedType();
7030 RHSValue = RHSValue.getUnqualifiedType();
7032 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7034 if (ResultType.isNull()) return QualType();
7035 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7037 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7039 return getAtomicType(ResultType);
7041 case Type::ConstantArray:
7043 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7044 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7045 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7048 QualType LHSElem = getAsArrayType(LHS)->getElementType();
7049 QualType RHSElem = getAsArrayType(RHS)->getElementType();
7051 LHSElem = LHSElem.getUnqualifiedType();
7052 RHSElem = RHSElem.getUnqualifiedType();
7055 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7056 if (ResultType.isNull()) return QualType();
7057 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7059 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7061 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7062 ArrayType::ArraySizeModifier(), 0);
7063 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7064 ArrayType::ArraySizeModifier(), 0);
7065 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7066 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7067 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7069 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7072 // FIXME: This isn't correct! But tricky to implement because
7073 // the array's size has to be the size of LHS, but the type
7074 // has to be different.
7078 // FIXME: This isn't correct! But tricky to implement because
7079 // the array's size has to be the size of RHS, but the type
7080 // has to be different.
7083 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7084 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7085 return getIncompleteArrayType(ResultType,
7086 ArrayType::ArraySizeModifier(), 0);
7088 case Type::FunctionNoProto:
7089 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7094 // Only exactly equal builtin types are compatible, which is tested above.
7097 // Distinct complex types are incompatible.
7100 // FIXME: The merged type should be an ExtVector!
7101 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7102 RHSCan->getAs<VectorType>()))
7105 case Type::ObjCObject: {
7106 // Check if the types are assignment compatible.
7107 // FIXME: This should be type compatibility, e.g. whether
7108 // "LHS x; RHS x;" at global scope is legal.
7109 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7110 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7111 if (canAssignObjCInterfaces(LHSIface, RHSIface))
7116 case Type::ObjCObjectPointer: {
7117 if (OfBlockPointer) {
7118 if (canAssignObjCInterfacesInBlockPointer(
7119 LHS->getAs<ObjCObjectPointerType>(),
7120 RHS->getAs<ObjCObjectPointerType>(),
7125 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7126 RHS->getAs<ObjCObjectPointerType>()))
7133 llvm_unreachable("Invalid Type::Class!");
7136 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7137 const FunctionProtoType *FromFunctionType,
7138 const FunctionProtoType *ToFunctionType) {
7139 if (FromFunctionType->hasAnyConsumedArgs() !=
7140 ToFunctionType->hasAnyConsumedArgs())
7142 FunctionProtoType::ExtProtoInfo FromEPI =
7143 FromFunctionType->getExtProtoInfo();
7144 FunctionProtoType::ExtProtoInfo ToEPI =
7145 ToFunctionType->getExtProtoInfo();
7146 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
7147 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
7148 ArgIdx != NumArgs; ++ArgIdx) {
7149 if (FromEPI.ConsumedArguments[ArgIdx] !=
7150 ToEPI.ConsumedArguments[ArgIdx])
7156 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7157 /// 'RHS' attributes and returns the merged version; including for function
7159 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7160 QualType LHSCan = getCanonicalType(LHS),
7161 RHSCan = getCanonicalType(RHS);
7162 // If two types are identical, they are compatible.
7163 if (LHSCan == RHSCan)
7165 if (RHSCan->isFunctionType()) {
7166 if (!LHSCan->isFunctionType())
7168 QualType OldReturnType =
7169 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
7170 QualType NewReturnType =
7171 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
7172 QualType ResReturnType =
7173 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7174 if (ResReturnType.isNull())
7176 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7177 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7178 // In either case, use OldReturnType to build the new function type.
7179 const FunctionType *F = LHS->getAs<FunctionType>();
7180 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7181 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7182 EPI.ExtInfo = getFunctionExtInfo(LHS);
7184 = getFunctionType(OldReturnType,
7185 ArrayRef<QualType>(FPT->arg_type_begin(),
7194 // If the qualifiers are different, the types can still be merged.
7195 Qualifiers LQuals = LHSCan.getLocalQualifiers();
7196 Qualifiers RQuals = RHSCan.getLocalQualifiers();
7197 if (LQuals != RQuals) {
7198 // If any of these qualifiers are different, we have a type mismatch.
7199 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7200 LQuals.getAddressSpace() != RQuals.getAddressSpace())
7203 // Exactly one GC qualifier difference is allowed: __strong is
7204 // okay if the other type has no GC qualifier but is an Objective
7205 // C object pointer (i.e. implicitly strong by default). We fix
7206 // this by pretending that the unqualified type was actually
7207 // qualified __strong.
7208 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7209 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7210 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7212 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7215 if (GC_L == Qualifiers::Strong)
7217 if (GC_R == Qualifiers::Strong)
7222 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7223 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7224 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7225 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7226 if (ResQT == LHSBaseQT)
7228 if (ResQT == RHSBaseQT)
7234 //===----------------------------------------------------------------------===//
7235 // Integer Predicates
7236 //===----------------------------------------------------------------------===//
7238 unsigned ASTContext::getIntWidth(QualType T) const {
7239 if (const EnumType *ET = dyn_cast<EnumType>(T))
7240 T = ET->getDecl()->getIntegerType();
7241 if (T->isBooleanType())
7243 // For builtin types, just use the standard type sizing method
7244 return (unsigned)getTypeSize(T);
7247 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
7248 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
7250 // Turn <4 x signed int> -> <4 x unsigned int>
7251 if (const VectorType *VTy = T->getAs<VectorType>())
7252 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
7253 VTy->getNumElements(), VTy->getVectorKind());
7255 // For enums, we return the unsigned version of the base type.
7256 if (const EnumType *ETy = T->getAs<EnumType>())
7257 T = ETy->getDecl()->getIntegerType();
7259 const BuiltinType *BTy = T->getAs<BuiltinType>();
7260 assert(BTy && "Unexpected signed integer type");
7261 switch (BTy->getKind()) {
7262 case BuiltinType::Char_S:
7263 case BuiltinType::SChar:
7264 return UnsignedCharTy;
7265 case BuiltinType::Short:
7266 return UnsignedShortTy;
7267 case BuiltinType::Int:
7268 return UnsignedIntTy;
7269 case BuiltinType::Long:
7270 return UnsignedLongTy;
7271 case BuiltinType::LongLong:
7272 return UnsignedLongLongTy;
7273 case BuiltinType::Int128:
7274 return UnsignedInt128Ty;
7276 llvm_unreachable("Unexpected signed integer type");
7280 ASTMutationListener::~ASTMutationListener() { }
7283 //===----------------------------------------------------------------------===//
7284 // Builtin Type Computation
7285 //===----------------------------------------------------------------------===//
7287 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
7288 /// pointer over the consumed characters. This returns the resultant type. If
7289 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7290 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
7291 /// a vector of "i*".
7293 /// RequiresICE is filled in on return to indicate whether the value is required
7294 /// to be an Integer Constant Expression.
7295 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
7296 ASTContext::GetBuiltinTypeError &Error,
7298 bool AllowTypeModifiers) {
7301 bool Signed = false, Unsigned = false;
7302 RequiresICE = false;
7304 // Read the prefixed modifiers first.
7308 default: Done = true; --Str; break;
7313 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7314 assert(!Signed && "Can't use 'S' modifier multiple times!");
7318 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7319 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
7323 assert(HowLong <= 2 && "Can't have LLLL modifier");
7331 // Read the base type.
7333 default: llvm_unreachable("Unknown builtin type letter!");
7335 assert(HowLong == 0 && !Signed && !Unsigned &&
7336 "Bad modifiers used with 'v'!");
7337 Type = Context.VoidTy;
7340 assert(HowLong == 0 && !Signed && !Unsigned &&
7341 "Bad modifiers used with 'f'!");
7342 Type = Context.FloatTy;
7345 assert(HowLong < 2 && !Signed && !Unsigned &&
7346 "Bad modifiers used with 'd'!");
7348 Type = Context.LongDoubleTy;
7350 Type = Context.DoubleTy;
7353 assert(HowLong == 0 && "Bad modifiers used with 's'!");
7355 Type = Context.UnsignedShortTy;
7357 Type = Context.ShortTy;
7361 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7362 else if (HowLong == 2)
7363 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7364 else if (HowLong == 1)
7365 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7367 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7370 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7372 Type = Context.SignedCharTy;
7374 Type = Context.UnsignedCharTy;
7376 Type = Context.CharTy;
7378 case 'b': // boolean
7379 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7380 Type = Context.BoolTy;
7382 case 'z': // size_t.
7383 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7384 Type = Context.getSizeType();
7387 Type = Context.getCFConstantStringType();
7390 Type = Context.getObjCIdType();
7393 Type = Context.getObjCSelType();
7396 Type = Context.getObjCSuperType();
7399 Type = Context.getBuiltinVaListType();
7400 assert(!Type.isNull() && "builtin va list type not initialized!");
7403 // This is a "reference" to a va_list; however, what exactly
7404 // this means depends on how va_list is defined. There are two
7405 // different kinds of va_list: ones passed by value, and ones
7406 // passed by reference. An example of a by-value va_list is
7407 // x86, where va_list is a char*. An example of by-ref va_list
7408 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
7409 // we want this argument to be a char*&; for x86-64, we want
7410 // it to be a __va_list_tag*.
7411 Type = Context.getBuiltinVaListType();
7412 assert(!Type.isNull() && "builtin va list type not initialized!");
7413 if (Type->isArrayType())
7414 Type = Context.getArrayDecayedType(Type);
7416 Type = Context.getLValueReferenceType(Type);
7420 unsigned NumElements = strtoul(Str, &End, 10);
7421 assert(End != Str && "Missing vector size");
7424 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
7425 RequiresICE, false);
7426 assert(!RequiresICE && "Can't require vector ICE");
7428 // TODO: No way to make AltiVec vectors in builtins yet.
7429 Type = Context.getVectorType(ElementType, NumElements,
7430 VectorType::GenericVector);
7436 unsigned NumElements = strtoul(Str, &End, 10);
7437 assert(End != Str && "Missing vector size");
7441 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7443 Type = Context.getExtVectorType(ElementType, NumElements);
7447 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
7449 assert(!RequiresICE && "Can't require complex ICE");
7450 Type = Context.getComplexType(ElementType);
7454 Type = Context.getPointerDiffType();
7458 Type = Context.getFILEType();
7459 if (Type.isNull()) {
7460 Error = ASTContext::GE_Missing_stdio;
7466 Type = Context.getsigjmp_bufType();
7468 Type = Context.getjmp_bufType();
7470 if (Type.isNull()) {
7471 Error = ASTContext::GE_Missing_setjmp;
7476 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
7477 Type = Context.getucontext_tType();
7479 if (Type.isNull()) {
7480 Error = ASTContext::GE_Missing_ucontext;
7485 Type = Context.getProcessIDType();
7489 // If there are modifiers and if we're allowed to parse them, go for it.
7490 Done = !AllowTypeModifiers;
7492 switch (char c = *Str++) {
7493 default: Done = true; --Str; break;
7496 // Both pointers and references can have their pointee types
7497 // qualified with an address space.
7499 unsigned AddrSpace = strtoul(Str, &End, 10);
7500 if (End != Str && AddrSpace != 0) {
7501 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
7505 Type = Context.getPointerType(Type);
7507 Type = Context.getLValueReferenceType(Type);
7510 // FIXME: There's no way to have a built-in with an rvalue ref arg.
7512 Type = Type.withConst();
7515 Type = Context.getVolatileType(Type);
7518 Type = Type.withRestrict();
7523 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
7524 "Integer constant 'I' type must be an integer");
7529 /// GetBuiltinType - Return the type for the specified builtin.
7530 QualType ASTContext::GetBuiltinType(unsigned Id,
7531 GetBuiltinTypeError &Error,
7532 unsigned *IntegerConstantArgs) const {
7533 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
7535 SmallVector<QualType, 8> ArgTypes;
7537 bool RequiresICE = false;
7539 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
7541 if (Error != GE_None)
7544 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
7546 while (TypeStr[0] && TypeStr[0] != '.') {
7547 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
7548 if (Error != GE_None)
7551 // If this argument is required to be an IntegerConstantExpression and the
7552 // caller cares, fill in the bitmask we return.
7553 if (RequiresICE && IntegerConstantArgs)
7554 *IntegerConstantArgs |= 1 << ArgTypes.size();
7556 // Do array -> pointer decay. The builtin should use the decayed type.
7557 if (Ty->isArrayType())
7558 Ty = getArrayDecayedType(Ty);
7560 ArgTypes.push_back(Ty);
7563 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
7564 "'.' should only occur at end of builtin type list!");
7566 FunctionType::ExtInfo EI;
7567 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
7569 bool Variadic = (TypeStr[0] == '.');
7571 // We really shouldn't be making a no-proto type here, especially in C++.
7572 if (ArgTypes.empty() && Variadic)
7573 return getFunctionNoProtoType(ResType, EI);
7575 FunctionProtoType::ExtProtoInfo EPI;
7577 EPI.Variadic = Variadic;
7579 return getFunctionType(ResType, ArgTypes, EPI);
7582 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
7583 GVALinkage External = GVA_StrongExternal;
7585 Linkage L = FD->getLinkage();
7588 case InternalLinkage:
7589 case UniqueExternalLinkage:
7590 return GVA_Internal;
7592 case ExternalLinkage:
7593 switch (FD->getTemplateSpecializationKind()) {
7594 case TSK_Undeclared:
7595 case TSK_ExplicitSpecialization:
7596 External = GVA_StrongExternal;
7599 case TSK_ExplicitInstantiationDefinition:
7600 return GVA_ExplicitTemplateInstantiation;
7602 case TSK_ExplicitInstantiationDeclaration:
7603 case TSK_ImplicitInstantiation:
7604 External = GVA_TemplateInstantiation;
7609 if (!FD->isInlined())
7612 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
7613 // GNU or C99 inline semantics. Determine whether this symbol should be
7614 // externally visible.
7615 if (FD->isInlineDefinitionExternallyVisible())
7618 // C99 inline semantics, where the symbol is not externally visible.
7619 return GVA_C99Inline;
7622 // C++0x [temp.explicit]p9:
7623 // [ Note: The intent is that an inline function that is the subject of
7624 // an explicit instantiation declaration will still be implicitly
7625 // instantiated when used so that the body can be considered for
7626 // inlining, but that no out-of-line copy of the inline function would be
7627 // generated in the translation unit. -- end note ]
7628 if (FD->getTemplateSpecializationKind()
7629 == TSK_ExplicitInstantiationDeclaration)
7630 return GVA_C99Inline;
7632 return GVA_CXXInline;
7635 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
7636 // If this is a static data member, compute the kind of template
7637 // specialization. Otherwise, this variable is not part of a
7639 TemplateSpecializationKind TSK = TSK_Undeclared;
7640 if (VD->isStaticDataMember())
7641 TSK = VD->getTemplateSpecializationKind();
7643 Linkage L = VD->getLinkage();
7647 case InternalLinkage:
7648 case UniqueExternalLinkage:
7649 return GVA_Internal;
7651 case ExternalLinkage:
7653 case TSK_Undeclared:
7654 case TSK_ExplicitSpecialization:
7655 return GVA_StrongExternal;
7657 case TSK_ExplicitInstantiationDeclaration:
7658 llvm_unreachable("Variable should not be instantiated");
7659 // Fall through to treat this like any other instantiation.
7661 case TSK_ExplicitInstantiationDefinition:
7662 return GVA_ExplicitTemplateInstantiation;
7664 case TSK_ImplicitInstantiation:
7665 return GVA_TemplateInstantiation;
7669 llvm_unreachable("Invalid Linkage!");
7672 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
7673 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7674 if (!VD->isFileVarDecl())
7676 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7677 // We never need to emit an uninstantiated function template.
7678 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
7683 // If this is a member of a class template, we do not need to emit it.
7684 if (D->getDeclContext()->isDependentContext())
7687 // Weak references don't produce any output by themselves.
7688 if (D->hasAttr<WeakRefAttr>())
7691 // Aliases and used decls are required.
7692 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
7695 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7696 // Forward declarations aren't required.
7697 if (!FD->doesThisDeclarationHaveABody())
7698 return FD->doesDeclarationForceExternallyVisibleDefinition();
7700 // Constructors and destructors are required.
7701 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
7704 // The key function for a class is required. This rule only comes
7705 // into play when inline functions can be key functions, though.
7706 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7707 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7708 const CXXRecordDecl *RD = MD->getParent();
7709 if (MD->isOutOfLine() && RD->isDynamicClass()) {
7710 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
7711 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7717 GVALinkage Linkage = GetGVALinkageForFunction(FD);
7719 // static, static inline, always_inline, and extern inline functions can
7720 // always be deferred. Normal inline functions can be deferred in C99/C++.
7721 // Implicit template instantiations can also be deferred in C++.
7722 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
7723 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
7728 const VarDecl *VD = cast<VarDecl>(D);
7729 assert(VD->isFileVarDecl() && "Expected file scoped var");
7731 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7734 // Variables that can be needed in other TUs are required.
7735 GVALinkage L = GetGVALinkageForVariable(VD);
7736 if (L != GVA_Internal && L != GVA_TemplateInstantiation)
7739 // Variables that have destruction with side-effects are required.
7740 if (VD->getType().isDestructedType())
7743 // Variables that have initialization with side-effects are required.
7744 if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
7750 CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) {
7751 // Pass through to the C++ ABI object
7752 return ABI->getDefaultMethodCallConv(isVariadic);
7755 CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const {
7756 if (CC == CC_C && !LangOpts.MRTD &&
7757 getTargetInfo().getCXXABI().isMemberFunctionCCDefault())
7762 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
7763 // Pass through to the C++ ABI object
7764 return ABI->isNearlyEmpty(RD);
7767 MangleContext *ASTContext::createMangleContext() {
7768 switch (Target->getCXXABI().getKind()) {
7769 case TargetCXXABI::GenericAArch64:
7770 case TargetCXXABI::GenericItanium:
7771 case TargetCXXABI::GenericARM:
7772 case TargetCXXABI::iOS:
7773 return createItaniumMangleContext(*this, getDiagnostics());
7774 case TargetCXXABI::Microsoft:
7775 return createMicrosoftMangleContext(*this, getDiagnostics());
7777 llvm_unreachable("Unsupported ABI");
7780 CXXABI::~CXXABI() {}
7782 size_t ASTContext::getSideTableAllocatedMemory() const {
7783 return ASTRecordLayouts.getMemorySize()
7784 + llvm::capacity_in_bytes(ObjCLayouts)
7785 + llvm::capacity_in_bytes(KeyFunctions)
7786 + llvm::capacity_in_bytes(ObjCImpls)
7787 + llvm::capacity_in_bytes(BlockVarCopyInits)
7788 + llvm::capacity_in_bytes(DeclAttrs)
7789 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7790 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7791 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7792 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7793 + llvm::capacity_in_bytes(OverriddenMethods)
7794 + llvm::capacity_in_bytes(Types)
7795 + llvm::capacity_in_bytes(VariableArrayTypes)
7796 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
7799 void ASTContext::addUnnamedTag(const TagDecl *Tag) {
7800 // FIXME: This mangling should be applied to function local classes too
7801 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl() ||
7802 !isa<CXXRecordDecl>(Tag->getParent()) || Tag->getLinkage() != ExternalLinkage)
7805 std::pair<llvm::DenseMap<const DeclContext *, unsigned>::iterator, bool> P =
7806 UnnamedMangleContexts.insert(std::make_pair(Tag->getParent(), 0));
7807 UnnamedMangleNumbers.insert(std::make_pair(Tag, P.first->second++));
7810 int ASTContext::getUnnamedTagManglingNumber(const TagDecl *Tag) const {
7811 llvm::DenseMap<const TagDecl *, unsigned>::const_iterator I =
7812 UnnamedMangleNumbers.find(Tag);
7813 return I != UnnamedMangleNumbers.end() ? I->second : -1;
7816 unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7817 CXXRecordDecl *Lambda = CallOperator->getParent();
7818 return LambdaMangleContexts[Lambda->getDeclContext()]
7819 .getManglingNumber(CallOperator);
7823 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7824 ParamIndices[D] = index;
7827 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7828 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7829 assert(I != ParamIndices.end() &&
7830 "ParmIndices lacks entry set by ParmVarDecl");