1 //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the ASTContext interface.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTContext.h"
15 #include "Interp/Context.h"
16 #include "clang/AST/APValue.h"
17 #include "clang/AST/ASTConcept.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/ASTTypeTraits.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/AttrIterator.h"
22 #include "clang/AST/CharUnits.h"
23 #include "clang/AST/Comment.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclBase.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/DeclContextInternals.h"
28 #include "clang/AST/DeclObjC.h"
29 #include "clang/AST/DeclOpenMP.h"
30 #include "clang/AST/DeclTemplate.h"
31 #include "clang/AST/DeclarationName.h"
32 #include "clang/AST/DependenceFlags.h"
33 #include "clang/AST/Expr.h"
34 #include "clang/AST/ExprCXX.h"
35 #include "clang/AST/ExprConcepts.h"
36 #include "clang/AST/ExternalASTSource.h"
37 #include "clang/AST/Mangle.h"
38 #include "clang/AST/MangleNumberingContext.h"
39 #include "clang/AST/NestedNameSpecifier.h"
40 #include "clang/AST/ParentMapContext.h"
41 #include "clang/AST/RawCommentList.h"
42 #include "clang/AST/RecordLayout.h"
43 #include "clang/AST/Stmt.h"
44 #include "clang/AST/TemplateBase.h"
45 #include "clang/AST/TemplateName.h"
46 #include "clang/AST/Type.h"
47 #include "clang/AST/TypeLoc.h"
48 #include "clang/AST/UnresolvedSet.h"
49 #include "clang/AST/VTableBuilder.h"
50 #include "clang/Basic/AddressSpaces.h"
51 #include "clang/Basic/Builtins.h"
52 #include "clang/Basic/CommentOptions.h"
53 #include "clang/Basic/ExceptionSpecificationType.h"
54 #include "clang/Basic/FixedPoint.h"
55 #include "clang/Basic/IdentifierTable.h"
56 #include "clang/Basic/LLVM.h"
57 #include "clang/Basic/LangOptions.h"
58 #include "clang/Basic/Linkage.h"
59 #include "clang/Basic/Module.h"
60 #include "clang/Basic/ObjCRuntime.h"
61 #include "clang/Basic/SanitizerBlacklist.h"
62 #include "clang/Basic/SourceLocation.h"
63 #include "clang/Basic/SourceManager.h"
64 #include "clang/Basic/Specifiers.h"
65 #include "clang/Basic/TargetCXXABI.h"
66 #include "clang/Basic/TargetInfo.h"
67 #include "clang/Basic/XRayLists.h"
68 #include "llvm/ADT/APInt.h"
69 #include "llvm/ADT/APSInt.h"
70 #include "llvm/ADT/ArrayRef.h"
71 #include "llvm/ADT/DenseMap.h"
72 #include "llvm/ADT/DenseSet.h"
73 #include "llvm/ADT/FoldingSet.h"
74 #include "llvm/ADT/None.h"
75 #include "llvm/ADT/Optional.h"
76 #include "llvm/ADT/PointerUnion.h"
77 #include "llvm/ADT/STLExtras.h"
78 #include "llvm/ADT/SmallPtrSet.h"
79 #include "llvm/ADT/SmallVector.h"
80 #include "llvm/ADT/StringExtras.h"
81 #include "llvm/ADT/StringRef.h"
82 #include "llvm/ADT/Triple.h"
83 #include "llvm/Support/Capacity.h"
84 #include "llvm/Support/Casting.h"
85 #include "llvm/Support/Compiler.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
100 using namespace clang;
103 BFloat16Rank, Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
106 /// \returns location that is relevant when searching for Doc comments related
108 static SourceLocation getDeclLocForCommentSearch(const Decl *D,
109 SourceManager &SourceMgr) {
112 // User can not attach documentation to implicit declarations.
116 // User can not attach documentation to implicit instantiations.
117 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
118 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
122 if (const auto *VD = dyn_cast<VarDecl>(D)) {
123 if (VD->isStaticDataMember() &&
124 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
128 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
129 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
133 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
134 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
135 if (TSK == TSK_ImplicitInstantiation ||
136 TSK == TSK_Undeclared)
140 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
141 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
144 if (const auto *TD = dyn_cast<TagDecl>(D)) {
145 // When tag declaration (but not definition!) is part of the
146 // decl-specifier-seq of some other declaration, it doesn't get comment
147 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
150 // TODO: handle comments for function parameters properly.
151 if (isa<ParmVarDecl>(D))
154 // TODO: we could look up template parameter documentation in the template
156 if (isa<TemplateTypeParmDecl>(D) ||
157 isa<NonTypeTemplateParmDecl>(D) ||
158 isa<TemplateTemplateParmDecl>(D))
161 // Find declaration location.
162 // For Objective-C declarations we generally don't expect to have multiple
163 // declarators, thus use declaration starting location as the "declaration
165 // For all other declarations multiple declarators are used quite frequently,
166 // so we use the location of the identifier as the "declaration location".
167 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
168 isa<ObjCPropertyDecl>(D) ||
169 isa<RedeclarableTemplateDecl>(D) ||
170 isa<ClassTemplateSpecializationDecl>(D) ||
171 // Allow association with Y across {} in `typedef struct X {} Y`.
173 return D->getBeginLoc();
175 const SourceLocation DeclLoc = D->getLocation();
176 if (DeclLoc.isMacroID()) {
177 if (isa<TypedefDecl>(D)) {
178 // If location of the typedef name is in a macro, it is because being
179 // declared via a macro. Try using declaration's starting location as
180 // the "declaration location".
181 return D->getBeginLoc();
182 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
183 // If location of the tag decl is inside a macro, but the spelling of
184 // the tag name comes from a macro argument, it looks like a special
185 // macro like NS_ENUM is being used to define the tag decl. In that
186 // case, adjust the source location to the expansion loc so that we can
187 // attach the comment to the tag decl.
188 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
189 TD->isCompleteDefinition())
190 return SourceMgr.getExpansionLoc(DeclLoc);
199 RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
200 const Decl *D, const SourceLocation RepresentativeLocForDecl,
201 const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
202 // If the declaration doesn't map directly to a location in a file, we
203 // can't find the comment.
204 if (RepresentativeLocForDecl.isInvalid() ||
205 !RepresentativeLocForDecl.isFileID())
208 // If there are no comments anywhere, we won't find anything.
209 if (CommentsInTheFile.empty())
212 // Decompose the location for the declaration and find the beginning of the
214 const std::pair<FileID, unsigned> DeclLocDecomp =
215 SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
218 auto OffsetCommentBehindDecl =
219 CommentsInTheFile.lower_bound(DeclLocDecomp.second);
221 // First check whether we have a trailing comment.
222 if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
223 RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
224 if ((CommentBehindDecl->isDocumentation() ||
225 LangOpts.CommentOpts.ParseAllComments) &&
226 CommentBehindDecl->isTrailingComment() &&
227 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
228 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
230 // Check that Doxygen trailing comment comes after the declaration, starts
231 // on the same line and in the same file as the declaration.
232 if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
233 Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
234 OffsetCommentBehindDecl->first)) {
235 return CommentBehindDecl;
240 // The comment just after the declaration was not a trailing comment.
241 // Let's look at the previous comment.
242 if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
245 auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
246 RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
248 // Check that we actually have a non-member Doxygen comment.
249 if (!(CommentBeforeDecl->isDocumentation() ||
250 LangOpts.CommentOpts.ParseAllComments) ||
251 CommentBeforeDecl->isTrailingComment())
254 // Decompose the end of the comment.
255 const unsigned CommentEndOffset =
256 Comments.getCommentEndOffset(CommentBeforeDecl);
258 // Get the corresponding buffer.
259 bool Invalid = false;
260 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
265 // Extract text between the comment and declaration.
266 StringRef Text(Buffer + CommentEndOffset,
267 DeclLocDecomp.second - CommentEndOffset);
269 // There should be no other declarations or preprocessor directives between
270 // comment and declaration.
271 if (Text.find_first_of(";{}#@") != StringRef::npos)
274 return CommentBeforeDecl;
277 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
278 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
280 // If the declaration doesn't map directly to a location in a file, we
281 // can't find the comment.
282 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
285 if (ExternalSource && !CommentsLoaded) {
286 ExternalSource->ReadComments();
287 CommentsLoaded = true;
290 if (Comments.empty())
293 const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
294 const auto CommentsInThisFile = Comments.getCommentsInFile(File);
295 if (!CommentsInThisFile || CommentsInThisFile->empty())
298 return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
301 void ASTContext::addComment(const RawComment &RC) {
302 assert(LangOpts.RetainCommentsFromSystemHeaders ||
303 !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
304 Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
307 /// If we have a 'templated' declaration for a template, adjust 'D' to
308 /// refer to the actual template.
309 /// If we have an implicit instantiation, adjust 'D' to refer to template.
310 static const Decl &adjustDeclToTemplate(const Decl &D) {
311 if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
312 // Is this function declaration part of a function template?
313 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
316 // Nothing to do if function is not an implicit instantiation.
317 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
320 // Function is an implicit instantiation of a function template?
321 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
324 // Function is instantiated from a member definition of a class template?
325 if (const FunctionDecl *MemberDecl =
326 FD->getInstantiatedFromMemberFunction())
331 if (const auto *VD = dyn_cast<VarDecl>(&D)) {
332 // Static data member is instantiated from a member definition of a class
334 if (VD->isStaticDataMember())
335 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
340 if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
341 // Is this class declaration part of a class template?
342 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
345 // Class is an implicit instantiation of a class template or partial
347 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
348 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
350 llvm::PointerUnion<ClassTemplateDecl *,
351 ClassTemplatePartialSpecializationDecl *>
352 PU = CTSD->getSpecializedTemplateOrPartial();
353 return PU.is<ClassTemplateDecl *>()
354 ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
355 : *static_cast<const Decl *>(
356 PU.get<ClassTemplatePartialSpecializationDecl *>());
359 // Class is instantiated from a member definition of a class template?
360 if (const MemberSpecializationInfo *Info =
361 CRD->getMemberSpecializationInfo())
362 return *Info->getInstantiatedFrom();
366 if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
367 // Enum is instantiated from a member definition of a class template?
368 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
373 // FIXME: Adjust alias templates?
377 const RawComment *ASTContext::getRawCommentForAnyRedecl(
379 const Decl **OriginalDecl) const {
382 OriginalDecl = nullptr;
386 D = &adjustDeclToTemplate(*D);
388 // Any comment directly attached to D?
390 auto DeclComment = DeclRawComments.find(D);
391 if (DeclComment != DeclRawComments.end()) {
394 return DeclComment->second;
398 // Any comment attached to any redeclaration of D?
399 const Decl *CanonicalD = D->getCanonicalDecl();
404 auto RedeclComment = RedeclChainComments.find(CanonicalD);
405 if (RedeclComment != RedeclChainComments.end()) {
407 *OriginalDecl = RedeclComment->second;
408 auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
409 assert(CommentAtRedecl != DeclRawComments.end() &&
410 "This decl is supposed to have comment attached.");
411 return CommentAtRedecl->second;
415 // Any redeclarations of D that we haven't checked for comments yet?
416 // We can't use DenseMap::iterator directly since it'd get invalid.
417 auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
418 auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
419 if (LookupRes != CommentlessRedeclChains.end())
420 return LookupRes->second;
424 for (const auto Redecl : D->redecls()) {
426 // Skip all redeclarations that have been checked previously.
427 if (LastCheckedRedecl) {
428 if (LastCheckedRedecl == Redecl) {
429 LastCheckedRedecl = nullptr;
433 const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
435 cacheRawCommentForDecl(*Redecl, *RedeclComment);
437 *OriginalDecl = Redecl;
438 return RedeclComment;
440 CommentlessRedeclChains[CanonicalD] = Redecl;
444 *OriginalDecl = nullptr;
448 void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
449 const RawComment &Comment) const {
450 assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
451 DeclRawComments.try_emplace(&OriginalD, &Comment);
452 const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
453 RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
454 CommentlessRedeclChains.erase(CanonicalDecl);
457 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
458 SmallVectorImpl<const NamedDecl *> &Redeclared) {
459 const DeclContext *DC = ObjCMethod->getDeclContext();
460 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
461 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
464 // Add redeclared method here.
465 for (const auto *Ext : ID->known_extensions()) {
466 if (ObjCMethodDecl *RedeclaredMethod =
467 Ext->getMethod(ObjCMethod->getSelector(),
468 ObjCMethod->isInstanceMethod()))
469 Redeclared.push_back(RedeclaredMethod);
474 void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
475 const Preprocessor *PP) {
476 if (Comments.empty() || Decls.empty())
480 for (Decl *D : Decls) {
481 SourceLocation Loc = D->getLocation();
483 // See if there are any new comments that are not attached to a decl.
484 // The location doesn't have to be precise - we care only about the file.
485 File = SourceMgr.getDecomposedLoc(Loc).first;
490 if (File.isInvalid())
493 auto CommentsInThisFile = Comments.getCommentsInFile(File);
494 if (!CommentsInThisFile || CommentsInThisFile->empty() ||
495 CommentsInThisFile->rbegin()->second->isAttached())
498 // There is at least one comment not attached to a decl.
499 // Maybe it should be attached to one of Decls?
501 // Note that this way we pick up not only comments that precede the
502 // declaration, but also comments that *follow* the declaration -- thanks to
503 // the lookahead in the lexer: we've consumed the semicolon and looked
504 // ahead through comments.
506 for (const Decl *D : Decls) {
508 if (D->isInvalidDecl())
511 D = &adjustDeclToTemplate(*D);
513 const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
515 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
518 if (DeclRawComments.count(D) > 0)
521 if (RawComment *const DocComment =
522 getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
523 cacheRawCommentForDecl(*D, *DocComment);
524 comments::FullComment *FC = DocComment->parse(*this, PP, D);
525 ParsedComments[D->getCanonicalDecl()] = FC;
530 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
531 const Decl *D) const {
532 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
533 ThisDeclInfo->CommentDecl = D;
534 ThisDeclInfo->IsFilled = false;
535 ThisDeclInfo->fill();
536 ThisDeclInfo->CommentDecl = FC->getDecl();
537 if (!ThisDeclInfo->TemplateParameters)
538 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
539 comments::FullComment *CFC =
540 new (*this) comments::FullComment(FC->getBlocks(),
545 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
546 const RawComment *RC = getRawCommentForDeclNoCache(D);
547 return RC ? RC->parse(*this, nullptr, D) : nullptr;
550 comments::FullComment *ASTContext::getCommentForDecl(
552 const Preprocessor *PP) const {
553 if (!D || D->isInvalidDecl())
555 D = &adjustDeclToTemplate(*D);
557 const Decl *Canonical = D->getCanonicalDecl();
558 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
559 ParsedComments.find(Canonical);
561 if (Pos != ParsedComments.end()) {
562 if (Canonical != D) {
563 comments::FullComment *FC = Pos->second;
564 comments::FullComment *CFC = cloneFullComment(FC, D);
570 const Decl *OriginalDecl = nullptr;
572 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
574 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
575 SmallVector<const NamedDecl*, 8> Overridden;
576 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
577 if (OMD && OMD->isPropertyAccessor())
578 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
579 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
580 return cloneFullComment(FC, D);
582 addRedeclaredMethods(OMD, Overridden);
583 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
584 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
585 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
586 return cloneFullComment(FC, D);
588 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
589 // Attach any tag type's documentation to its typedef if latter
590 // does not have one of its own.
591 QualType QT = TD->getUnderlyingType();
592 if (const auto *TT = QT->getAs<TagType>())
593 if (const Decl *TD = TT->getDecl())
594 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
595 return cloneFullComment(FC, D);
597 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
598 while (IC->getSuperClass()) {
599 IC = IC->getSuperClass();
600 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
601 return cloneFullComment(FC, D);
604 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
605 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
606 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
607 return cloneFullComment(FC, D);
609 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
610 if (!(RD = RD->getDefinition()))
612 // Check non-virtual bases.
613 for (const auto &I : RD->bases()) {
614 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
616 QualType Ty = I.getType();
619 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
620 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
623 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
624 return cloneFullComment(FC, D);
627 // Check virtual bases.
628 for (const auto &I : RD->vbases()) {
629 if (I.getAccessSpecifier() != AS_public)
631 QualType Ty = I.getType();
634 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
635 if (!(VirtualBase= VirtualBase->getDefinition()))
637 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
638 return cloneFullComment(FC, D);
645 // If the RawComment was attached to other redeclaration of this Decl, we
646 // should parse the comment in context of that other Decl. This is important
647 // because comments can contain references to parameter names which can be
648 // different across redeclarations.
649 if (D != OriginalDecl && OriginalDecl)
650 return getCommentForDecl(OriginalDecl, PP);
652 comments::FullComment *FC = RC->parse(*this, PP, D);
653 ParsedComments[Canonical] = FC;
658 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
660 TemplateTemplateParmDecl *Parm) {
661 ID.AddInteger(Parm->getDepth());
662 ID.AddInteger(Parm->getPosition());
663 ID.AddBoolean(Parm->isParameterPack());
665 TemplateParameterList *Params = Parm->getTemplateParameters();
666 ID.AddInteger(Params->size());
667 for (TemplateParameterList::const_iterator P = Params->begin(),
668 PEnd = Params->end();
670 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
672 ID.AddBoolean(TTP->isParameterPack());
673 const TypeConstraint *TC = TTP->getTypeConstraint();
674 ID.AddBoolean(TC != nullptr);
676 TC->getImmediatelyDeclaredConstraint()->Profile(ID, C,
678 if (TTP->isExpandedParameterPack()) {
680 ID.AddInteger(TTP->getNumExpansionParameters());
682 ID.AddBoolean(false);
686 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
688 ID.AddBoolean(NTTP->isParameterPack());
689 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
690 if (NTTP->isExpandedParameterPack()) {
692 ID.AddInteger(NTTP->getNumExpansionTypes());
693 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
694 QualType T = NTTP->getExpansionType(I);
695 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
698 ID.AddBoolean(false);
702 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
706 Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause();
707 ID.AddBoolean(RequiresClause != nullptr);
709 RequiresClause->Profile(ID, C, /*Canonical=*/true);
713 canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC,
714 QualType ConstrainedType) {
715 // This is a bit ugly - we need to form a new immediately-declared
716 // constraint that references the new parameter; this would ideally
717 // require semantic analysis (e.g. template<C T> struct S {}; - the
718 // converted arguments of C<T> could be an argument pack if C is
719 // declared as template<typename... T> concept C = ...).
720 // We don't have semantic analysis here so we dig deep into the
721 // ready-made constraint expr and change the thing manually.
722 ConceptSpecializationExpr *CSE;
723 if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC))
724 CSE = cast<ConceptSpecializationExpr>(Fold->getLHS());
726 CSE = cast<ConceptSpecializationExpr>(IDC);
727 ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments();
728 SmallVector<TemplateArgument, 3> NewConverted;
729 NewConverted.reserve(OldConverted.size());
730 if (OldConverted.front().getKind() == TemplateArgument::Pack) {
732 // template<typename... T> concept C = true;
733 // template<C<int> T> struct S; -> constraint is C<{T, int}>
734 NewConverted.push_back(ConstrainedType);
735 for (auto &Arg : OldConverted.front().pack_elements().drop_front(1))
736 NewConverted.push_back(Arg);
737 TemplateArgument NewPack(NewConverted);
739 NewConverted.clear();
740 NewConverted.push_back(NewPack);
741 assert(OldConverted.size() == 1 &&
742 "Template parameter pack should be the last parameter");
744 assert(OldConverted.front().getKind() == TemplateArgument::Type &&
745 "Unexpected first argument kind for immediately-declared "
747 NewConverted.push_back(ConstrainedType);
748 for (auto &Arg : OldConverted.drop_front(1))
749 NewConverted.push_back(Arg);
751 Expr *NewIDC = ConceptSpecializationExpr::Create(
752 C, CSE->getNamedConcept(), NewConverted, nullptr,
753 CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack());
755 if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
756 NewIDC = new (C) CXXFoldExpr(OrigFold->getType(), SourceLocation(), NewIDC,
757 BinaryOperatorKind::BO_LAnd,
758 SourceLocation(), /*RHS=*/nullptr,
759 SourceLocation(), /*NumExpansions=*/None);
763 TemplateTemplateParmDecl *
764 ASTContext::getCanonicalTemplateTemplateParmDecl(
765 TemplateTemplateParmDecl *TTP) const {
766 // Check if we already have a canonical template template parameter.
767 llvm::FoldingSetNodeID ID;
768 CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
769 void *InsertPos = nullptr;
770 CanonicalTemplateTemplateParm *Canonical
771 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
773 return Canonical->getParam();
775 // Build a canonical template parameter list.
776 TemplateParameterList *Params = TTP->getTemplateParameters();
777 SmallVector<NamedDecl *, 4> CanonParams;
778 CanonParams.reserve(Params->size());
779 for (TemplateParameterList::const_iterator P = Params->begin(),
780 PEnd = Params->end();
782 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
783 TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this,
784 getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
785 TTP->getDepth(), TTP->getIndex(), nullptr, false,
786 TTP->isParameterPack(), TTP->hasTypeConstraint(),
787 TTP->isExpandedParameterPack() ?
788 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
789 if (const auto *TC = TTP->getTypeConstraint()) {
790 QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
791 Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
792 *this, TC->getImmediatelyDeclaredConstraint(),
794 TemplateArgumentListInfo CanonArgsAsWritten;
795 if (auto *Args = TC->getTemplateArgsAsWritten())
796 for (const auto &ArgLoc : Args->arguments())
797 CanonArgsAsWritten.addArgument(
798 TemplateArgumentLoc(ArgLoc.getArgument(),
799 TemplateArgumentLocInfo()));
800 NewTTP->setTypeConstraint(
801 NestedNameSpecifierLoc(),
802 DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
803 SourceLocation()), /*FoundDecl=*/nullptr,
804 // Actually canonicalizing a TemplateArgumentLoc is difficult so we
805 // simply omit the ArgsAsWritten
806 TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
808 CanonParams.push_back(NewTTP);
809 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
810 QualType T = getCanonicalType(NTTP->getType());
811 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
812 NonTypeTemplateParmDecl *Param;
813 if (NTTP->isExpandedParameterPack()) {
814 SmallVector<QualType, 2> ExpandedTypes;
815 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
816 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
817 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
818 ExpandedTInfos.push_back(
819 getTrivialTypeSourceInfo(ExpandedTypes.back()));
822 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
826 NTTP->getPosition(), nullptr,
832 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
836 NTTP->getPosition(), nullptr,
838 NTTP->isParameterPack(),
841 if (AutoType *AT = T->getContainedAutoType()) {
842 if (AT->isConstrained()) {
843 Param->setPlaceholderTypeConstraint(
844 canonicalizeImmediatelyDeclaredConstraint(
845 *this, NTTP->getPlaceholderTypeConstraint(), T));
848 CanonParams.push_back(Param);
851 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
852 cast<TemplateTemplateParmDecl>(*P)));
855 Expr *CanonRequiresClause = nullptr;
856 if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
857 CanonRequiresClause = RequiresClause;
859 TemplateTemplateParmDecl *CanonTTP
860 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
861 SourceLocation(), TTP->getDepth(),
863 TTP->isParameterPack(),
865 TemplateParameterList::Create(*this, SourceLocation(),
869 CanonRequiresClause));
871 // Get the new insert position for the node we care about.
872 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
873 assert(!Canonical && "Shouldn't be in the map!");
876 // Create the canonical template template parameter entry.
877 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
878 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
882 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
883 if (!LangOpts.CPlusPlus) return nullptr;
885 switch (T.getCXXABI().getKind()) {
886 case TargetCXXABI::Fuchsia:
887 case TargetCXXABI::GenericARM: // Same as Itanium at this level
888 case TargetCXXABI::iOS:
889 case TargetCXXABI::iOS64:
890 case TargetCXXABI::WatchOS:
891 case TargetCXXABI::GenericAArch64:
892 case TargetCXXABI::GenericMIPS:
893 case TargetCXXABI::GenericItanium:
894 case TargetCXXABI::WebAssembly:
895 case TargetCXXABI::XL:
896 return CreateItaniumCXXABI(*this);
897 case TargetCXXABI::Microsoft:
898 return CreateMicrosoftCXXABI(*this);
900 llvm_unreachable("Invalid CXXABI type!");
903 interp::Context &ASTContext::getInterpContext() {
904 if (!InterpContext) {
905 InterpContext.reset(new interp::Context(*this));
907 return *InterpContext.get();
910 ParentMapContext &ASTContext::getParentMapContext() {
912 ParentMapCtx.reset(new ParentMapContext(*this));
913 return *ParentMapCtx.get();
916 static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
917 const LangOptions &LOpts) {
918 if (LOpts.FakeAddressSpaceMap) {
919 // The fake address space map must have a distinct entry for each
920 // language-specific address space.
921 static const unsigned FakeAddrSpaceMap[] = {
925 2, // opencl_constant
935 return &FakeAddrSpaceMap;
937 return &T.getAddressSpaceMap();
941 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
942 const LangOptions &LangOpts) {
943 switch (LangOpts.getAddressSpaceMapMangling()) {
944 case LangOptions::ASMM_Target:
945 return TI.useAddressSpaceMapMangling();
946 case LangOptions::ASMM_On:
948 case LangOptions::ASMM_Off:
951 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
954 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
955 IdentifierTable &idents, SelectorTable &sels,
956 Builtin::Context &builtins)
957 : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
958 TemplateSpecializationTypes(this_()),
959 DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
960 SubstTemplateTemplateParmPacks(this_()),
961 CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
962 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
963 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
964 LangOpts.XRayNeverInstrumentFiles,
965 LangOpts.XRayAttrListFiles, SM)),
966 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
967 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
968 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
969 CompCategories(this_()), LastSDM(nullptr, 0) {
970 TUDecl = TranslationUnitDecl::Create(*this);
971 TraversalScope = {TUDecl};
974 ASTContext::~ASTContext() {
975 // Release the DenseMaps associated with DeclContext objects.
976 // FIXME: Is this the ideal solution?
977 ReleaseDeclContextMaps();
979 // Call all of the deallocation functions on all of their targets.
980 for (auto &Pair : Deallocations)
981 (Pair.first)(Pair.second);
983 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
984 // because they can contain DenseMaps.
985 for (llvm::DenseMap<const ObjCContainerDecl*,
986 const ASTRecordLayout*>::iterator
987 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
988 // Increment in loop to prevent using deallocated memory.
989 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
992 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
993 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
994 // Increment in loop to prevent using deallocated memory.
995 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
999 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
1000 AEnd = DeclAttrs.end();
1002 A->second->~AttrVec();
1004 for (const auto &Value : ModuleInitializers)
1005 Value.second->~PerModuleInitializers();
1007 for (APValue *Value : APValueCleanups)
1011 void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
1012 TraversalScope = TopLevelDecls;
1013 getParentMapContext().clear();
1016 void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
1017 Deallocations.push_back({Callback, Data});
1021 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
1022 ExternalSource = std::move(Source);
1025 void ASTContext::PrintStats() const {
1026 llvm::errs() << "\n*** AST Context Stats:\n";
1027 llvm::errs() << " " << Types.size() << " types total.\n";
1029 unsigned counts[] = {
1030 #define TYPE(Name, Parent) 0,
1031 #define ABSTRACT_TYPE(Name, Parent)
1032 #include "clang/AST/TypeNodes.inc"
1036 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1038 counts[(unsigned)T->getTypeClass()]++;
1042 unsigned TotalBytes = 0;
1043 #define TYPE(Name, Parent) \
1045 llvm::errs() << " " << counts[Idx] << " " << #Name \
1046 << " types, " << sizeof(Name##Type) << " each " \
1047 << "(" << counts[Idx] * sizeof(Name##Type) \
1049 TotalBytes += counts[Idx] * sizeof(Name##Type); \
1051 #define ABSTRACT_TYPE(Name, Parent)
1052 #include "clang/AST/TypeNodes.inc"
1054 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
1056 // Implicit special member functions.
1057 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
1058 << NumImplicitDefaultConstructors
1059 << " implicit default constructors created\n";
1060 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
1061 << NumImplicitCopyConstructors
1062 << " implicit copy constructors created\n";
1063 if (getLangOpts().CPlusPlus)
1064 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
1065 << NumImplicitMoveConstructors
1066 << " implicit move constructors created\n";
1067 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
1068 << NumImplicitCopyAssignmentOperators
1069 << " implicit copy assignment operators created\n";
1070 if (getLangOpts().CPlusPlus)
1071 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
1072 << NumImplicitMoveAssignmentOperators
1073 << " implicit move assignment operators created\n";
1074 llvm::errs() << NumImplicitDestructorsDeclared << "/"
1075 << NumImplicitDestructors
1076 << " implicit destructors created\n";
1078 if (ExternalSource) {
1079 llvm::errs() << "\n";
1080 ExternalSource->PrintStats();
1083 BumpAlloc.PrintStats();
1086 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1087 bool NotifyListeners) {
1088 if (NotifyListeners)
1089 if (auto *Listener = getASTMutationListener())
1090 Listener->RedefinedHiddenDefinition(ND, M);
1092 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
1095 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
1096 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
1097 if (It == MergedDefModules.end())
1100 auto &Merged = It->second;
1101 llvm::DenseSet<Module*> Found;
1102 for (Module *&M : Merged)
1103 if (!Found.insert(M).second)
1105 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
1109 ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
1111 MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
1112 if (MergedIt == MergedDefModules.end())
1114 return MergedIt->second;
1117 void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
1118 if (LazyInitializers.empty())
1121 auto *Source = Ctx.getExternalSource();
1122 assert(Source && "lazy initializers but no external source");
1124 auto LazyInits = std::move(LazyInitializers);
1125 LazyInitializers.clear();
1127 for (auto ID : LazyInits)
1128 Initializers.push_back(Source->GetExternalDecl(ID));
1130 assert(LazyInitializers.empty() &&
1131 "GetExternalDecl for lazy module initializer added more inits");
1134 void ASTContext::addModuleInitializer(Module *M, Decl *D) {
1135 // One special case: if we add a module initializer that imports another
1136 // module, and that module's only initializer is an ImportDecl, simplify.
1137 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
1138 auto It = ModuleInitializers.find(ID->getImportedModule());
1140 // Maybe the ImportDecl does nothing at all. (Common case.)
1141 if (It == ModuleInitializers.end())
1144 // Maybe the ImportDecl only imports another ImportDecl.
1145 auto &Imported = *It->second;
1146 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
1147 Imported.resolve(*this);
1148 auto *OnlyDecl = Imported.Initializers.front();
1149 if (isa<ImportDecl>(OnlyDecl))
1154 auto *&Inits = ModuleInitializers[M];
1156 Inits = new (*this) PerModuleInitializers;
1157 Inits->Initializers.push_back(D);
1160 void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
1161 auto *&Inits = ModuleInitializers[M];
1163 Inits = new (*this) PerModuleInitializers;
1164 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
1165 IDs.begin(), IDs.end());
1168 ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
1169 auto It = ModuleInitializers.find(M);
1170 if (It == ModuleInitializers.end())
1173 auto *Inits = It->second;
1174 Inits->resolve(*this);
1175 return Inits->Initializers;
1178 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1179 if (!ExternCContext)
1180 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1182 return ExternCContext;
1185 BuiltinTemplateDecl *
1186 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1187 const IdentifierInfo *II) const {
1188 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1189 BuiltinTemplate->setImplicit();
1190 TUDecl->addDecl(BuiltinTemplate);
1192 return BuiltinTemplate;
1195 BuiltinTemplateDecl *
1196 ASTContext::getMakeIntegerSeqDecl() const {
1197 if (!MakeIntegerSeqDecl)
1198 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1199 getMakeIntegerSeqName());
1200 return MakeIntegerSeqDecl;
1203 BuiltinTemplateDecl *
1204 ASTContext::getTypePackElementDecl() const {
1205 if (!TypePackElementDecl)
1206 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1207 getTypePackElementName());
1208 return TypePackElementDecl;
1211 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1212 RecordDecl::TagKind TK) const {
1214 RecordDecl *NewDecl;
1215 if (getLangOpts().CPlusPlus)
1216 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1217 Loc, &Idents.get(Name));
1219 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1221 NewDecl->setImplicit();
1222 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1223 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
1227 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1228 StringRef Name) const {
1229 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1230 TypedefDecl *NewDecl = TypedefDecl::Create(
1231 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1232 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1233 NewDecl->setImplicit();
1237 TypedefDecl *ASTContext::getInt128Decl() const {
1239 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
1243 TypedefDecl *ASTContext::getUInt128Decl() const {
1245 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
1249 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
1250 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
1251 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
1252 Types.push_back(Ty);
1255 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1256 const TargetInfo *AuxTarget) {
1257 assert((!this->Target || this->Target == &Target) &&
1258 "Incorrect target reinitialization");
1259 assert(VoidTy.isNull() && "Context reinitialized?");
1261 this->Target = &Target;
1262 this->AuxTarget = AuxTarget;
1264 ABI.reset(createCXXABI(Target));
1265 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
1266 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
1269 InitBuiltinType(VoidTy, BuiltinType::Void);
1272 InitBuiltinType(BoolTy, BuiltinType::Bool);
1274 if (LangOpts.CharIsSigned)
1275 InitBuiltinType(CharTy, BuiltinType::Char_S);
1277 InitBuiltinType(CharTy, BuiltinType::Char_U);
1279 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1280 InitBuiltinType(ShortTy, BuiltinType::Short);
1281 InitBuiltinType(IntTy, BuiltinType::Int);
1282 InitBuiltinType(LongTy, BuiltinType::Long);
1283 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
1286 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1287 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1288 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1289 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1290 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
1293 InitBuiltinType(FloatTy, BuiltinType::Float);
1294 InitBuiltinType(DoubleTy, BuiltinType::Double);
1295 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
1297 // GNU extension, __float128 for IEEE quadruple precision
1298 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1300 // C11 extension ISO/IEC TS 18661-3
1301 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1303 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1304 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1305 InitBuiltinType(AccumTy, BuiltinType::Accum);
1306 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1307 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1308 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1309 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1310 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1311 InitBuiltinType(FractTy, BuiltinType::Fract);
1312 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1313 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1314 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1315 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1316 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1317 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1318 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1319 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1320 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1321 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1322 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1323 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1324 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1325 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1326 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1327 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
1329 // GNU extension, 128-bit integers.
1330 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1331 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1334 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1335 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1336 else // -fshort-wchar makes wchar_t be unsigned.
1337 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1338 if (LangOpts.CPlusPlus && LangOpts.WChar)
1339 WideCharTy = WCharTy;
1341 // C99 (or C++ using -fno-wchar).
1342 WideCharTy = getFromTargetType(Target.getWCharType());
1345 WIntTy = getFromTargetType(Target.getWIntType());
1348 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1350 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1351 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1353 Char16Ty = getFromTargetType(Target.getChar16Type());
1355 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1356 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1358 Char32Ty = getFromTargetType(Target.getChar32Type());
1360 // Placeholder type for type-dependent expressions whose type is
1361 // completely unknown. No code should ever check a type against
1362 // DependentTy and users should never see it; however, it is here to
1363 // help diagnose failures to properly check for type-dependent
1365 InitBuiltinType(DependentTy, BuiltinType::Dependent);
1367 // Placeholder type for functions.
1368 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1370 // Placeholder type for bound members.
1371 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1373 // Placeholder type for pseudo-objects.
1374 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1376 // "any" type; useful for debugger-like clients.
1377 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1379 // Placeholder type for unbridged ARC casts.
1380 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1382 // Placeholder type for builtin functions.
1383 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1385 // Placeholder type for OMP array sections.
1386 if (LangOpts.OpenMP) {
1387 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1388 InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
1389 InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
1391 if (LangOpts.MatrixTypes)
1392 InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
1395 FloatComplexTy = getComplexType(FloatTy);
1396 DoubleComplexTy = getComplexType(DoubleTy);
1397 LongDoubleComplexTy = getComplexType(LongDoubleTy);
1398 Float128ComplexTy = getComplexType(Float128Ty);
1400 // Builtin types for 'id', 'Class', and 'SEL'.
1401 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1402 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1403 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1405 if (LangOpts.OpenCL) {
1406 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1407 InitBuiltinType(SingletonId, BuiltinType::Id);
1408 #include "clang/Basic/OpenCLImageTypes.def"
1410 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1411 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1412 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1413 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1414 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1416 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1417 InitBuiltinType(Id##Ty, BuiltinType::Id);
1418 #include "clang/Basic/OpenCLExtensionTypes.def"
1421 if (Target.hasAArch64SVETypes()) {
1422 #define SVE_TYPE(Name, Id, SingletonId) \
1423 InitBuiltinType(SingletonId, BuiltinType::Id);
1424 #include "clang/Basic/AArch64SVEACLETypes.def"
1427 // Builtin type for __objc_yes and __objc_no
1428 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1429 SignedCharTy : BoolTy);
1431 ObjCConstantStringType = QualType();
1433 ObjCSuperType = QualType();
1436 if (LangOpts.OpenCLVersion >= 200) {
1437 auto Q = VoidTy.getQualifiers();
1438 Q.setAddressSpace(LangAS::opencl_generic);
1439 VoidPtrTy = getPointerType(getCanonicalType(
1440 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1442 VoidPtrTy = getPointerType(VoidTy);
1445 // nullptr type (C++0x 2.14.7)
1446 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
1448 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1449 InitBuiltinType(HalfTy, BuiltinType::Half);
1451 InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
1453 // Builtin type used to help define __builtin_va_list.
1454 VaListTagDecl = nullptr;
1456 // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
1457 if (LangOpts.MicrosoftExt || LangOpts.Borland) {
1458 MSGuidTagDecl = buildImplicitRecord("_GUID");
1459 TUDecl->addDecl(MSGuidTagDecl);
1463 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1464 return SourceMgr.getDiagnostics();
1467 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1468 AttrVec *&Result = DeclAttrs[D];
1470 void *Mem = Allocate(sizeof(AttrVec));
1471 Result = new (Mem) AttrVec;
1477 /// Erase the attributes corresponding to the given declaration.
1478 void ASTContext::eraseDeclAttrs(const Decl *D) {
1479 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1480 if (Pos != DeclAttrs.end()) {
1481 Pos->second->~AttrVec();
1482 DeclAttrs.erase(Pos);
1487 MemberSpecializationInfo *
1488 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1489 assert(Var->isStaticDataMember() && "Not a static data member");
1490 return getTemplateOrSpecializationInfo(Var)
1491 .dyn_cast<MemberSpecializationInfo *>();
1494 ASTContext::TemplateOrSpecializationInfo
1495 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1496 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1497 TemplateOrInstantiation.find(Var);
1498 if (Pos == TemplateOrInstantiation.end())
1505 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1506 TemplateSpecializationKind TSK,
1507 SourceLocation PointOfInstantiation) {
1508 assert(Inst->isStaticDataMember() && "Not a static data member");
1509 assert(Tmpl->isStaticDataMember() && "Not a static data member");
1510 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1511 Tmpl, TSK, PointOfInstantiation));
1515 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1516 TemplateOrSpecializationInfo TSI) {
1517 assert(!TemplateOrInstantiation[Inst] &&
1518 "Already noted what the variable was instantiated from");
1519 TemplateOrInstantiation[Inst] = TSI;
1523 ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1524 auto Pos = InstantiatedFromUsingDecl.find(UUD);
1525 if (Pos == InstantiatedFromUsingDecl.end())
1532 ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
1533 assert((isa<UsingDecl>(Pattern) ||
1534 isa<UnresolvedUsingValueDecl>(Pattern) ||
1535 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1536 "pattern decl is not a using decl");
1537 assert((isa<UsingDecl>(Inst) ||
1538 isa<UnresolvedUsingValueDecl>(Inst) ||
1539 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1540 "instantiation did not produce a using decl");
1541 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1542 InstantiatedFromUsingDecl[Inst] = Pattern;
1546 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1547 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1548 = InstantiatedFromUsingShadowDecl.find(Inst);
1549 if (Pos == InstantiatedFromUsingShadowDecl.end())
1556 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1557 UsingShadowDecl *Pattern) {
1558 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1559 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1562 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1563 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1564 = InstantiatedFromUnnamedFieldDecl.find(Field);
1565 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1571 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1573 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1574 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1575 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1576 "Already noted what unnamed field was instantiated from");
1578 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1581 ASTContext::overridden_cxx_method_iterator
1582 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1583 return overridden_methods(Method).begin();
1586 ASTContext::overridden_cxx_method_iterator
1587 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1588 return overridden_methods(Method).end();
1592 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1593 auto Range = overridden_methods(Method);
1594 return Range.end() - Range.begin();
1597 ASTContext::overridden_method_range
1598 ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1599 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1600 OverriddenMethods.find(Method->getCanonicalDecl());
1601 if (Pos == OverriddenMethods.end())
1602 return overridden_method_range(nullptr, nullptr);
1603 return overridden_method_range(Pos->second.begin(), Pos->second.end());
1606 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1607 const CXXMethodDecl *Overridden) {
1608 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1609 OverriddenMethods[Method].push_back(Overridden);
1612 void ASTContext::getOverriddenMethods(
1614 SmallVectorImpl<const NamedDecl *> &Overridden) const {
1617 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1618 Overridden.append(overridden_methods_begin(CXXMethod),
1619 overridden_methods_end(CXXMethod));
1623 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
1627 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1628 Method->getOverriddenMethods(OverDecls);
1629 Overridden.append(OverDecls.begin(), OverDecls.end());
1632 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1633 assert(!Import->getNextLocalImport() &&
1634 "Import declaration already in the chain");
1635 assert(!Import->isFromASTFile() && "Non-local import declaration");
1636 if (!FirstLocalImport) {
1637 FirstLocalImport = Import;
1638 LastLocalImport = Import;
1642 LastLocalImport->setNextLocalImport(Import);
1643 LastLocalImport = Import;
1646 //===----------------------------------------------------------------------===//
1647 // Type Sizing and Analysis
1648 //===----------------------------------------------------------------------===//
1650 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1651 /// scalar floating point type.
1652 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1653 switch (T->castAs<BuiltinType>()->getKind()) {
1655 llvm_unreachable("Not a floating point type!");
1656 case BuiltinType::BFloat16:
1657 return Target->getBFloat16Format();
1658 case BuiltinType::Float16:
1659 case BuiltinType::Half:
1660 return Target->getHalfFormat();
1661 case BuiltinType::Float: return Target->getFloatFormat();
1662 case BuiltinType::Double: return Target->getDoubleFormat();
1663 case BuiltinType::LongDouble:
1664 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1665 return AuxTarget->getLongDoubleFormat();
1666 return Target->getLongDoubleFormat();
1667 case BuiltinType::Float128:
1668 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
1669 return AuxTarget->getFloat128Format();
1670 return Target->getFloat128Format();
1674 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1675 unsigned Align = Target->getCharWidth();
1677 bool UseAlignAttrOnly = false;
1678 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1679 Align = AlignFromAttr;
1681 // __attribute__((aligned)) can increase or decrease alignment
1682 // *except* on a struct or struct member, where it only increases
1683 // alignment unless 'packed' is also specified.
1685 // It is an error for alignas to decrease alignment, so we can
1686 // ignore that possibility; Sema should diagnose it.
1687 if (isa<FieldDecl>(D)) {
1688 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1689 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1691 UseAlignAttrOnly = true;
1694 else if (isa<FieldDecl>(D))
1696 D->hasAttr<PackedAttr>() ||
1697 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1699 // If we're using the align attribute only, just ignore everything
1700 // else about the declaration and its type.
1701 if (UseAlignAttrOnly) {
1703 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
1704 QualType T = VD->getType();
1705 if (const auto *RT = T->getAs<ReferenceType>()) {
1707 T = RT->getPointeeType();
1709 T = getPointerType(RT->getPointeeType());
1711 QualType BaseT = getBaseElementType(T);
1712 if (T->isFunctionType())
1713 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1714 else if (!BaseT->isIncompleteType()) {
1715 // Adjust alignments of declarations with array type by the
1716 // large-array alignment on the target.
1717 if (const ArrayType *arrayType = getAsArrayType(T)) {
1718 unsigned MinWidth = Target->getLargeArrayMinWidth();
1719 if (!ForAlignof && MinWidth) {
1720 if (isa<VariableArrayType>(arrayType))
1721 Align = std::max(Align, Target->getLargeArrayAlign());
1722 else if (isa<ConstantArrayType>(arrayType) &&
1723 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1724 Align = std::max(Align, Target->getLargeArrayAlign());
1727 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1728 if (BaseT.getQualifiers().hasUnaligned())
1729 Align = Target->getCharWidth();
1730 if (const auto *VD = dyn_cast<VarDecl>(D)) {
1731 if (VD->hasGlobalStorage() && !ForAlignof) {
1732 uint64_t TypeSize = getTypeSize(T.getTypePtr());
1733 Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
1738 // Fields can be subject to extra alignment constraints, like if
1739 // the field is packed, the struct is packed, or the struct has a
1740 // a max-field-alignment constraint (#pragma pack). So calculate
1741 // the actual alignment of the field within the struct, and then
1742 // (as we're expected to) constrain that by the alignment of the type.
1743 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
1744 const RecordDecl *Parent = Field->getParent();
1745 // We can only produce a sensible answer if the record is valid.
1746 if (!Parent->isInvalidDecl()) {
1747 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1749 // Start with the record's overall alignment.
1750 unsigned FieldAlign = toBits(Layout.getAlignment());
1752 // Use the GCD of that and the offset within the record.
1753 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1755 // Alignment is always a power of 2, so the GCD will be a power of 2,
1756 // which means we get to do this crazy thing instead of Euclid's.
1757 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1758 if (LowBitOfOffset < FieldAlign)
1759 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1762 Align = std::min(Align, FieldAlign);
1767 return toCharUnitsFromBits(Align);
1770 CharUnits ASTContext::getExnObjectAlignment() const {
1771 return toCharUnitsFromBits(Target->getExnObjectAlignment());
1774 // getTypeInfoDataSizeInChars - Return the size of a type, in
1775 // chars. If the type is a record, its data size is returned. This is
1776 // the size of the memcpy that's performed when assigning this type
1777 // using a trivial copy/move assignment operator.
1778 std::pair<CharUnits, CharUnits>
1779 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1780 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1782 // In C++, objects can sometimes be allocated into the tail padding
1783 // of a base-class subobject. We decide whether that's possible
1784 // during class layout, so here we can just trust the layout results.
1785 if (getLangOpts().CPlusPlus) {
1786 if (const auto *RT = T->getAs<RecordType>()) {
1787 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1788 sizeAndAlign.first = layout.getDataSize();
1792 return sizeAndAlign;
1795 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1796 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1797 std::pair<CharUnits, CharUnits>
1798 static getConstantArrayInfoInChars(const ASTContext &Context,
1799 const ConstantArrayType *CAT) {
1800 std::pair<CharUnits, CharUnits> EltInfo =
1801 Context.getTypeInfoInChars(CAT->getElementType());
1802 uint64_t Size = CAT->getSize().getZExtValue();
1803 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1804 (uint64_t)(-1)/Size) &&
1805 "Overflow in array type char size evaluation");
1806 uint64_t Width = EltInfo.first.getQuantity() * Size;
1807 unsigned Align = EltInfo.second.getQuantity();
1808 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1809 Context.getTargetInfo().getPointerWidth(0) == 64)
1810 Width = llvm::alignTo(Width, Align);
1811 return std::make_pair(CharUnits::fromQuantity(Width),
1812 CharUnits::fromQuantity(Align));
1815 std::pair<CharUnits, CharUnits>
1816 ASTContext::getTypeInfoInChars(const Type *T) const {
1817 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1818 return getConstantArrayInfoInChars(*this, CAT);
1819 TypeInfo Info = getTypeInfo(T);
1820 return std::make_pair(toCharUnitsFromBits(Info.Width),
1821 toCharUnitsFromBits(Info.Align));
1824 std::pair<CharUnits, CharUnits>
1825 ASTContext::getTypeInfoInChars(QualType T) const {
1826 return getTypeInfoInChars(T.getTypePtr());
1829 bool ASTContext::isAlignmentRequired(const Type *T) const {
1830 return getTypeInfo(T).AlignIsRequired;
1833 bool ASTContext::isAlignmentRequired(QualType T) const {
1834 return isAlignmentRequired(T.getTypePtr());
1837 unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1838 // An alignment on a typedef overrides anything else.
1839 if (const auto *TT = T->getAs<TypedefType>())
1840 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1843 // If we have an (array of) complete type, we're done.
1844 T = getBaseElementType(T);
1845 if (!T->isIncompleteType())
1846 return getTypeAlign(T);
1848 // If we had an array type, its element type might be a typedef
1849 // type with an alignment attribute.
1850 if (const auto *TT = T->getAs<TypedefType>())
1851 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1854 // Otherwise, see if the declaration of the type had an attribute.
1855 if (const auto *TT = T->getAs<TagType>())
1856 return TT->getDecl()->getMaxAlignment();
1861 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1862 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1863 if (I != MemoizedTypeInfo.end())
1866 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1867 TypeInfo TI = getTypeInfoImpl(T);
1868 MemoizedTypeInfo[T] = TI;
1872 /// getTypeInfoImpl - Return the size of the specified type, in bits. This
1873 /// method does not work on incomplete types.
1875 /// FIXME: Pointers into different addr spaces could have different sizes and
1876 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1877 /// should take a QualType, &c.
1878 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1881 bool AlignIsRequired = false;
1883 switch (T->getTypeClass()) {
1884 #define TYPE(Class, Base)
1885 #define ABSTRACT_TYPE(Class, Base)
1886 #define NON_CANONICAL_TYPE(Class, Base)
1887 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1888 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1890 assert(!T->isDependentType() && "should not see dependent types here"); \
1891 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1892 #include "clang/AST/TypeNodes.inc"
1893 llvm_unreachable("Should not see dependent types");
1895 case Type::FunctionNoProto:
1896 case Type::FunctionProto:
1897 // GCC extension: alignof(function) = 32 bits
1902 case Type::IncompleteArray:
1903 case Type::VariableArray:
1904 case Type::ConstantArray: {
1905 // Model non-constant sized arrays as size zero, but track the alignment.
1907 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
1908 Size = CAT->getSize().getZExtValue();
1910 TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
1911 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1912 "Overflow in array type bit size evaluation");
1913 Width = EltInfo.Width * Size;
1914 Align = EltInfo.Align;
1915 AlignIsRequired = EltInfo.AlignIsRequired;
1916 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1917 getTargetInfo().getPointerWidth(0) == 64)
1918 Width = llvm::alignTo(Width, Align);
1922 case Type::ExtVector:
1923 case Type::Vector: {
1924 const auto *VT = cast<VectorType>(T);
1925 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1926 Width = EltInfo.Width * VT->getNumElements();
1928 // If the alignment is not a power of 2, round up to the next power of 2.
1929 // This happens for non-power-of-2 length vectors.
1930 if (Align & (Align-1)) {
1931 Align = llvm::NextPowerOf2(Align);
1932 Width = llvm::alignTo(Width, Align);
1934 // Adjust the alignment based on the target max.
1935 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1936 if (TargetVectorAlign && TargetVectorAlign < Align)
1937 Align = TargetVectorAlign;
1941 case Type::ConstantMatrix: {
1942 const auto *MT = cast<ConstantMatrixType>(T);
1943 TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
1944 // The internal layout of a matrix value is implementation defined.
1945 // Initially be ABI compatible with arrays with respect to alignment and
1947 Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
1948 Align = ElementInfo.Align;
1953 switch (cast<BuiltinType>(T)->getKind()) {
1954 default: llvm_unreachable("Unknown builtin type!");
1955 case BuiltinType::Void:
1956 // GCC extension: alignof(void) = 8 bits.
1960 case BuiltinType::Bool:
1961 Width = Target->getBoolWidth();
1962 Align = Target->getBoolAlign();
1964 case BuiltinType::Char_S:
1965 case BuiltinType::Char_U:
1966 case BuiltinType::UChar:
1967 case BuiltinType::SChar:
1968 case BuiltinType::Char8:
1969 Width = Target->getCharWidth();
1970 Align = Target->getCharAlign();
1972 case BuiltinType::WChar_S:
1973 case BuiltinType::WChar_U:
1974 Width = Target->getWCharWidth();
1975 Align = Target->getWCharAlign();
1977 case BuiltinType::Char16:
1978 Width = Target->getChar16Width();
1979 Align = Target->getChar16Align();
1981 case BuiltinType::Char32:
1982 Width = Target->getChar32Width();
1983 Align = Target->getChar32Align();
1985 case BuiltinType::UShort:
1986 case BuiltinType::Short:
1987 Width = Target->getShortWidth();
1988 Align = Target->getShortAlign();
1990 case BuiltinType::UInt:
1991 case BuiltinType::Int:
1992 Width = Target->getIntWidth();
1993 Align = Target->getIntAlign();
1995 case BuiltinType::ULong:
1996 case BuiltinType::Long:
1997 Width = Target->getLongWidth();
1998 Align = Target->getLongAlign();
2000 case BuiltinType::ULongLong:
2001 case BuiltinType::LongLong:
2002 Width = Target->getLongLongWidth();
2003 Align = Target->getLongLongAlign();
2005 case BuiltinType::Int128:
2006 case BuiltinType::UInt128:
2008 Align = 128; // int128_t is 128-bit aligned on all targets.
2010 case BuiltinType::ShortAccum:
2011 case BuiltinType::UShortAccum:
2012 case BuiltinType::SatShortAccum:
2013 case BuiltinType::SatUShortAccum:
2014 Width = Target->getShortAccumWidth();
2015 Align = Target->getShortAccumAlign();
2017 case BuiltinType::Accum:
2018 case BuiltinType::UAccum:
2019 case BuiltinType::SatAccum:
2020 case BuiltinType::SatUAccum:
2021 Width = Target->getAccumWidth();
2022 Align = Target->getAccumAlign();
2024 case BuiltinType::LongAccum:
2025 case BuiltinType::ULongAccum:
2026 case BuiltinType::SatLongAccum:
2027 case BuiltinType::SatULongAccum:
2028 Width = Target->getLongAccumWidth();
2029 Align = Target->getLongAccumAlign();
2031 case BuiltinType::ShortFract:
2032 case BuiltinType::UShortFract:
2033 case BuiltinType::SatShortFract:
2034 case BuiltinType::SatUShortFract:
2035 Width = Target->getShortFractWidth();
2036 Align = Target->getShortFractAlign();
2038 case BuiltinType::Fract:
2039 case BuiltinType::UFract:
2040 case BuiltinType::SatFract:
2041 case BuiltinType::SatUFract:
2042 Width = Target->getFractWidth();
2043 Align = Target->getFractAlign();
2045 case BuiltinType::LongFract:
2046 case BuiltinType::ULongFract:
2047 case BuiltinType::SatLongFract:
2048 case BuiltinType::SatULongFract:
2049 Width = Target->getLongFractWidth();
2050 Align = Target->getLongFractAlign();
2052 case BuiltinType::BFloat16:
2053 Width = Target->getBFloat16Width();
2054 Align = Target->getBFloat16Align();
2056 case BuiltinType::Float16:
2057 case BuiltinType::Half:
2058 if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
2059 !getLangOpts().OpenMPIsDevice) {
2060 Width = Target->getHalfWidth();
2061 Align = Target->getHalfAlign();
2063 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2064 "Expected OpenMP device compilation.");
2065 Width = AuxTarget->getHalfWidth();
2066 Align = AuxTarget->getHalfAlign();
2069 case BuiltinType::Float:
2070 Width = Target->getFloatWidth();
2071 Align = Target->getFloatAlign();
2073 case BuiltinType::Double:
2074 Width = Target->getDoubleWidth();
2075 Align = Target->getDoubleAlign();
2077 case BuiltinType::LongDouble:
2078 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2079 (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
2080 Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
2081 Width = AuxTarget->getLongDoubleWidth();
2082 Align = AuxTarget->getLongDoubleAlign();
2084 Width = Target->getLongDoubleWidth();
2085 Align = Target->getLongDoubleAlign();
2088 case BuiltinType::Float128:
2089 if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
2090 !getLangOpts().OpenMPIsDevice) {
2091 Width = Target->getFloat128Width();
2092 Align = Target->getFloat128Align();
2094 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2095 "Expected OpenMP device compilation.");
2096 Width = AuxTarget->getFloat128Width();
2097 Align = AuxTarget->getFloat128Align();
2100 case BuiltinType::NullPtr:
2101 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
2102 Align = Target->getPointerAlign(0); // == sizeof(void*)
2104 case BuiltinType::ObjCId:
2105 case BuiltinType::ObjCClass:
2106 case BuiltinType::ObjCSel:
2107 Width = Target->getPointerWidth(0);
2108 Align = Target->getPointerAlign(0);
2110 case BuiltinType::OCLSampler:
2111 case BuiltinType::OCLEvent:
2112 case BuiltinType::OCLClkEvent:
2113 case BuiltinType::OCLQueue:
2114 case BuiltinType::OCLReserveID:
2115 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2116 case BuiltinType::Id:
2117 #include "clang/Basic/OpenCLImageTypes.def"
2118 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2119 case BuiltinType::Id:
2120 #include "clang/Basic/OpenCLExtensionTypes.def"
2121 AS = getTargetAddressSpace(
2122 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
2123 Width = Target->getPointerWidth(AS);
2124 Align = Target->getPointerAlign(AS);
2126 // The SVE types are effectively target-specific. The length of an
2127 // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
2128 // of 128 bits. There is one predicate bit for each vector byte, so the
2129 // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
2131 // Because the length is only known at runtime, we use a dummy value
2132 // of 0 for the static length. The alignment values are those defined
2133 // by the Procedure Call Standard for the Arm Architecture.
2134 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
2135 IsSigned, IsFP, IsBF) \
2136 case BuiltinType::Id: \
2140 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
2141 case BuiltinType::Id: \
2145 #include "clang/Basic/AArch64SVEACLETypes.def"
2148 case Type::ObjCObjectPointer:
2149 Width = Target->getPointerWidth(0);
2150 Align = Target->getPointerAlign(0);
2152 case Type::BlockPointer:
2153 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
2154 Width = Target->getPointerWidth(AS);
2155 Align = Target->getPointerAlign(AS);
2157 case Type::LValueReference:
2158 case Type::RValueReference:
2159 // alignof and sizeof should never enter this code path here, so we go
2160 // the pointer route.
2161 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
2162 Width = Target->getPointerWidth(AS);
2163 Align = Target->getPointerAlign(AS);
2166 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
2167 Width = Target->getPointerWidth(AS);
2168 Align = Target->getPointerAlign(AS);
2170 case Type::MemberPointer: {
2171 const auto *MPT = cast<MemberPointerType>(T);
2172 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
2177 case Type::Complex: {
2178 // Complex types have the same alignment as their elements, but twice the
2180 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
2181 Width = EltInfo.Width * 2;
2182 Align = EltInfo.Align;
2185 case Type::ObjCObject:
2186 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
2187 case Type::Adjusted:
2189 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
2190 case Type::ObjCInterface: {
2191 const auto *ObjCI = cast<ObjCInterfaceType>(T);
2192 if (ObjCI->getDecl()->isInvalidDecl()) {
2197 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2198 Width = toBits(Layout.getSize());
2199 Align = toBits(Layout.getAlignment());
2202 case Type::ExtInt: {
2203 const auto *EIT = cast<ExtIntType>(T);
2205 std::min(static_cast<unsigned>(std::max(
2206 getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))),
2207 Target->getLongLongAlign());
2208 Width = llvm::alignTo(EIT->getNumBits(), Align);
2213 const auto *TT = cast<TagType>(T);
2215 if (TT->getDecl()->isInvalidDecl()) {
2221 if (const auto *ET = dyn_cast<EnumType>(TT)) {
2222 const EnumDecl *ED = ET->getDecl();
2224 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
2225 if (unsigned AttrAlign = ED->getMaxAlignment()) {
2226 Info.Align = AttrAlign;
2227 Info.AlignIsRequired = true;
2232 const auto *RT = cast<RecordType>(TT);
2233 const RecordDecl *RD = RT->getDecl();
2234 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2235 Width = toBits(Layout.getSize());
2236 Align = toBits(Layout.getAlignment());
2237 AlignIsRequired = RD->hasAttr<AlignedAttr>();
2241 case Type::SubstTemplateTypeParm:
2242 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
2243 getReplacementType().getTypePtr());
2246 case Type::DeducedTemplateSpecialization: {
2247 const auto *A = cast<DeducedType>(T);
2248 assert(!A->getDeducedType().isNull() &&
2249 "cannot request the size of an undeduced or dependent auto type");
2250 return getTypeInfo(A->getDeducedType().getTypePtr());
2254 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
2256 case Type::MacroQualified:
2258 cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
2260 case Type::ObjCTypeParam:
2261 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
2263 case Type::Typedef: {
2264 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
2265 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
2266 // If the typedef has an aligned attribute on it, it overrides any computed
2267 // alignment we have. This violates the GCC documentation (which says that
2268 // attribute(aligned) can only round up) but matches its implementation.
2269 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
2271 AlignIsRequired = true;
2274 AlignIsRequired = Info.AlignIsRequired;
2280 case Type::Elaborated:
2281 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
2283 case Type::Attributed:
2285 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2287 case Type::Atomic: {
2288 // Start with the base type information.
2289 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2294 // An otherwise zero-sized type should still generate an
2295 // atomic operation.
2296 Width = Target->getCharWidth();
2298 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2299 // If the size of the type doesn't exceed the platform's max
2300 // atomic promotion width, make the size and alignment more
2301 // favorable to atomic operations:
2303 // Round the size up to a power of 2.
2304 if (!llvm::isPowerOf2_64(Width))
2305 Width = llvm::NextPowerOf2(Width);
2307 // Set the alignment equal to the size.
2308 Align = static_cast<unsigned>(Width);
2314 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2315 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
2319 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
2320 return TypeInfo(Width, Align, AlignIsRequired);
2323 unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2324 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2325 if (I != MemoizedUnadjustedAlign.end())
2328 unsigned UnadjustedAlign;
2329 if (const auto *RT = T->getAs<RecordType>()) {
2330 const RecordDecl *RD = RT->getDecl();
2331 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2332 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2333 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2334 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2335 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2337 UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
2340 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2341 return UnadjustedAlign;
2344 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2345 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2346 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2347 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2348 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2349 getTargetInfo().getABI() == "elfv1-qpx" &&
2350 T->isSpecificBuiltinType(BuiltinType::Double))
2355 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2356 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2357 return CharUnits::fromQuantity(BitSize / getCharWidth());
2360 /// toBits - Convert a size in characters to a size in characters.
2361 int64_t ASTContext::toBits(CharUnits CharSize) const {
2362 return CharSize.getQuantity() * getCharWidth();
2365 /// getTypeSizeInChars - Return the size of the specified type, in characters.
2366 /// This method does not work on incomplete types.
2367 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
2368 return getTypeInfoInChars(T).first;
2370 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
2371 return getTypeInfoInChars(T).first;
2374 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
2375 /// characters. This method does not work on incomplete types.
2376 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
2377 return toCharUnitsFromBits(getTypeAlign(T));
2379 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
2380 return toCharUnitsFromBits(getTypeAlign(T));
2383 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2384 /// type, in characters, before alignment adustments. This method does
2385 /// not work on incomplete types.
2386 CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2387 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2389 CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2390 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2393 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2394 /// type for the current target in bits. This can be different than the ABI
2395 /// alignment in cases where it is beneficial for performance to overalign
2397 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
2398 TypeInfo TI = getTypeInfo(T);
2399 unsigned ABIAlign = TI.Align;
2401 T = T->getBaseElementTypeUnsafe();
2403 // The preferred alignment of member pointers is that of a pointer.
2404 if (T->isMemberPointerType())
2405 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2407 if (!Target->allowsLargerPreferedTypeAlignment())
2410 // Double and long long should be naturally aligned if possible.
2411 if (const auto *CT = T->getAs<ComplexType>())
2412 T = CT->getElementType().getTypePtr();
2413 if (const auto *ET = T->getAs<EnumType>())
2414 T = ET->getDecl()->getIntegerType().getTypePtr();
2415 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
2416 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2417 T->isSpecificBuiltinType(BuiltinType::ULongLong))
2418 // Don't increase the alignment if an alignment attribute was specified on a
2419 // typedef declaration.
2420 if (!TI.AlignIsRequired)
2421 return std::max(ABIAlign, (unsigned)getTypeSize(T));
2426 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2427 /// for __attribute__((aligned)) on this target, to be used if no alignment
2428 /// value is specified.
2429 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
2430 return getTargetInfo().getDefaultAlignForAttributeAligned();
2433 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
2434 /// to a global variable of the specified type.
2435 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2436 uint64_t TypeSize = getTypeSize(T.getTypePtr());
2437 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
2440 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
2441 /// should be given to a global variable of the specified type.
2442 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2443 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2446 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2447 CharUnits Offset = CharUnits::Zero();
2448 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2449 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2450 Offset += Layout->getBaseClassOffset(Base);
2451 Layout = &getASTRecordLayout(Base);
2456 /// DeepCollectObjCIvars -
2457 /// This routine first collects all declared, but not synthesized, ivars in
2458 /// super class and then collects all ivars, including those synthesized for
2459 /// current class. This routine is used for implementation of current class
2460 /// when all ivars, declared and synthesized are known.
2461 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2463 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
2464 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2465 DeepCollectObjCIvars(SuperClass, false, Ivars);
2467 for (const auto *I : OI->ivars())
2470 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
2471 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
2472 Iv= Iv->getNextIvar())
2473 Ivars.push_back(Iv);
2477 /// CollectInheritedProtocols - Collect all protocols in current class and
2478 /// those inherited by it.
2479 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
2480 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
2481 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2482 // We can use protocol_iterator here instead of
2483 // all_referenced_protocol_iterator since we are walking all categories.
2484 for (auto *Proto : OI->all_referenced_protocols()) {
2485 CollectInheritedProtocols(Proto, Protocols);
2488 // Categories of this Interface.
2489 for (const auto *Cat : OI->visible_categories())
2490 CollectInheritedProtocols(Cat, Protocols);
2492 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2494 CollectInheritedProtocols(SD, Protocols);
2495 SD = SD->getSuperClass();
2497 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2498 for (auto *Proto : OC->protocols()) {
2499 CollectInheritedProtocols(Proto, Protocols);
2501 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
2502 // Insert the protocol.
2503 if (!Protocols.insert(
2504 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2507 for (auto *Proto : OP->protocols())
2508 CollectInheritedProtocols(Proto, Protocols);
2512 static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2513 const RecordDecl *RD) {
2514 assert(RD->isUnion() && "Must be union type");
2515 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2517 for (const auto *Field : RD->fields()) {
2518 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2520 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2521 if (FieldSize != UnionSize)
2524 return !RD->field_empty();
2527 static bool isStructEmpty(QualType Ty) {
2528 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2530 if (!RD->field_empty())
2533 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2534 return ClassDecl->isEmpty();
2539 static llvm::Optional<int64_t>
2540 structHasUniqueObjectRepresentations(const ASTContext &Context,
2541 const RecordDecl *RD) {
2542 assert(!RD->isUnion() && "Must be struct/class type");
2543 const auto &Layout = Context.getASTRecordLayout(RD);
2545 int64_t CurOffsetInBits = 0;
2546 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2547 if (ClassDecl->isDynamicClass())
2550 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2551 for (const auto &Base : ClassDecl->bases()) {
2552 // Empty types can be inherited from, and non-empty types can potentially
2553 // have tail padding, so just make sure there isn't an error.
2554 if (!isStructEmpty(Base.getType())) {
2555 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2556 Context, Base.getType()->castAs<RecordType>()->getDecl());
2559 Bases.emplace_back(Base.getType(), Size.getValue());
2563 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2564 const std::pair<QualType, int64_t> &R) {
2565 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2566 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2569 for (const auto &Base : Bases) {
2570 int64_t BaseOffset = Context.toBits(
2571 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2572 int64_t BaseSize = Base.second;
2573 if (BaseOffset != CurOffsetInBits)
2575 CurOffsetInBits = BaseOffset + BaseSize;
2579 for (const auto *Field : RD->fields()) {
2580 if (!Field->getType()->isReferenceType() &&
2581 !Context.hasUniqueObjectRepresentations(Field->getType()))
2584 int64_t FieldSizeInBits =
2585 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2586 if (Field->isBitField()) {
2587 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2589 if (BitfieldSize > FieldSizeInBits)
2591 FieldSizeInBits = BitfieldSize;
2594 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2596 if (FieldOffsetInBits != CurOffsetInBits)
2599 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2602 return CurOffsetInBits;
2605 bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2606 // C++17 [meta.unary.prop]:
2607 // The predicate condition for a template specialization
2608 // has_unique_object_representations<T> shall be
2609 // satisfied if and only if:
2610 // (9.1) - T is trivially copyable, and
2611 // (9.2) - any two objects of type T with the same value have the same
2612 // object representation, where two objects
2613 // of array or non-union class type are considered to have the same value
2614 // if their respective sequences of
2615 // direct subobjects have the same values, and two objects of union type
2616 // are considered to have the same
2617 // value if they have the same active member and the corresponding members
2618 // have the same value.
2619 // The set of scalar types for which this condition holds is
2620 // implementation-defined. [ Note: If a type has padding
2621 // bits, the condition does not hold; otherwise, the condition holds true
2622 // for unsigned integral types. -- end note ]
2623 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2625 // Arrays are unique only if their element type is unique.
2626 if (Ty->isArrayType())
2627 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2629 // (9.1) - T is trivially copyable...
2630 if (!Ty.isTriviallyCopyableType(*this))
2633 // All integrals and enums are unique.
2634 if (Ty->isIntegralOrEnumerationType())
2637 // All other pointers are unique.
2638 if (Ty->isPointerType())
2641 if (Ty->isMemberPointerType()) {
2642 const auto *MPT = Ty->getAs<MemberPointerType>();
2643 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2646 if (Ty->isRecordType()) {
2647 const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
2649 if (Record->isInvalidDecl())
2652 if (Record->isUnion())
2653 return unionHasUniqueObjectRepresentations(*this, Record);
2655 Optional<int64_t> StructSize =
2656 structHasUniqueObjectRepresentations(*this, Record);
2658 return StructSize &&
2659 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2662 // FIXME: More cases to handle here (list by rsmith):
2663 // vectors (careful about, eg, vector of 3 foo)
2664 // _Complex int and friends
2666 // Obj-C block pointers
2667 // Obj-C object pointers
2668 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2669 // clk_event_t, queue_t, reserve_id_t)
2670 // There're also Obj-C class types and the Obj-C selector type, but I think it
2671 // makes sense for those to return false here.
2676 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2678 // Count ivars declared in class extension.
2679 for (const auto *Ext : OI->known_extensions())
2680 count += Ext->ivar_size();
2682 // Count ivar defined in this class's implementation. This
2683 // includes synthesized ivars.
2684 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2685 count += ImplDecl->ivar_size();
2690 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2694 // nullptr_t is always treated as null.
2695 if (E->getType()->isNullPtrType()) return true;
2697 if (E->getType()->isAnyPointerType() &&
2698 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2699 Expr::NPC_ValueDependentIsNull))
2702 // Unfortunately, __null has type 'int'.
2703 if (isa<GNUNullExpr>(E)) return true;
2708 /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
2710 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2711 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2712 I = ObjCImpls.find(D);
2713 if (I != ObjCImpls.end())
2714 return cast<ObjCImplementationDecl>(I->second);
2718 /// Get the implementation of ObjCCategoryDecl, or nullptr if none
2720 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2721 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2722 I = ObjCImpls.find(D);
2723 if (I != ObjCImpls.end())
2724 return cast<ObjCCategoryImplDecl>(I->second);
2728 /// Set the implementation of ObjCInterfaceDecl.
2729 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2730 ObjCImplementationDecl *ImplD) {
2731 assert(IFaceD && ImplD && "Passed null params");
2732 ObjCImpls[IFaceD] = ImplD;
2735 /// Set the implementation of ObjCCategoryDecl.
2736 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2737 ObjCCategoryImplDecl *ImplD) {
2738 assert(CatD && ImplD && "Passed null params");
2739 ObjCImpls[CatD] = ImplD;
2742 const ObjCMethodDecl *
2743 ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2744 return ObjCMethodRedecls.lookup(MD);
2747 void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2748 const ObjCMethodDecl *Redecl) {
2749 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2750 ObjCMethodRedecls[MD] = Redecl;
2753 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2754 const NamedDecl *ND) const {
2755 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2757 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2758 return CD->getClassInterface();
2759 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2760 return IMD->getClassInterface();
2765 /// Get the copy initialization expression of VarDecl, or nullptr if
2767 BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
2768 assert(VD && "Passed null params");
2769 assert(VD->hasAttr<BlocksAttr>() &&
2770 "getBlockVarCopyInits - not __block var");
2771 auto I = BlockVarCopyInits.find(VD);
2772 if (I != BlockVarCopyInits.end())
2774 return {nullptr, false};
2777 /// Set the copy initialization expression of a block var decl.
2778 void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2780 assert(VD && CopyExpr && "Passed null params");
2781 assert(VD->hasAttr<BlocksAttr>() &&
2782 "setBlockVarCopyInits - not __block var");
2783 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
2786 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2787 unsigned DataSize) const {
2789 DataSize = TypeLoc::getFullDataSizeForType(T);
2791 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2792 "incorrect data size provided to CreateTypeSourceInfo!");
2795 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2796 new (TInfo) TypeSourceInfo(T);
2800 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2801 SourceLocation L) const {
2802 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2803 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2807 const ASTRecordLayout &
2808 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2809 return getObjCLayout(D, nullptr);
2812 const ASTRecordLayout &
2813 ASTContext::getASTObjCImplementationLayout(
2814 const ObjCImplementationDecl *D) const {
2815 return getObjCLayout(D->getClassInterface(), D);
2818 //===----------------------------------------------------------------------===//
2819 // Type creation/memoization methods
2820 //===----------------------------------------------------------------------===//
2823 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2824 unsigned fastQuals = quals.getFastQualifiers();
2825 quals.removeFastQualifiers();
2827 // Check if we've already instantiated this type.
2828 llvm::FoldingSetNodeID ID;
2829 ExtQuals::Profile(ID, baseType, quals);
2830 void *insertPos = nullptr;
2831 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2832 assert(eq->getQualifiers() == quals);
2833 return QualType(eq, fastQuals);
2836 // If the base type is not canonical, make the appropriate canonical type.
2838 if (!baseType->isCanonicalUnqualified()) {
2839 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2840 canonSplit.Quals.addConsistentQualifiers(quals);
2841 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2843 // Re-find the insert position.
2844 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2847 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2848 ExtQualNodes.InsertNode(eq, insertPos);
2849 return QualType(eq, fastQuals);
2852 QualType ASTContext::getAddrSpaceQualType(QualType T,
2853 LangAS AddressSpace) const {
2854 QualType CanT = getCanonicalType(T);
2855 if (CanT.getAddressSpace() == AddressSpace)
2858 // If we are composing extended qualifiers together, merge together
2859 // into one ExtQuals node.
2860 QualifierCollector Quals;
2861 const Type *TypeNode = Quals.strip(T);
2863 // If this type already has an address space specified, it cannot get
2865 assert(!Quals.hasAddressSpace() &&
2866 "Type cannot be in multiple addr spaces!");
2867 Quals.addAddressSpace(AddressSpace);
2869 return getExtQualType(TypeNode, Quals);
2872 QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2873 // If we are composing extended qualifiers together, merge together
2874 // into one ExtQuals node.
2875 QualifierCollector Quals;
2876 const Type *TypeNode = Quals.strip(T);
2878 // If the qualifier doesn't have an address space just return it.
2879 if (!Quals.hasAddressSpace())
2882 Quals.removeAddressSpace();
2884 // Removal of the address space can mean there are no longer any
2885 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2887 if (Quals.hasNonFastQualifiers())
2888 return getExtQualType(TypeNode, Quals);
2890 return QualType(TypeNode, Quals.getFastQualifiers());
2893 QualType ASTContext::getObjCGCQualType(QualType T,
2894 Qualifiers::GC GCAttr) const {
2895 QualType CanT = getCanonicalType(T);
2896 if (CanT.getObjCGCAttr() == GCAttr)
2899 if (const auto *ptr = T->getAs<PointerType>()) {
2900 QualType Pointee = ptr->getPointeeType();
2901 if (Pointee->isAnyPointerType()) {
2902 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2903 return getPointerType(ResultType);
2907 // If we are composing extended qualifiers together, merge together
2908 // into one ExtQuals node.
2909 QualifierCollector Quals;
2910 const Type *TypeNode = Quals.strip(T);
2912 // If this type already has an ObjCGC specified, it cannot get
2914 assert(!Quals.hasObjCGCAttr() &&
2915 "Type cannot have multiple ObjCGCs!");
2916 Quals.addObjCGCAttr(GCAttr);
2918 return getExtQualType(TypeNode, Quals);
2921 QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
2922 if (const PointerType *Ptr = T->getAs<PointerType>()) {
2923 QualType Pointee = Ptr->getPointeeType();
2924 if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
2925 return getPointerType(removeAddrSpaceQualType(Pointee));
2931 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2932 FunctionType::ExtInfo Info) {
2933 if (T->getExtInfo() == Info)
2937 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2938 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2940 const auto *FPT = cast<FunctionProtoType>(T);
2941 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2943 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2946 return cast<FunctionType>(Result.getTypePtr());
2949 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2950 QualType ResultType) {
2951 FD = FD->getMostRecentDecl();
2953 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
2954 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2955 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2956 if (FunctionDecl *Next = FD->getPreviousDecl())
2961 if (ASTMutationListener *L = getASTMutationListener())
2962 L->DeducedReturnType(FD, ResultType);
2965 /// Get a function type and produce the equivalent function type with the
2966 /// specified exception specification. Type sugar that can be present on a
2967 /// declaration of a function with an exception specification is permitted
2968 /// and preserved. Other type sugar (for instance, typedefs) is not.
2969 QualType ASTContext::getFunctionTypeWithExceptionSpec(
2970 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
2971 // Might have some parens.
2972 if (const auto *PT = dyn_cast<ParenType>(Orig))
2973 return getParenType(
2974 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
2976 // Might be wrapped in a macro qualified type.
2977 if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
2978 return getMacroQualifiedType(
2979 getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
2980 MQT->getMacroIdentifier());
2982 // Might have a calling-convention attribute.
2983 if (const auto *AT = dyn_cast<AttributedType>(Orig))
2984 return getAttributedType(
2986 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2987 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
2989 // Anything else must be a function type. Rebuild it with the new exception
2991 const auto *Proto = Orig->castAs<FunctionProtoType>();
2992 return getFunctionType(
2993 Proto->getReturnType(), Proto->getParamTypes(),
2994 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2997 bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2999 return hasSameType(T, U) ||
3000 (getLangOpts().CPlusPlus17 &&
3001 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
3002 getFunctionTypeWithExceptionSpec(U, EST_None)));
3005 QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
3006 if (const auto *Proto = T->getAs<FunctionProtoType>()) {
3007 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3008 SmallVector<QualType, 16> Args(Proto->param_types());
3009 for (unsigned i = 0, n = Args.size(); i != n; ++i)
3010 Args[i] = removePtrSizeAddrSpace(Args[i]);
3011 return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
3014 if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
3015 QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
3016 return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
3022 bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
3023 return hasSameType(T, U) ||
3024 hasSameType(getFunctionTypeWithoutPtrSizes(T),
3025 getFunctionTypeWithoutPtrSizes(U));
3028 void ASTContext::adjustExceptionSpec(
3029 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
3033 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
3034 FD->setType(Updated);
3039 // Update the type in the type source information too.
3040 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
3041 // If the type and the type-as-written differ, we may need to update
3042 // the type-as-written too.
3043 if (TSInfo->getType() != FD->getType())
3044 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
3046 // FIXME: When we get proper type location information for exceptions,
3047 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
3048 // up the TypeSourceInfo;
3049 assert(TypeLoc::getFullDataSizeForType(Updated) ==
3050 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
3051 "TypeLoc size mismatch from updating exception specification");
3052 TSInfo->overrideType(Updated);
3056 /// getComplexType - Return the uniqued reference to the type for a complex
3057 /// number with the specified element type.
3058 QualType ASTContext::getComplexType(QualType T) const {
3059 // Unique pointers, to guarantee there is only one pointer of a particular
3061 llvm::FoldingSetNodeID ID;
3062 ComplexType::Profile(ID, T);
3064 void *InsertPos = nullptr;
3065 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
3066 return QualType(CT, 0);
3068 // If the pointee type isn't canonical, this won't be a canonical type either,
3069 // so fill in the canonical type field.
3071 if (!T.isCanonical()) {
3072 Canonical = getComplexType(getCanonicalType(T));
3074 // Get the new insert position for the node we care about.
3075 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
3076 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3078 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
3079 Types.push_back(New);
3080 ComplexTypes.InsertNode(New, InsertPos);
3081 return QualType(New, 0);
3084 /// getPointerType - Return the uniqued reference to the type for a pointer to
3085 /// the specified type.
3086 QualType ASTContext::getPointerType(QualType T) const {
3087 // Unique pointers, to guarantee there is only one pointer of a particular
3089 llvm::FoldingSetNodeID ID;
3090 PointerType::Profile(ID, T);
3092 void *InsertPos = nullptr;
3093 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3094 return QualType(PT, 0);
3096 // If the pointee type isn't canonical, this won't be a canonical type either,
3097 // so fill in the canonical type field.
3099 if (!T.isCanonical()) {
3100 Canonical = getPointerType(getCanonicalType(T));
3102 // Get the new insert position for the node we care about.
3103 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3104 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3106 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
3107 Types.push_back(New);
3108 PointerTypes.InsertNode(New, InsertPos);
3109 return QualType(New, 0);
3112 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
3113 llvm::FoldingSetNodeID ID;
3114 AdjustedType::Profile(ID, Orig, New);
3115 void *InsertPos = nullptr;
3116 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3118 return QualType(AT, 0);
3120 QualType Canonical = getCanonicalType(New);
3122 // Get the new insert position for the node we care about.
3123 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3124 assert(!AT && "Shouldn't be in the map!");
3126 AT = new (*this, TypeAlignment)
3127 AdjustedType(Type::Adjusted, Orig, New, Canonical);
3128 Types.push_back(AT);
3129 AdjustedTypes.InsertNode(AT, InsertPos);
3130 return QualType(AT, 0);
3133 QualType ASTContext::getDecayedType(QualType T) const {
3134 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
3139 // A declaration of a parameter as "array of type" shall be
3140 // adjusted to "qualified pointer to type", where the type
3141 // qualifiers (if any) are those specified within the [ and ] of
3142 // the array type derivation.
3143 if (T->isArrayType())
3144 Decayed = getArrayDecayedType(T);
3147 // A declaration of a parameter as "function returning type"
3148 // shall be adjusted to "pointer to function returning type", as
3150 if (T->isFunctionType())
3151 Decayed = getPointerType(T);
3153 llvm::FoldingSetNodeID ID;
3154 AdjustedType::Profile(ID, T, Decayed);
3155 void *InsertPos = nullptr;
3156 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3158 return QualType(AT, 0);
3160 QualType Canonical = getCanonicalType(Decayed);
3162 // Get the new insert position for the node we care about.
3163 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
3164 assert(!AT && "Shouldn't be in the map!");
3166 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
3167 Types.push_back(AT);
3168 AdjustedTypes.InsertNode(AT, InsertPos);
3169 return QualType(AT, 0);
3172 /// getBlockPointerType - Return the uniqued reference to the type for
3173 /// a pointer to the specified block.
3174 QualType ASTContext::getBlockPointerType(QualType T) const {
3175 assert(T->isFunctionType() && "block of function types only");
3176 // Unique pointers, to guarantee there is only one block of a particular
3178 llvm::FoldingSetNodeID ID;
3179 BlockPointerType::Profile(ID, T);
3181 void *InsertPos = nullptr;
3182 if (BlockPointerType *PT =
3183 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3184 return QualType(PT, 0);
3186 // If the block pointee type isn't canonical, this won't be a canonical
3187 // type either so fill in the canonical type field.
3189 if (!T.isCanonical()) {
3190 Canonical = getBlockPointerType(getCanonicalType(T));
3192 // Get the new insert position for the node we care about.
3193 BlockPointerType *NewIP =
3194 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3195 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3197 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
3198 Types.push_back(New);
3199 BlockPointerTypes.InsertNode(New, InsertPos);
3200 return QualType(New, 0);
3203 /// getLValueReferenceType - Return the uniqued reference to the type for an
3204 /// lvalue reference to the specified type.
3206 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
3207 assert(getCanonicalType(T) != OverloadTy &&
3208 "Unresolved overloaded function type");
3210 // Unique pointers, to guarantee there is only one pointer of a particular
3212 llvm::FoldingSetNodeID ID;
3213 ReferenceType::Profile(ID, T, SpelledAsLValue);
3215 void *InsertPos = nullptr;
3216 if (LValueReferenceType *RT =
3217 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3218 return QualType(RT, 0);
3220 const auto *InnerRef = T->getAs<ReferenceType>();
3222 // If the referencee type isn't canonical, this won't be a canonical type
3223 // either, so fill in the canonical type field.
3225 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
3226 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3227 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
3229 // Get the new insert position for the node we care about.
3230 LValueReferenceType *NewIP =
3231 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3232 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3235 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
3237 Types.push_back(New);
3238 LValueReferenceTypes.InsertNode(New, InsertPos);
3240 return QualType(New, 0);
3243 /// getRValueReferenceType - Return the uniqued reference to the type for an
3244 /// rvalue reference to the specified type.
3245 QualType ASTContext::getRValueReferenceType(QualType T) const {
3246 // Unique pointers, to guarantee there is only one pointer of a particular
3248 llvm::FoldingSetNodeID ID;
3249 ReferenceType::Profile(ID, T, false);
3251 void *InsertPos = nullptr;
3252 if (RValueReferenceType *RT =
3253 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
3254 return QualType(RT, 0);
3256 const auto *InnerRef = T->getAs<ReferenceType>();
3258 // If the referencee type isn't canonical, this won't be a canonical type
3259 // either, so fill in the canonical type field.
3261 if (InnerRef || !T.isCanonical()) {
3262 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
3263 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
3265 // Get the new insert position for the node we care about.
3266 RValueReferenceType *NewIP =
3267 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
3268 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3271 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
3272 Types.push_back(New);
3273 RValueReferenceTypes.InsertNode(New, InsertPos);
3274 return QualType(New, 0);
3277 /// getMemberPointerType - Return the uniqued reference to the type for a
3278 /// member pointer to the specified type, in the specified class.
3279 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
3280 // Unique pointers, to guarantee there is only one pointer of a particular
3282 llvm::FoldingSetNodeID ID;
3283 MemberPointerType::Profile(ID, T, Cls);
3285 void *InsertPos = nullptr;
3286 if (MemberPointerType *PT =
3287 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3288 return QualType(PT, 0);
3290 // If the pointee or class type isn't canonical, this won't be a canonical
3291 // type either, so fill in the canonical type field.
3293 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
3294 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
3296 // Get the new insert position for the node we care about.
3297 MemberPointerType *NewIP =
3298 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3299 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3301 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
3302 Types.push_back(New);
3303 MemberPointerTypes.InsertNode(New, InsertPos);
3304 return QualType(New, 0);
3307 /// getConstantArrayType - Return the unique reference to the type for an
3308 /// array of the specified element type.
3309 QualType ASTContext::getConstantArrayType(QualType EltTy,
3310 const llvm::APInt &ArySizeIn,
3311 const Expr *SizeExpr,
3312 ArrayType::ArraySizeModifier ASM,
3313 unsigned IndexTypeQuals) const {
3314 assert((EltTy->isDependentType() ||
3315 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
3316 "Constant array of VLAs is illegal!");
3318 // We only need the size as part of the type if it's instantiation-dependent.
3319 if (SizeExpr && !SizeExpr->isInstantiationDependent())
3322 // Convert the array size into a canonical width matching the pointer size for
3324 llvm::APInt ArySize(ArySizeIn);
3325 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
3327 llvm::FoldingSetNodeID ID;
3328 ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
3331 void *InsertPos = nullptr;
3332 if (ConstantArrayType *ATP =
3333 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
3334 return QualType(ATP, 0);
3336 // If the element type isn't canonical or has qualifiers, or the array bound
3337 // is instantiation-dependent, this won't be a canonical type either, so fill
3338 // in the canonical type field.
3340 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
3341 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3342 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
3343 ASM, IndexTypeQuals);
3344 Canon = getQualifiedType(Canon, canonSplit.Quals);
3346 // Get the new insert position for the node we care about.
3347 ConstantArrayType *NewIP =
3348 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
3349 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3352 void *Mem = Allocate(
3353 ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
3355 auto *New = new (Mem)
3356 ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
3357 ConstantArrayTypes.InsertNode(New, InsertPos);
3358 Types.push_back(New);
3359 return QualType(New, 0);
3362 /// getVariableArrayDecayedType - Turns the given type, which may be
3363 /// variably-modified, into the corresponding type with all the known
3364 /// sizes replaced with [*].
3365 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3366 // Vastly most common case.
3367 if (!type->isVariablyModifiedType()) return type;
3371 SplitQualType split = type.getSplitDesugaredType();
3372 const Type *ty = split.Ty;
3373 switch (ty->getTypeClass()) {
3374 #define TYPE(Class, Base)
3375 #define ABSTRACT_TYPE(Class, Base)
3376 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3377 #include "clang/AST/TypeNodes.inc"
3378 llvm_unreachable("didn't desugar past all non-canonical types?");
3380 // These types should never be variably-modified.
3384 case Type::DependentVector:
3385 case Type::ExtVector:
3386 case Type::DependentSizedExtVector:
3387 case Type::ConstantMatrix:
3388 case Type::DependentSizedMatrix:
3389 case Type::DependentAddressSpace:
3390 case Type::ObjCObject:
3391 case Type::ObjCInterface:
3392 case Type::ObjCObjectPointer:
3395 case Type::UnresolvedUsing:
3396 case Type::TypeOfExpr:
3398 case Type::Decltype:
3399 case Type::UnaryTransform:
3400 case Type::DependentName:
3401 case Type::InjectedClassName:
3402 case Type::TemplateSpecialization:
3403 case Type::DependentTemplateSpecialization:
3404 case Type::TemplateTypeParm:
3405 case Type::SubstTemplateTypeParmPack:
3407 case Type::DeducedTemplateSpecialization:
3408 case Type::PackExpansion:
3410 case Type::DependentExtInt:
3411 llvm_unreachable("type should never be variably-modified");
3413 // These types can be variably-modified but should never need to
3415 case Type::FunctionNoProto:
3416 case Type::FunctionProto:
3417 case Type::BlockPointer:
3418 case Type::MemberPointer:
3422 // These types can be variably-modified. All these modifications
3423 // preserve structure except as noted by comments.
3424 // TODO: if we ever care about optimizing VLAs, there are no-op
3425 // optimizations available here.
3427 result = getPointerType(getVariableArrayDecayedType(
3428 cast<PointerType>(ty)->getPointeeType()));
3431 case Type::LValueReference: {
3432 const auto *lv = cast<LValueReferenceType>(ty);
3433 result = getLValueReferenceType(
3434 getVariableArrayDecayedType(lv->getPointeeType()),
3435 lv->isSpelledAsLValue());
3439 case Type::RValueReference: {
3440 const auto *lv = cast<RValueReferenceType>(ty);
3441 result = getRValueReferenceType(
3442 getVariableArrayDecayedType(lv->getPointeeType()));
3446 case Type::Atomic: {
3447 const auto *at = cast<AtomicType>(ty);
3448 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3452 case Type::ConstantArray: {
3453 const auto *cat = cast<ConstantArrayType>(ty);
3454 result = getConstantArrayType(
3455 getVariableArrayDecayedType(cat->getElementType()),
3458 cat->getSizeModifier(),
3459 cat->getIndexTypeCVRQualifiers());
3463 case Type::DependentSizedArray: {
3464 const auto *dat = cast<DependentSizedArrayType>(ty);
3465 result = getDependentSizedArrayType(
3466 getVariableArrayDecayedType(dat->getElementType()),
3468 dat->getSizeModifier(),
3469 dat->getIndexTypeCVRQualifiers(),
3470 dat->getBracketsRange());
3474 // Turn incomplete types into [*] types.
3475 case Type::IncompleteArray: {
3476 const auto *iat = cast<IncompleteArrayType>(ty);
3477 result = getVariableArrayType(
3478 getVariableArrayDecayedType(iat->getElementType()),
3481 iat->getIndexTypeCVRQualifiers(),
3486 // Turn VLA types into [*] types.
3487 case Type::VariableArray: {
3488 const auto *vat = cast<VariableArrayType>(ty);
3489 result = getVariableArrayType(
3490 getVariableArrayDecayedType(vat->getElementType()),
3493 vat->getIndexTypeCVRQualifiers(),
3494 vat->getBracketsRange());
3499 // Apply the top-level qualifiers from the original.
3500 return getQualifiedType(result, split.Quals);
3503 /// getVariableArrayType - Returns a non-unique reference to the type for a
3504 /// variable array of the specified element type.
3505 QualType ASTContext::getVariableArrayType(QualType EltTy,
3507 ArrayType::ArraySizeModifier ASM,
3508 unsigned IndexTypeQuals,
3509 SourceRange Brackets) const {
3510 // Since we don't unique expressions, it isn't possible to unique VLA's
3511 // that have an expression provided for their size.
3514 // Be sure to pull qualifiers off the element type.
3515 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3516 SplitQualType canonSplit = getCanonicalType(EltTy).split();
3517 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
3518 IndexTypeQuals, Brackets);
3519 Canon = getQualifiedType(Canon, canonSplit.Quals);
3522 auto *New = new (*this, TypeAlignment)
3523 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
3525 VariableArrayTypes.push_back(New);
3526 Types.push_back(New);
3527 return QualType(New, 0);
3530 /// getDependentSizedArrayType - Returns a non-unique reference to
3531 /// the type for a dependently-sized array of the specified element
3533 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3535 ArrayType::ArraySizeModifier ASM,
3536 unsigned elementTypeQuals,
3537 SourceRange brackets) const {
3538 assert((!numElements || numElements->isTypeDependent() ||
3539 numElements->isValueDependent()) &&
3540 "Size must be type- or value-dependent!");
3542 // Dependently-sized array types that do not have a specified number
3543 // of elements will have their sizes deduced from a dependent
3544 // initializer. We do no canonicalization here at all, which is okay
3545 // because they can't be used in most locations.
3548 = new (*this, TypeAlignment)
3549 DependentSizedArrayType(*this, elementType, QualType(),
3550 numElements, ASM, elementTypeQuals,
3552 Types.push_back(newType);
3553 return QualType(newType, 0);
3556 // Otherwise, we actually build a new type every time, but we
3557 // also build a canonical type.
3559 SplitQualType canonElementType = getCanonicalType(elementType).split();
3561 void *insertPos = nullptr;
3562 llvm::FoldingSetNodeID ID;
3563 DependentSizedArrayType::Profile(ID, *this,
3564 QualType(canonElementType.Ty, 0),
3565 ASM, elementTypeQuals, numElements);
3567 // Look for an existing type with these properties.
3568 DependentSizedArrayType *canonTy =
3569 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3571 // If we don't have one, build one.
3573 canonTy = new (*this, TypeAlignment)
3574 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
3575 QualType(), numElements, ASM, elementTypeQuals,
3577 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3578 Types.push_back(canonTy);
3581 // Apply qualifiers from the element type to the array.
3582 QualType canon = getQualifiedType(QualType(canonTy,0),
3583 canonElementType.Quals);
3585 // If we didn't need extra canonicalization for the element type or the size
3586 // expression, then just use that as our result.
3587 if (QualType(canonElementType.Ty, 0) == elementType &&
3588 canonTy->getSizeExpr() == numElements)
3591 // Otherwise, we need to build a type which follows the spelling
3592 // of the element type.
3594 = new (*this, TypeAlignment)
3595 DependentSizedArrayType(*this, elementType, canon, numElements,
3596 ASM, elementTypeQuals, brackets);
3597 Types.push_back(sugaredType);
3598 return QualType(sugaredType, 0);
3601 QualType ASTContext::getIncompleteArrayType(QualType elementType,
3602 ArrayType::ArraySizeModifier ASM,
3603 unsigned elementTypeQuals) const {
3604 llvm::FoldingSetNodeID ID;
3605 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
3607 void *insertPos = nullptr;
3608 if (IncompleteArrayType *iat =
3609 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3610 return QualType(iat, 0);
3612 // If the element type isn't canonical, this won't be a canonical type
3613 // either, so fill in the canonical type field. We also have to pull
3614 // qualifiers off the element type.
3617 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3618 SplitQualType canonSplit = getCanonicalType(elementType).split();
3619 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
3620 ASM, elementTypeQuals);
3621 canon = getQualifiedType(canon, canonSplit.Quals);
3623 // Get the new insert position for the node we care about.
3624 IncompleteArrayType *existing =
3625 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3626 assert(!existing && "Shouldn't be in the map!"); (void) existing;
3629 auto *newType = new (*this, TypeAlignment)
3630 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
3632 IncompleteArrayTypes.InsertNode(newType, insertPos);
3633 Types.push_back(newType);
3634 return QualType(newType, 0);
3637 /// getScalableVectorType - Return the unique reference to a scalable vector
3638 /// type of the specified element type and size. VectorType must be a built-in
3640 QualType ASTContext::getScalableVectorType(QualType EltTy,
3641 unsigned NumElts) const {
3642 if (Target->hasAArch64SVETypes()) {
3643 uint64_t EltTySize = getTypeSize(EltTy);
3644 #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
3645 IsSigned, IsFP, IsBF) \
3646 if (!EltTy->isBooleanType() && \
3647 ((EltTy->hasIntegerRepresentation() && \
3648 EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
3649 (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
3651 (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
3652 IsBF && !IsFP)) && \
3653 EltTySize == ElBits && NumElts == NumEls) { \
3654 return SingletonId; \
3656 #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
3657 if (EltTy->isBooleanType() && NumElts == NumEls) \
3659 #include "clang/Basic/AArch64SVEACLETypes.def"
3664 /// getVectorType - Return the unique reference to a vector type of
3665 /// the specified element type and size. VectorType must be a built-in type.
3666 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
3667 VectorType::VectorKind VecKind) const {
3668 assert(vecType->isBuiltinType());
3670 // Check if we've already instantiated a vector of this type.
3671 llvm::FoldingSetNodeID ID;
3672 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
3674 void *InsertPos = nullptr;
3675 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3676 return QualType(VTP, 0);
3678 // If the element type isn't canonical, this won't be a canonical type either,
3679 // so fill in the canonical type field.
3681 if (!vecType.isCanonical()) {
3682 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
3684 // Get the new insert position for the node we care about.
3685 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3686 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3688 auto *New = new (*this, TypeAlignment)
3689 VectorType(vecType, NumElts, Canonical, VecKind);
3690 VectorTypes.InsertNode(New, InsertPos);
3691 Types.push_back(New);
3692 return QualType(New, 0);
3696 ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3697 SourceLocation AttrLoc,
3698 VectorType::VectorKind VecKind) const {
3699 llvm::FoldingSetNodeID ID;
3700 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3702 void *InsertPos = nullptr;
3703 DependentVectorType *Canon =
3704 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3705 DependentVectorType *New;
3708 New = new (*this, TypeAlignment) DependentVectorType(
3709 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3711 QualType CanonVecTy = getCanonicalType(VecType);
3712 if (CanonVecTy == VecType) {
3713 New = new (*this, TypeAlignment) DependentVectorType(
3714 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3716 DependentVectorType *CanonCheck =
3717 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3718 assert(!CanonCheck &&
3719 "Dependent-sized vector_size canonical type broken");
3721 DependentVectorTypes.InsertNode(New, InsertPos);
3723 QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
3724 SourceLocation(), VecKind);
3725 New = new (*this, TypeAlignment) DependentVectorType(
3726 *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
3730 Types.push_back(New);
3731 return QualType(New, 0);
3734 /// getExtVectorType - Return the unique reference to an extended vector type of
3735 /// the specified element type and size. VectorType must be a built-in type.
3737 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
3738 assert(vecType->isBuiltinType() || vecType->isDependentType());
3740 // Check if we've already instantiated a vector of this type.
3741 llvm::FoldingSetNodeID ID;
3742 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
3743 VectorType::GenericVector);
3744 void *InsertPos = nullptr;
3745 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3746 return QualType(VTP, 0);
3748 // If the element type isn't canonical, this won't be a canonical type either,
3749 // so fill in the canonical type field.
3751 if (!vecType.isCanonical()) {
3752 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
3754 // Get the new insert position for the node we care about.
3755 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3756 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3758 auto *New = new (*this, TypeAlignment)
3759 ExtVectorType(vecType, NumElts, Canonical);
3760 VectorTypes.InsertNode(New, InsertPos);
3761 Types.push_back(New);
3762 return QualType(New, 0);
3766 ASTContext::getDependentSizedExtVectorType(QualType vecType,
3768 SourceLocation AttrLoc) const {
3769 llvm::FoldingSetNodeID ID;
3770 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
3773 void *InsertPos = nullptr;
3774 DependentSizedExtVectorType *Canon
3775 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3776 DependentSizedExtVectorType *New;
3778 // We already have a canonical version of this array type; use it as
3779 // the canonical type for a newly-built type.
3780 New = new (*this, TypeAlignment)
3781 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3784 QualType CanonVecTy = getCanonicalType(vecType);
3785 if (CanonVecTy == vecType) {
3786 New = new (*this, TypeAlignment)
3787 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3790 DependentSizedExtVectorType *CanonCheck
3791 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3792 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3794 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3796 QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3798 New = new (*this, TypeAlignment) DependentSizedExtVectorType(
3799 *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
3803 Types.push_back(New);
3804 return QualType(New, 0);
3807 QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
3808 unsigned NumColumns) const {
3809 llvm::FoldingSetNodeID ID;
3810 ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
3811 Type::ConstantMatrix);
3813 assert(MatrixType::isValidElementType(ElementTy) &&
3814 "need a valid element type");
3815 assert(ConstantMatrixType::isDimensionValid(NumRows) &&
3816 ConstantMatrixType::isDimensionValid(NumColumns) &&
3817 "need valid matrix dimensions");
3818 void *InsertPos = nullptr;
3819 if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
3820 return QualType(MTP, 0);
3823 if (!ElementTy.isCanonical()) {
3825 getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
3827 ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
3828 assert(!NewIP && "Matrix type shouldn't already exist in the map");
3832 auto *New = new (*this, TypeAlignment)
3833 ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
3834 MatrixTypes.InsertNode(New, InsertPos);
3835 Types.push_back(New);
3836 return QualType(New, 0);
3839 QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
3842 SourceLocation AttrLoc) const {
3843 QualType CanonElementTy = getCanonicalType(ElementTy);
3844 llvm::FoldingSetNodeID ID;
3845 DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
3848 void *InsertPos = nullptr;
3849 DependentSizedMatrixType *Canon =
3850 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
3853 Canon = new (*this, TypeAlignment) DependentSizedMatrixType(
3854 *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc);
3856 DependentSizedMatrixType *CanonCheck =
3857 DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
3858 assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
3860 DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
3861 Types.push_back(Canon);
3864 // Already have a canonical version of the matrix type
3866 // If it exactly matches the requested type, use it directly.
3867 if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
3868 Canon->getRowExpr() == ColumnExpr)
3869 return QualType(Canon, 0);
3871 // Use Canon as the canonical type for newly-built type.
3872 DependentSizedMatrixType *New = new (*this, TypeAlignment)
3873 DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr,
3874 ColumnExpr, AttrLoc);
3875 Types.push_back(New);
3876 return QualType(New, 0);
3879 QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3880 Expr *AddrSpaceExpr,
3881 SourceLocation AttrLoc) const {
3882 assert(AddrSpaceExpr->isInstantiationDependent());
3884 QualType canonPointeeType = getCanonicalType(PointeeType);
3886 void *insertPos = nullptr;
3887 llvm::FoldingSetNodeID ID;
3888 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3891 DependentAddressSpaceType *canonTy =
3892 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3895 canonTy = new (*this, TypeAlignment)
3896 DependentAddressSpaceType(*this, canonPointeeType,
3897 QualType(), AddrSpaceExpr, AttrLoc);
3898 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3899 Types.push_back(canonTy);
3902 if (canonPointeeType == PointeeType &&
3903 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
3904 return QualType(canonTy, 0);
3907 = new (*this, TypeAlignment)
3908 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
3909 AddrSpaceExpr, AttrLoc);
3910 Types.push_back(sugaredType);
3911 return QualType(sugaredType, 0);
3914 /// Determine whether \p T is canonical as the result type of a function.
3915 static bool isCanonicalResultType(QualType T) {
3916 return T.isCanonical() &&
3917 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3918 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3921 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
3923 ASTContext::getFunctionNoProtoType(QualType ResultTy,
3924 const FunctionType::ExtInfo &Info) const {
3925 // Unique functions, to guarantee there is only one function of a particular
3927 llvm::FoldingSetNodeID ID;
3928 FunctionNoProtoType::Profile(ID, ResultTy, Info);
3930 void *InsertPos = nullptr;
3931 if (FunctionNoProtoType *FT =
3932 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3933 return QualType(FT, 0);
3936 if (!isCanonicalResultType(ResultTy)) {
3938 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
3940 // Get the new insert position for the node we care about.
3941 FunctionNoProtoType *NewIP =
3942 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3943 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3946 auto *New = new (*this, TypeAlignment)
3947 FunctionNoProtoType(ResultTy, Canonical, Info);
3948 Types.push_back(New);
3949 FunctionNoProtoTypes.InsertNode(New, InsertPos);
3950 return QualType(New, 0);
3954 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3955 CanQualType CanResultType = getCanonicalType(ResultType);
3957 // Canonical result types do not have ARC lifetime qualifiers.
3958 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3959 Qualifiers Qs = CanResultType.getQualifiers();
3960 Qs.removeObjCLifetime();
3961 return CanQualType::CreateUnsafe(
3962 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3965 return CanResultType;
3968 static bool isCanonicalExceptionSpecification(
3969 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3970 if (ESI.Type == EST_None)
3972 if (!NoexceptInType)
3975 // C++17 onwards: exception specification is part of the type, as a simple
3976 // boolean "can this function type throw".
3977 if (ESI.Type == EST_BasicNoexcept)
3980 // A noexcept(expr) specification is (possibly) canonical if expr is
3982 if (ESI.Type == EST_DependentNoexcept)
3985 // A dynamic exception specification is canonical if it only contains pack
3986 // expansions (so we can't tell whether it's non-throwing) and all its
3987 // contained types are canonical.
3988 if (ESI.Type == EST_Dynamic) {
3989 bool AnyPackExpansions = false;
3990 for (QualType ET : ESI.Exceptions) {
3991 if (!ET.isCanonical())
3993 if (ET->getAs<PackExpansionType>())
3994 AnyPackExpansions = true;
3996 return AnyPackExpansions;
4002 QualType ASTContext::getFunctionTypeInternal(
4003 QualType ResultTy, ArrayRef<QualType> ArgArray,
4004 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
4005 size_t NumArgs = ArgArray.size();
4007 // Unique functions, to guarantee there is only one function of a particular
4009 llvm::FoldingSetNodeID ID;
4010 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
4014 bool Unique = false;
4016 void *InsertPos = nullptr;
4017 if (FunctionProtoType *FPT =
4018 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
4019 QualType Existing = QualType(FPT, 0);
4021 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
4022 // it so long as our exception specification doesn't contain a dependent
4023 // noexcept expression, or we're just looking for a canonical type.
4024 // Otherwise, we're going to need to create a type
4025 // sugar node to hold the concrete expression.
4026 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
4027 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
4030 // We need a new type sugar node for this one, to hold the new noexcept
4031 // expression. We do no canonicalization here, but that's OK since we don't
4032 // expect to see the same noexcept expression much more than once.
4033 Canonical = getCanonicalType(Existing);
4037 bool NoexceptInType = getLangOpts().CPlusPlus17;
4038 bool IsCanonicalExceptionSpec =
4039 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
4041 // Determine whether the type being created is already canonical or not.
4042 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
4043 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
4044 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
4045 if (!ArgArray[i].isCanonicalAsParam())
4046 isCanonical = false;
4048 if (OnlyWantCanonical)
4049 assert(isCanonical &&
4050 "given non-canonical parameters constructing canonical type");
4052 // If this type isn't canonical, get the canonical version of it if we don't
4053 // already have it. The exception spec is only partially part of the
4054 // canonical type, and only in C++17 onwards.
4055 if (!isCanonical && Canonical.isNull()) {
4056 SmallVector<QualType, 16> CanonicalArgs;
4057 CanonicalArgs.reserve(NumArgs);
4058 for (unsigned i = 0; i != NumArgs; ++i)
4059 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
4061 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
4062 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
4063 CanonicalEPI.HasTrailingReturn = false;
4065 if (IsCanonicalExceptionSpec) {
4066 // Exception spec is already OK.
4067 } else if (NoexceptInType) {
4068 switch (EPI.ExceptionSpec.Type) {
4069 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
4070 // We don't know yet. It shouldn't matter what we pick here; no-one
4071 // should ever look at this.
4073 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
4074 CanonicalEPI.ExceptionSpec.Type = EST_None;
4077 // A dynamic exception specification is almost always "not noexcept",
4078 // with the exception that a pack expansion might expand to no types.
4080 bool AnyPacks = false;
4081 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
4082 if (ET->getAs<PackExpansionType>())
4084 ExceptionTypeStorage.push_back(getCanonicalType(ET));
4087 CanonicalEPI.ExceptionSpec.Type = EST_None;
4089 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
4090 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
4095 case EST_DynamicNone:
4096 case EST_BasicNoexcept:
4097 case EST_NoexceptTrue:
4099 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
4102 case EST_DependentNoexcept:
4103 llvm_unreachable("dependent noexcept is already canonical");
4106 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
4109 // Adjust the canonical function result type.
4110 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
4112 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
4114 // Get the new insert position for the node we care about.
4115 FunctionProtoType *NewIP =
4116 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
4117 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4120 // Compute the needed size to hold this FunctionProtoType and the
4121 // various trailing objects.
4122 auto ESH = FunctionProtoType::getExceptionSpecSize(
4123 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
4124 size_t Size = FunctionProtoType::totalSizeToAlloc<
4125 QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
4126 FunctionType::ExceptionType, Expr *, FunctionDecl *,
4127 FunctionProtoType::ExtParameterInfo, Qualifiers>(
4128 NumArgs, EPI.Variadic,
4129 FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
4130 ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
4131 EPI.ExtParameterInfos ? NumArgs : 0,
4132 EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
4134 auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
4135 FunctionProtoType::ExtProtoInfo newEPI = EPI;
4136 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
4137 Types.push_back(FTP);
4139 FunctionProtoTypes.InsertNode(FTP, InsertPos);
4140 return QualType(FTP, 0);
4143 QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
4144 llvm::FoldingSetNodeID ID;
4145 PipeType::Profile(ID, T, ReadOnly);
4147 void *InsertPos = nullptr;
4148 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
4149 return QualType(PT, 0);
4151 // If the pipe element type isn't canonical, this won't be a canonical type
4152 // either, so fill in the canonical type field.
4154 if (!T.isCanonical()) {
4155 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
4157 // Get the new insert position for the node we care about.
4158 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
4159 assert(!NewIP && "Shouldn't be in the map!");
4162 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
4163 Types.push_back(New);
4164 PipeTypes.InsertNode(New, InsertPos);
4165 return QualType(New, 0);
4168 QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
4169 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
4170 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
4174 QualType ASTContext::getReadPipeType(QualType T) const {
4175 return getPipeType(T, true);
4178 QualType ASTContext::getWritePipeType(QualType T) const {
4179 return getPipeType(T, false);
4182 QualType ASTContext::getExtIntType(bool IsUnsigned, unsigned NumBits) const {
4183 llvm::FoldingSetNodeID ID;
4184 ExtIntType::Profile(ID, IsUnsigned, NumBits);
4186 void *InsertPos = nullptr;
4187 if (ExtIntType *EIT = ExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4188 return QualType(EIT, 0);
4190 auto *New = new (*this, TypeAlignment) ExtIntType(IsUnsigned, NumBits);
4191 ExtIntTypes.InsertNode(New, InsertPos);
4192 Types.push_back(New);
4193 return QualType(New, 0);
4196 QualType ASTContext::getDependentExtIntType(bool IsUnsigned,
4197 Expr *NumBitsExpr) const {
4198 assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
4199 llvm::FoldingSetNodeID ID;
4200 DependentExtIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
4202 void *InsertPos = nullptr;
4203 if (DependentExtIntType *Existing =
4204 DependentExtIntTypes.FindNodeOrInsertPos(ID, InsertPos))
4205 return QualType(Existing, 0);
4207 auto *New = new (*this, TypeAlignment)
4208 DependentExtIntType(*this, IsUnsigned, NumBitsExpr);
4209 DependentExtIntTypes.InsertNode(New, InsertPos);
4211 Types.push_back(New);
4212 return QualType(New, 0);
4216 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
4217 if (!isa<CXXRecordDecl>(D)) return false;
4218 const auto *RD = cast<CXXRecordDecl>(D);
4219 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
4221 if (RD->getDescribedClassTemplate() &&
4222 !isa<ClassTemplateSpecializationDecl>(RD))
4228 /// getInjectedClassNameType - Return the unique reference to the
4229 /// injected class name type for the specified templated declaration.
4230 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
4231 QualType TST) const {
4232 assert(NeedsInjectedClassNameType(Decl));
4233 if (Decl->TypeForDecl) {
4234 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4235 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
4236 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
4237 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4238 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
4241 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
4242 Decl->TypeForDecl = newType;
4243 Types.push_back(newType);
4245 return QualType(Decl->TypeForDecl, 0);
4248 /// getTypeDeclType - Return the unique reference to the type for the
4249 /// specified type declaration.
4250 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
4251 assert(Decl && "Passed null for Decl param");
4252 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
4254 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
4255 return getTypedefType(Typedef);
4257 assert(!isa<TemplateTypeParmDecl>(Decl) &&
4258 "Template type parameter types are always available.");
4260 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
4261 assert(Record->isFirstDecl() && "struct/union has previous declaration");
4262 assert(!NeedsInjectedClassNameType(Record));
4263 return getRecordType(Record);
4264 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
4265 assert(Enum->isFirstDecl() && "enum has previous declaration");
4266 return getEnumType(Enum);
4267 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
4268 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
4269 Decl->TypeForDecl = newType;
4270 Types.push_back(newType);
4272 llvm_unreachable("TypeDecl without a type?");
4274 return QualType(Decl->TypeForDecl, 0);
4277 /// getTypedefType - Return the unique reference to the type for the
4278 /// specified typedef name decl.
4280 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
4281 QualType Canonical) const {
4282 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4284 if (Canonical.isNull())
4285 Canonical = getCanonicalType(Decl->getUnderlyingType());
4286 auto *newType = new (*this, TypeAlignment)
4287 TypedefType(Type::Typedef, Decl, Canonical);
4288 Decl->TypeForDecl = newType;
4289 Types.push_back(newType);
4290 return QualType(newType, 0);
4293 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
4294 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4296 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
4297 if (PrevDecl->TypeForDecl)
4298 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4300 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
4301 Decl->TypeForDecl = newType;
4302 Types.push_back(newType);
4303 return QualType(newType, 0);
4306 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
4307 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
4309 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
4310 if (PrevDecl->TypeForDecl)
4311 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
4313 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
4314 Decl->TypeForDecl = newType;
4315 Types.push_back(newType);
4316 return QualType(newType, 0);
4319 QualType ASTContext::getAttributedType(attr::Kind attrKind,
4320 QualType modifiedType,
4321 QualType equivalentType) {
4322 llvm::FoldingSetNodeID id;
4323 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
4325 void *insertPos = nullptr;
4326 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
4327 if (type) return QualType(type, 0);
4329 QualType canon = getCanonicalType(equivalentType);
4330 type = new (*this, TypeAlignment)
4331 AttributedType(canon, attrKind, modifiedType, equivalentType);
4333 Types.push_back(type);
4334 AttributedTypes.InsertNode(type, insertPos);
4336 return QualType(type, 0);
4339 /// Retrieve a substitution-result type.
4341 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
4342 QualType Replacement) const {
4343 assert(Replacement.isCanonical()
4344 && "replacement types must always be canonical");
4346 llvm::FoldingSetNodeID ID;
4347 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
4348 void *InsertPos = nullptr;
4349 SubstTemplateTypeParmType *SubstParm
4350 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4353 SubstParm = new (*this, TypeAlignment)
4354 SubstTemplateTypeParmType(Parm, Replacement);
4355 Types.push_back(SubstParm);
4356 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
4359 return QualType(SubstParm, 0);
4363 QualType ASTContext::getSubstTemplateTypeParmPackType(
4364 const TemplateTypeParmType *Parm,
4365 const TemplateArgument &ArgPack) {
4367 for (const auto &P : ArgPack.pack_elements()) {
4368 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
4369 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
4373 llvm::FoldingSetNodeID ID;
4374 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
4375 void *InsertPos = nullptr;
4376 if (SubstTemplateTypeParmPackType *SubstParm
4377 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
4378 return QualType(SubstParm, 0);
4381 if (!Parm->isCanonicalUnqualified()) {
4382 Canon = getCanonicalType(QualType(Parm, 0));
4383 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
4385 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
4389 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
4391 Types.push_back(SubstParm);
4392 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
4393 return QualType(SubstParm, 0);
4396 /// Retrieve the template type parameter type for a template
4397 /// parameter or parameter pack with the given depth, index, and (optionally)
4399 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
4401 TemplateTypeParmDecl *TTPDecl) const {
4402 llvm::FoldingSetNodeID ID;
4403 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
4404 void *InsertPos = nullptr;
4405 TemplateTypeParmType *TypeParm
4406 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4409 return QualType(TypeParm, 0);
4412 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
4413 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
4415 TemplateTypeParmType *TypeCheck
4416 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
4417 assert(!TypeCheck && "Template type parameter canonical type broken");
4420 TypeParm = new (*this, TypeAlignment)
4421 TemplateTypeParmType(Depth, Index, ParameterPack);
4423 Types.push_back(TypeParm);
4424 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
4426 return QualType(TypeParm, 0);
4430 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
4431 SourceLocation NameLoc,
4432 const TemplateArgumentListInfo &Args,
4433 QualType Underlying) const {
4434 assert(!Name.getAsDependentTemplateName() &&
4435 "No dependent template names here!");
4436 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
4438 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
4439 TemplateSpecializationTypeLoc TL =
4440 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
4441 TL.setTemplateKeywordLoc(SourceLocation());
4442 TL.setTemplateNameLoc(NameLoc);
4443 TL.setLAngleLoc(Args.getLAngleLoc());
4444 TL.setRAngleLoc(Args.getRAngleLoc());
4445 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4446 TL.setArgLocInfo(i, Args[i].getLocInfo());
4451 ASTContext::getTemplateSpecializationType(TemplateName Template,
4452 const TemplateArgumentListInfo &Args,
4453 QualType Underlying) const {
4454 assert(!Template.getAsDependentTemplateName() &&
4455 "No dependent template names here!");
4457 SmallVector<TemplateArgument, 4> ArgVec;
4458 ArgVec.reserve(Args.size());
4459 for (const TemplateArgumentLoc &Arg : Args.arguments())
4460 ArgVec.push_back(Arg.getArgument());
4462 return getTemplateSpecializationType(Template, ArgVec, Underlying);
4466 static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4467 for (const TemplateArgument &Arg : Args)
4468 if (Arg.isPackExpansion())
4476 ASTContext::getTemplateSpecializationType(TemplateName Template,
4477 ArrayRef<TemplateArgument> Args,
4478 QualType Underlying) const {
4479 assert(!Template.getAsDependentTemplateName() &&
4480 "No dependent template names here!");
4481 // Look through qualified template names.
4482 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4483 Template = TemplateName(QTN->getTemplateDecl());
4486 Template.getAsTemplateDecl() &&
4487 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
4489 if (!Underlying.isNull())
4490 CanonType = getCanonicalType(Underlying);
4492 // We can get here with an alias template when the specialization contains
4493 // a pack expansion that does not match up with a parameter pack.
4494 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
4495 "Caller must compute aliased type");
4496 IsTypeAlias = false;
4497 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
4500 // Allocate the (non-canonical) template specialization type, but don't
4501 // try to unique it: these types typically have location information that
4502 // we don't unique and don't want to lose.
4503 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
4504 sizeof(TemplateArgument) * Args.size() +
4505 (IsTypeAlias? sizeof(QualType) : 0),
4508 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
4509 IsTypeAlias ? Underlying : QualType());
4511 Types.push_back(Spec);
4512 return QualType(Spec, 0);
4515 QualType ASTContext::getCanonicalTemplateSpecializationType(
4516 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
4517 assert(!Template.getAsDependentTemplateName() &&
4518 "No dependent template names here!");
4520 // Look through qualified template names.
4521 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4522 Template = TemplateName(QTN->getTemplateDecl());
4524 // Build the canonical template specialization type.
4525 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
4526 SmallVector<TemplateArgument, 4> CanonArgs;
4527 unsigned NumArgs = Args.size();
4528 CanonArgs.reserve(NumArgs);
4529 for (const TemplateArgument &Arg : Args)
4530 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
4532 // Determine whether this canonical template specialization type already
4534 llvm::FoldingSetNodeID ID;
4535 TemplateSpecializationType::Profile(ID, CanonTemplate,
4538 void *InsertPos = nullptr;
4539 TemplateSpecializationType *Spec
4540 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4543 // Allocate a new canonical template specialization type.
4544 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4545 sizeof(TemplateArgument) * NumArgs),
4547 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
4549 QualType(), QualType());
4550 Types.push_back(Spec);
4551 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4554 assert(Spec->isDependentType() &&
4555 "Non-dependent template-id type must have a canonical type");
4556 return QualType(Spec, 0);
4559 QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4560 NestedNameSpecifier *NNS,
4562 TagDecl *OwnedTagDecl) const {
4563 llvm::FoldingSetNodeID ID;
4564 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
4566 void *InsertPos = nullptr;
4567 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4569 return QualType(T, 0);
4571 QualType Canon = NamedType;
4572 if (!Canon.isCanonical()) {
4573 Canon = getCanonicalType(NamedType);
4574 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4575 assert(!CheckT && "Elaborated canonical type broken");
4579 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4581 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4584 ElaboratedTypes.InsertNode(T, InsertPos);
4585 return QualType(T, 0);
4589 ASTContext::getParenType(QualType InnerType) const {
4590 llvm::FoldingSetNodeID ID;
4591 ParenType::Profile(ID, InnerType);
4593 void *InsertPos = nullptr;
4594 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4596 return QualType(T, 0);
4598 QualType Canon = InnerType;
4599 if (!Canon.isCanonical()) {
4600 Canon = getCanonicalType(InnerType);
4601 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4602 assert(!CheckT && "Paren canonical type broken");
4606 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
4608 ParenTypes.InsertNode(T, InsertPos);
4609 return QualType(T, 0);
4613 ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
4614 const IdentifierInfo *MacroII) const {
4615 QualType Canon = UnderlyingTy;
4616 if (!Canon.isCanonical())
4617 Canon = getCanonicalType(UnderlyingTy);
4619 auto *newType = new (*this, TypeAlignment)
4620 MacroQualifiedType(UnderlyingTy, Canon, MacroII);
4621 Types.push_back(newType);
4622 return QualType(newType, 0);
4625 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4626 NestedNameSpecifier *NNS,
4627 const IdentifierInfo *Name,
4628 QualType Canon) const {
4629 if (Canon.isNull()) {
4630 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4631 if (CanonNNS != NNS)
4632 Canon = getDependentNameType(Keyword, CanonNNS, Name);
4635 llvm::FoldingSetNodeID ID;
4636 DependentNameType::Profile(ID, Keyword, NNS, Name);
4638 void *InsertPos = nullptr;
4639 DependentNameType *T
4640 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
4642 return QualType(T, 0);
4644 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
4646 DependentNameTypes.InsertNode(T, InsertPos);
4647 return QualType(T, 0);
4651 ASTContext::getDependentTemplateSpecializationType(
4652 ElaboratedTypeKeyword Keyword,
4653 NestedNameSpecifier *NNS,
4654 const IdentifierInfo *Name,
4655 const TemplateArgumentListInfo &Args) const {
4656 // TODO: avoid this copy
4657 SmallVector<TemplateArgument, 16> ArgCopy;
4658 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4659 ArgCopy.push_back(Args[I].getArgument());
4660 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
4664 ASTContext::getDependentTemplateSpecializationType(
4665 ElaboratedTypeKeyword Keyword,
4666 NestedNameSpecifier *NNS,
4667 const IdentifierInfo *Name,
4668 ArrayRef<TemplateArgument> Args) const {
4669 assert((!NNS || NNS->isDependent()) &&
4670 "nested-name-specifier must be dependent");
4672 llvm::FoldingSetNodeID ID;
4673 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
4676 void *InsertPos = nullptr;
4677 DependentTemplateSpecializationType *T
4678 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4680 return QualType(T, 0);
4682 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4684 ElaboratedTypeKeyword CanonKeyword = Keyword;
4685 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4687 bool AnyNonCanonArgs = false;
4688 unsigned NumArgs = Args.size();
4689 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
4690 for (unsigned I = 0; I != NumArgs; ++I) {
4691 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4692 if (!CanonArgs[I].structurallyEquals(Args[I]))
4693 AnyNonCanonArgs = true;
4697 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4698 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
4702 // Find the insert position again.
4703 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4706 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4707 sizeof(TemplateArgument) * NumArgs),
4709 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
4712 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
4713 return QualType(T, 0);
4716 TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4717 TemplateArgument Arg;
4718 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4719 QualType ArgType = getTypeDeclType(TTP);
4720 if (TTP->isParameterPack())
4721 ArgType = getPackExpansionType(ArgType, None);
4723 Arg = TemplateArgument(ArgType);
4724 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4725 Expr *E = new (*this) DeclRefExpr(
4726 *this, NTTP, /*enclosing*/ false,
4727 NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this),
4728 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4730 if (NTTP->isParameterPack())
4731 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4733 Arg = TemplateArgument(E);
4735 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4736 if (TTP->isParameterPack())
4737 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4739 Arg = TemplateArgument(TemplateName(TTP));
4742 if (Param->isTemplateParameterPack())
4743 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4749 ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4750 SmallVectorImpl<TemplateArgument> &Args) {
4751 Args.reserve(Args.size() + Params->size());
4753 for (NamedDecl *Param : *Params)
4754 Args.push_back(getInjectedTemplateArg(Param));
4757 QualType ASTContext::getPackExpansionType(QualType Pattern,
4758 Optional<unsigned> NumExpansions) {
4759 llvm::FoldingSetNodeID ID;
4760 PackExpansionType::Profile(ID, Pattern, NumExpansions);
4762 // A deduced type can deduce to a pack, eg
4763 // auto ...x = some_pack;
4764 // That declaration isn't (yet) valid, but is created as part of building an
4765 // init-capture pack:
4766 // [...x = some_pack] {}
4767 assert((Pattern->containsUnexpandedParameterPack() ||
4768 Pattern->getContainedDeducedType()) &&
4769 "Pack expansions must expand one or more parameter packs");
4770 void *InsertPos = nullptr;
4771 PackExpansionType *T
4772 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4774 return QualType(T, 0);
4777 if (!Pattern.isCanonical()) {
4778 Canon = getCanonicalType(Pattern);
4779 // The canonical type might not contain an unexpanded parameter pack, if it
4780 // contains an alias template specialization which ignores one of its
4782 if (Canon->containsUnexpandedParameterPack()) {
4783 Canon = getPackExpansionType(Canon, NumExpansions);
4785 // Find the insert position again, in case we inserted an element into
4786 // PackExpansionTypes and invalidated our insert position.
4787 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4791 T = new (*this, TypeAlignment)
4792 PackExpansionType(Pattern, Canon, NumExpansions);
4794 PackExpansionTypes.InsertNode(T, InsertPos);
4795 return QualType(T, 0);
4798 /// CmpProtocolNames - Comparison predicate for sorting protocols
4800 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4801 ObjCProtocolDecl *const *RHS) {
4802 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
4805 static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4806 if (Protocols.empty()) return true;
4808 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4811 for (unsigned i = 1; i != Protocols.size(); ++i)
4812 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
4813 Protocols[i]->getCanonicalDecl() != Protocols[i])
4819 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
4820 // Sort protocols, keyed by name.
4821 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
4824 for (ObjCProtocolDecl *&P : Protocols)
4825 P = P->getCanonicalDecl();
4827 // Remove duplicates.
4828 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4829 Protocols.erase(ProtocolsEnd, Protocols.end());
4832 QualType ASTContext::getObjCObjectType(QualType BaseType,
4833 ObjCProtocolDecl * const *Protocols,
4834 unsigned NumProtocols) const {
4835 return getObjCObjectType(BaseType, {},
4836 llvm::makeArrayRef(Protocols, NumProtocols),
4837 /*isKindOf=*/false);
4840 QualType ASTContext::getObjCObjectType(
4842 ArrayRef<QualType> typeArgs,
4843 ArrayRef<ObjCProtocolDecl *> protocols,
4844 bool isKindOf) const {
4845 // If the base type is an interface and there aren't any protocols or
4846 // type arguments to add, then the interface type will do just fine.
4847 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4848 isa<ObjCInterfaceType>(baseType))
4851 // Look in the folding set for an existing type.
4852 llvm::FoldingSetNodeID ID;
4853 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
4854 void *InsertPos = nullptr;
4855 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4856 return QualType(QT, 0);
4858 // Determine the type arguments to be used for canonicalization,
4859 // which may be explicitly specified here or written on the base
4861 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4862 if (effectiveTypeArgs.empty()) {
4863 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
4864 effectiveTypeArgs = baseObject->getTypeArgs();
4867 // Build the canonical type, which has the canonical base type and a
4868 // sorted-and-uniqued list of protocols and the type arguments
4871 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4872 effectiveTypeArgs.end(),
4873 [&](QualType type) {
4874 return type.isCanonical();
4876 bool protocolsSorted = areSortedAndUniqued(protocols);
4877 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4878 // Determine the canonical type arguments.
4879 ArrayRef<QualType> canonTypeArgs;
4880 SmallVector<QualType, 4> canonTypeArgsVec;
4881 if (!typeArgsAreCanonical) {
4882 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4883 for (auto typeArg : effectiveTypeArgs)
4884 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4885 canonTypeArgs = canonTypeArgsVec;
4887 canonTypeArgs = effectiveTypeArgs;
4890 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4891 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4892 if (!protocolsSorted) {
4893 canonProtocolsVec.append(protocols.begin(), protocols.end());
4894 SortAndUniqueProtocols(canonProtocolsVec);
4895 canonProtocols = canonProtocolsVec;
4897 canonProtocols = protocols;
4900 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
4901 canonProtocols, isKindOf);
4903 // Regenerate InsertPos.
4904 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4907 unsigned size = sizeof(ObjCObjectTypeImpl);
4908 size += typeArgs.size() * sizeof(QualType);
4909 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4910 void *mem = Allocate(size, TypeAlignment);
4912 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4916 ObjCObjectTypes.InsertNode(T, InsertPos);
4917 return QualType(T, 0);
4920 /// Apply Objective-C protocol qualifiers to the given type.
4921 /// If this is for the canonical type of a type parameter, we can apply
4922 /// protocol qualifiers on the ObjCObjectPointerType.
4924 ASTContext::applyObjCProtocolQualifiers(QualType type,
4925 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4926 bool allowOnPointerType) const {
4929 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4930 return getObjCTypeParamType(objT->getDecl(), protocols);
4933 // Apply protocol qualifiers to ObjCObjectPointerType.
4934 if (allowOnPointerType) {
4935 if (const auto *objPtr =
4936 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4937 const ObjCObjectType *objT = objPtr->getObjectType();
4938 // Merge protocol lists and construct ObjCObjectType.
4939 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4940 protocolsVec.append(objT->qual_begin(),
4942 protocolsVec.append(protocols.begin(), protocols.end());
4943 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4944 type = getObjCObjectType(
4945 objT->getBaseType(),
4946 objT->getTypeArgsAsWritten(),
4948 objT->isKindOfTypeAsWritten());
4949 return getObjCObjectPointerType(type);
4953 // Apply protocol qualifiers to ObjCObjectType.
4954 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4955 // FIXME: Check for protocols to which the class type is already
4956 // known to conform.
4958 return getObjCObjectType(objT->getBaseType(),
4959 objT->getTypeArgsAsWritten(),
4961 objT->isKindOfTypeAsWritten());
4964 // If the canonical type is ObjCObjectType, ...
4965 if (type->isObjCObjectType()) {
4966 // Silently overwrite any existing protocol qualifiers.
4967 // TODO: determine whether that's the right thing to do.
4969 // FIXME: Check for protocols to which the class type is already
4970 // known to conform.
4971 return getObjCObjectType(type, {}, protocols, false);
4974 // id<protocol-list>
4975 if (type->isObjCIdType()) {
4976 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
4977 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
4978 objPtr->isKindOfType());
4979 return getObjCObjectPointerType(type);
4982 // Class<protocol-list>
4983 if (type->isObjCClassType()) {
4984 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
4985 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
4986 objPtr->isKindOfType());
4987 return getObjCObjectPointerType(type);
4995 ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4996 ArrayRef<ObjCProtocolDecl *> protocols) const {
4997 // Look in the folding set for an existing type.
4998 llvm::FoldingSetNodeID ID;
4999 ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
5000 void *InsertPos = nullptr;
5001 if (ObjCTypeParamType *TypeParam =
5002 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
5003 return QualType(TypeParam, 0);
5005 // We canonicalize to the underlying type.
5006 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
5007 if (!protocols.empty()) {
5008 // Apply the protocol qualifers.
5010 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
5011 Canonical, protocols, hasError, true /*allowOnPointerType*/));
5012 assert(!hasError && "Error when apply protocol qualifier to bound type");
5015 unsigned size = sizeof(ObjCTypeParamType);
5016 size += protocols.size() * sizeof(ObjCProtocolDecl *);
5017 void *mem = Allocate(size, TypeAlignment);
5018 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
5020 Types.push_back(newType);
5021 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
5022 return QualType(newType, 0);
5025 void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
5026 ObjCTypeParamDecl *New) const {
5027 New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
5028 // Update TypeForDecl after updating TypeSourceInfo.
5029 auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
5030 SmallVector<ObjCProtocolDecl *, 8> protocols;
5031 protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
5032 QualType UpdatedTy = getObjCTypeParamType(New, protocols);
5033 New->setTypeForDecl(UpdatedTy.getTypePtr());
5036 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
5037 /// protocol list adopt all protocols in QT's qualified-id protocol
5039 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
5040 ObjCInterfaceDecl *IC) {
5041 if (!QT->isObjCQualifiedIdType())
5044 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
5045 // If both the right and left sides have qualifiers.
5046 for (auto *Proto : OPT->quals()) {
5047 if (!IC->ClassImplementsProtocol(Proto, false))
5055 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
5056 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
5058 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
5059 ObjCInterfaceDecl *IDecl) {
5060 if (!QT->isObjCQualifiedIdType())
5062 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
5065 if (!IDecl->hasDefinition())
5067 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
5068 CollectInheritedProtocols(IDecl, InheritedProtocols);
5069 if (InheritedProtocols.empty())
5071 // Check that if every protocol in list of id<plist> conforms to a protocol
5072 // of IDecl's, then bridge casting is ok.
5073 bool Conforms = false;
5074 for (auto *Proto : OPT->quals()) {
5076 for (auto *PI : InheritedProtocols) {
5077 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
5088 for (auto *PI : InheritedProtocols) {
5089 // If both the right and left sides have qualifiers.
5090 bool Adopts = false;
5091 for (auto *Proto : OPT->quals()) {
5092 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
5093 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
5102 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
5103 /// the given object type.
5104 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
5105 llvm::FoldingSetNodeID ID;
5106 ObjCObjectPointerType::Profile(ID, ObjectT);
5108 void *InsertPos = nullptr;
5109 if (ObjCObjectPointerType *QT =
5110 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
5111 return QualType(QT, 0);
5113 // Find the canonical object type.
5115 if (!ObjectT.isCanonical()) {
5116 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
5118 // Regenerate InsertPos.
5119 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
5123 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
5125 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
5127 Types.push_back(QType);
5128 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
5129 return QualType(QType, 0);
5132 /// getObjCInterfaceType - Return the unique reference to the type for the
5133 /// specified ObjC interface decl. The list of protocols is optional.
5134 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
5135 ObjCInterfaceDecl *PrevDecl) const {
5136 if (Decl->TypeForDecl)
5137 return QualType(Decl->TypeForDecl, 0);
5140 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
5141 Decl->TypeForDecl = PrevDecl->TypeForDecl;
5142 return QualType(PrevDecl->TypeForDecl, 0);
5145 // Prefer the definition, if there is one.
5146 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
5149 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
5150 auto *T = new (Mem) ObjCInterfaceType(Decl);
5151 Decl->TypeForDecl = T;
5153 return QualType(T, 0);
5156 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
5157 /// TypeOfExprType AST's (since expression's are never shared). For example,
5158 /// multiple declarations that refer to "typeof(x)" all contain different
5159 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
5160 /// on canonical type's (which are always unique).
5161 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
5162 TypeOfExprType *toe;
5163 if (tofExpr->isTypeDependent()) {
5164 llvm::FoldingSetNodeID ID;
5165 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
5167 void *InsertPos = nullptr;
5168 DependentTypeOfExprType *Canon
5169 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
5171 // We already have a "canonical" version of an identical, dependent
5172 // typeof(expr) type. Use that as our canonical type.
5173 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
5174 QualType((TypeOfExprType*)Canon, 0));
5176 // Build a new, canonical typeof(expr) type.
5178 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
5179 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
5183 QualType Canonical = getCanonicalType(tofExpr->getType());
5184 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
5186 Types.push_back(toe);
5187 return QualType(toe, 0);
5190 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
5191 /// TypeOfType nodes. The only motivation to unique these nodes would be
5192 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
5193 /// an issue. This doesn't affect the type checker, since it operates
5194 /// on canonical types (which are always unique).
5195 QualType ASTContext::getTypeOfType(QualType tofType) const {
5196 QualType Canonical = getCanonicalType(tofType);
5197 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
5198 Types.push_back(tot);
5199 return QualType(tot, 0);
5202 /// Unlike many "get<Type>" functions, we don't unique DecltypeType
5203 /// nodes. This would never be helpful, since each such type has its own
5204 /// expression, and would not give a significant memory saving, since there
5205 /// is an Expr tree under each such type.
5206 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
5209 // C++11 [temp.type]p2:
5210 // If an expression e involves a template parameter, decltype(e) denotes a
5211 // unique dependent type. Two such decltype-specifiers refer to the same
5212 // type only if their expressions are equivalent (14.5.6.1).
5213 if (e->isInstantiationDependent()) {
5214 llvm::FoldingSetNodeID ID;
5215 DependentDecltypeType::Profile(ID, *this, e);
5217 void *InsertPos = nullptr;
5218 DependentDecltypeType *Canon
5219 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
5221 // Build a new, canonical decltype(expr) type.
5222 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
5223 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
5225 dt = new (*this, TypeAlignment)
5226 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
5228 dt = new (*this, TypeAlignment)
5229 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
5231 Types.push_back(dt);
5232 return QualType(dt, 0);
5235 /// getUnaryTransformationType - We don't unique these, since the memory
5236 /// savings are minimal and these are rare.
5237 QualType ASTContext::getUnaryTransformType(QualType BaseType,
5238 QualType UnderlyingType,
5239 UnaryTransformType::UTTKind Kind)
5241 UnaryTransformType *ut = nullptr;
5243 if (BaseType->isDependentType()) {
5244 // Look in the folding set for an existing type.
5245 llvm::FoldingSetNodeID ID;
5246 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
5248 void *InsertPos = nullptr;
5249 DependentUnaryTransformType *Canon
5250 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
5253 // Build a new, canonical __underlying_type(type) type.
5254 Canon = new (*this, TypeAlignment)
5255 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
5257 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
5259 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5261 QualType(Canon, 0));
5263 QualType CanonType = getCanonicalType(UnderlyingType);
5264 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
5265 UnderlyingType, Kind,
5268 Types.push_back(ut);
5269 return QualType(ut, 0);
5272 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
5273 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
5274 /// canonical deduced-but-dependent 'auto' type.
5276 ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
5277 bool IsDependent, bool IsPack,
5278 ConceptDecl *TypeConstraintConcept,
5279 ArrayRef<TemplateArgument> TypeConstraintArgs) const {
5280 assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
5281 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
5282 !TypeConstraintConcept && !IsDependent)
5283 return getAutoDeductType();
5285 // Look in the folding set for an existing type.
5286 void *InsertPos = nullptr;
5287 llvm::FoldingSetNodeID ID;
5288 AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
5289 TypeConstraintConcept, TypeConstraintArgs);
5290 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
5291 return QualType(AT, 0);
5293 void *Mem = Allocate(sizeof(AutoType) +
5294 sizeof(TemplateArgument) * TypeConstraintArgs.size(),
5296 auto *AT = new (Mem) AutoType(
5297 DeducedType, Keyword,
5298 (IsDependent ? TypeDependence::DependentInstantiation
5299 : TypeDependence::None) |
5300 (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
5301 TypeConstraintConcept, TypeConstraintArgs);
5302 Types.push_back(AT);
5304 AutoTypes.InsertNode(AT, InsertPos);
5305 return QualType(AT, 0);
5308 /// Return the uniqued reference to the deduced template specialization type
5309 /// which has been deduced to the given type, or to the canonical undeduced
5310 /// such type, or the canonical deduced-but-dependent such type.
5311 QualType ASTContext::getDeducedTemplateSpecializationType(
5312 TemplateName Template, QualType DeducedType, bool IsDependent) const {
5313 // Look in the folding set for an existing type.
5314 void *InsertPos = nullptr;
5315 llvm::FoldingSetNodeID ID;
5316 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
5318 if (DeducedTemplateSpecializationType *DTST =
5319 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
5320 return QualType(DTST, 0);
5322 auto *DTST = new (*this, TypeAlignment)
5323 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
5324 Types.push_back(DTST);
5326 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
5327 return QualType(DTST, 0);
5330 /// getAtomicType - Return the uniqued reference to the atomic type for
5331 /// the given value type.
5332 QualType ASTContext::getAtomicType(QualType T) const {
5333 // Unique pointers, to guarantee there is only one pointer of a particular
5335 llvm::FoldingSetNodeID ID;
5336 AtomicType::Profile(ID, T);
5338 void *InsertPos = nullptr;
5339 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
5340 return QualType(AT, 0);
5342 // If the atomic value type isn't canonical, this won't be a canonical type
5343 // either, so fill in the canonical type field.
5345 if (!T.isCanonical()) {
5346 Canonical = getAtomicType(getCanonicalType(T));
5348 // Get the new insert position for the node we care about.
5349 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
5350 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
5352 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
5353 Types.push_back(New);
5354 AtomicTypes.InsertNode(New, InsertPos);
5355 return QualType(New, 0);
5358 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
5359 QualType ASTContext::getAutoDeductType() const {
5360 if (AutoDeductTy.isNull())
5361 AutoDeductTy = QualType(new (*this, TypeAlignment)
5362 AutoType(QualType(), AutoTypeKeyword::Auto,
5363 TypeDependence::None,
5364 /*concept*/ nullptr, /*args*/ {}),
5366 return AutoDeductTy;
5369 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
5370 QualType ASTContext::getAutoRRefDeductType() const {
5371 if (AutoRRefDeductTy.isNull())
5372 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
5373 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
5374 return AutoRRefDeductTy;
5377 /// getTagDeclType - Return the unique reference to the type for the
5378 /// specified TagDecl (struct/union/class/enum) decl.
5379 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
5381 // FIXME: What is the design on getTagDeclType when it requires casting
5382 // away const? mutable?
5383 return getTypeDeclType(const_cast<TagDecl*>(Decl));
5386 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
5387 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
5388 /// needs to agree with the definition in <stddef.h>.
5389 CanQualType ASTContext::getSizeType() const {
5390 return getFromTargetType(Target->getSizeType());
5393 /// Return the unique signed counterpart of the integer type
5394 /// corresponding to size_t.
5395 CanQualType ASTContext::getSignedSizeType() const {
5396 return getFromTargetType(Target->getSignedSizeType());
5399 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
5400 CanQualType ASTContext::getIntMaxType() const {
5401 return getFromTargetType(Target->getIntMaxType());
5404 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
5405 CanQualType ASTContext::getUIntMaxType() const {
5406 return getFromTargetType(Target->getUIntMaxType());
5409 /// getSignedWCharType - Return the type of "signed wchar_t".
5410 /// Used when in C++, as a GCC extension.
5411 QualType ASTContext::getSignedWCharType() const {
5412 // FIXME: derive from "Target" ?
5416 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
5417 /// Used when in C++, as a GCC extension.
5418 QualType ASTContext::getUnsignedWCharType() const {
5419 // FIXME: derive from "Target" ?
5420 return UnsignedIntTy;
5423 QualType ASTContext::getIntPtrType() const {
5424 return getFromTargetType(Target->getIntPtrType());
5427 QualType ASTContext::getUIntPtrType() const {
5428 return getCorrespondingUnsignedType(getIntPtrType());
5431 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
5432 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
5433 QualType ASTContext::getPointerDiffType() const {
5434 return getFromTargetType(Target->getPtrDiffType(0));
5437 /// Return the unique unsigned counterpart of "ptrdiff_t"
5438 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
5439 /// in the definition of %tu format specifier.
5440 QualType ASTContext::getUnsignedPointerDiffType() const {
5441 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
5444 /// Return the unique type for "pid_t" defined in
5445 /// <sys/types.h>. We need this to compute the correct type for vfork().
5446 QualType ASTContext::getProcessIDType() const {
5447 return getFromTargetType(Target->getProcessIDType());
5450 //===----------------------------------------------------------------------===//
5452 //===----------------------------------------------------------------------===//
5454 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
5455 // Push qualifiers into arrays, and then discard any remaining
5457 T = getCanonicalType(T);
5458 T = getVariableArrayDecayedType(T);
5459 const Type *Ty = T.getTypePtr();
5461 if (isa<ArrayType>(Ty)) {
5462 Result = getArrayDecayedType(QualType(Ty,0));
5463 } else if (isa<FunctionType>(Ty)) {
5464 Result = getPointerType(QualType(Ty, 0));
5466 Result = QualType(Ty, 0);
5469 return CanQualType::CreateUnsafe(Result);
5472 QualType ASTContext::getUnqualifiedArrayType(QualType type,
5473 Qualifiers &quals) {
5474 SplitQualType splitType = type.getSplitUnqualifiedType();
5476 // FIXME: getSplitUnqualifiedType() actually walks all the way to
5477 // the unqualified desugared type and then drops it on the floor.
5478 // We then have to strip that sugar back off with
5479 // getUnqualifiedDesugaredType(), which is silly.
5481 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
5483 // If we don't have an array, just use the results in splitType.
5485 quals = splitType.Quals;
5486 return QualType(splitType.Ty, 0);
5489 // Otherwise, recurse on the array's element type.
5490 QualType elementType = AT->getElementType();
5491 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5493 // If that didn't change the element type, AT has no qualifiers, so we
5494 // can just use the results in splitType.
5495 if (elementType == unqualElementType) {
5496 assert(quals.empty()); // from the recursive call
5497 quals = splitType.Quals;
5498 return QualType(splitType.Ty, 0);
5501 // Otherwise, add in the qualifiers from the outermost type, then
5502 // build the type back up.
5503 quals.addConsistentQualifiers(splitType.Quals);
5505 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
5506 return getConstantArrayType(unqualElementType, CAT->getSize(),
5507 CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
5510 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
5511 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
5514 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
5515 return getVariableArrayType(unqualElementType,
5517 VAT->getSizeModifier(),
5518 VAT->getIndexTypeCVRQualifiers(),
5519 VAT->getBracketsRange());
5522 const auto *DSAT = cast<DependentSizedArrayType>(AT);
5523 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
5524 DSAT->getSizeModifier(), 0,
5528 /// Attempt to unwrap two types that may both be array types with the same bound
5529 /// (or both be array types of unknown bound) for the purpose of comparing the
5530 /// cv-decomposition of two types per C++ [conv.qual].
5531 bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5532 bool UnwrappedAny = false;
5534 auto *AT1 = getAsArrayType(T1);
5535 if (!AT1) return UnwrappedAny;
5537 auto *AT2 = getAsArrayType(T2);
5538 if (!AT2) return UnwrappedAny;
5540 // If we don't have two array types with the same constant bound nor two
5541 // incomplete array types, we've unwrapped everything we can.
5542 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5543 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5544 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
5545 return UnwrappedAny;
5546 } else if (!isa<IncompleteArrayType>(AT1) ||
5547 !isa<IncompleteArrayType>(AT2)) {
5548 return UnwrappedAny;
5551 T1 = AT1->getElementType();
5552 T2 = AT2->getElementType();
5553 UnwrappedAny = true;
5557 /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5559 /// If T1 and T2 are both pointer types of the same kind, or both array types
5560 /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5561 /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5563 /// This function will typically be called in a loop that successively
5564 /// "unwraps" pointer and pointer-to-member types to compare them at each
5567 /// \return \c true if a pointer type was unwrapped, \c false if we reached a
5568 /// pair of types that can't be unwrapped further.
5569 bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
5570 UnwrapSimilarArrayTypes(T1, T2);
5572 const auto *T1PtrType = T1->getAs<PointerType>();
5573 const auto *T2PtrType = T2->getAs<PointerType>();
5574 if (T1PtrType && T2PtrType) {
5575 T1 = T1PtrType->getPointeeType();
5576 T2 = T2PtrType->getPointeeType();
5580 const auto *T1MPType = T1->getAs<MemberPointerType>();
5581 const auto *T2MPType = T2->getAs<MemberPointerType>();
5582 if (T1MPType && T2MPType &&
5583 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
5584 QualType(T2MPType->getClass(), 0))) {
5585 T1 = T1MPType->getPointeeType();
5586 T2 = T2MPType->getPointeeType();
5590 if (getLangOpts().ObjC) {
5591 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5592 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
5593 if (T1OPType && T2OPType) {
5594 T1 = T1OPType->getPointeeType();
5595 T2 = T2OPType->getPointeeType();
5600 // FIXME: Block pointers, too?
5605 bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5608 T1 = getUnqualifiedArrayType(T1, Quals);
5609 T2 = getUnqualifiedArrayType(T2, Quals);
5610 if (hasSameType(T1, T2))
5612 if (!UnwrapSimilarTypes(T1, T2))
5617 bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5619 Qualifiers Quals1, Quals2;
5620 T1 = getUnqualifiedArrayType(T1, Quals1);
5621 T2 = getUnqualifiedArrayType(T2, Quals2);
5623 Quals1.removeCVRQualifiers();
5624 Quals2.removeCVRQualifiers();
5625 if (Quals1 != Quals2)
5628 if (hasSameType(T1, T2))
5631 if (!UnwrapSimilarTypes(T1, T2))
5637 ASTContext::getNameForTemplate(TemplateName Name,
5638 SourceLocation NameLoc) const {
5639 switch (Name.getKind()) {
5640 case TemplateName::QualifiedTemplate:
5641 case TemplateName::Template:
5642 // DNInfo work in progress: CHECKME: what about DNLoc?
5643 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5646 case TemplateName::OverloadedTemplate: {
5647 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5648 // DNInfo work in progress: CHECKME: what about DNLoc?
5649 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5652 case TemplateName::AssumedTemplate: {
5653 AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
5654 return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
5657 case TemplateName::DependentTemplate: {
5658 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5659 DeclarationName DName;
5660 if (DTN->isIdentifier()) {
5661 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5662 return DeclarationNameInfo(DName, NameLoc);
5664 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5665 // DNInfo work in progress: FIXME: source locations?
5666 DeclarationNameLoc DNLoc;
5667 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5668 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5669 return DeclarationNameInfo(DName, NameLoc, DNLoc);
5673 case TemplateName::SubstTemplateTemplateParm: {
5674 SubstTemplateTemplateParmStorage *subst
5675 = Name.getAsSubstTemplateTemplateParm();
5676 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5680 case TemplateName::SubstTemplateTemplateParmPack: {
5681 SubstTemplateTemplateParmPackStorage *subst
5682 = Name.getAsSubstTemplateTemplateParmPack();
5683 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5688 llvm_unreachable("bad template name kind!");
5691 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
5692 switch (Name.getKind()) {
5693 case TemplateName::QualifiedTemplate:
5694 case TemplateName::Template: {
5695 TemplateDecl *Template = Name.getAsTemplateDecl();
5696 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
5697 Template = getCanonicalTemplateTemplateParmDecl(TTP);
5699 // The canonical template name is the canonical template declaration.
5700 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
5703 case TemplateName::OverloadedTemplate:
5704 case TemplateName::AssumedTemplate:
5705 llvm_unreachable("cannot canonicalize unresolved template");
5707 case TemplateName::DependentTemplate: {
5708 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5709 assert(DTN && "Non-dependent template names must refer to template decls.");
5710 return DTN->CanonicalTemplateName;
5713 case TemplateName::SubstTemplateTemplateParm: {
5714 SubstTemplateTemplateParmStorage *subst
5715 = Name.getAsSubstTemplateTemplateParm();
5716 return getCanonicalTemplateName(subst->getReplacement());
5719 case TemplateName::SubstTemplateTemplateParmPack: {
5720 SubstTemplateTemplateParmPackStorage *subst
5721 = Name.getAsSubstTemplateTemplateParmPack();
5722 TemplateTemplateParmDecl *canonParameter
5723 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5724 TemplateArgument canonArgPack
5725 = getCanonicalTemplateArgument(subst->getArgumentPack());
5726 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5730 llvm_unreachable("bad template name!");
5733 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5734 X = getCanonicalTemplateName(X);
5735 Y = getCanonicalTemplateName(Y);
5736 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5740 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
5741 switch (Arg.getKind()) {
5742 case TemplateArgument::Null:
5745 case TemplateArgument::Expression:
5748 case TemplateArgument::Declaration: {
5749 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
5750 return TemplateArgument(D, Arg.getParamTypeForDecl());
5753 case TemplateArgument::NullPtr:
5754 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5757 case TemplateArgument::Template:
5758 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
5760 case TemplateArgument::TemplateExpansion:
5761 return TemplateArgument(getCanonicalTemplateName(
5762 Arg.getAsTemplateOrTemplatePattern()),
5763 Arg.getNumTemplateExpansions());
5765 case TemplateArgument::Integral:
5766 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
5768 case TemplateArgument::Type:
5769 return TemplateArgument(getCanonicalType(Arg.getAsType()));
5771 case TemplateArgument::Pack: {
5772 if (Arg.pack_size() == 0)
5775 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
5777 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
5778 AEnd = Arg.pack_end();
5779 A != AEnd; (void)++A, ++Idx)
5780 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
5782 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
5786 // Silence GCC warning
5787 llvm_unreachable("Unhandled template argument kind");
5790 NestedNameSpecifier *
5791 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
5795 switch (NNS->getKind()) {
5796 case NestedNameSpecifier::Identifier:
5797 // Canonicalize the prefix but keep the identifier the same.
5798 return NestedNameSpecifier::Create(*this,
5799 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5800 NNS->getAsIdentifier());
5802 case NestedNameSpecifier::Namespace:
5803 // A namespace is canonical; build a nested-name-specifier with
5804 // this namespace and no prefix.
5805 return NestedNameSpecifier::Create(*this, nullptr,
5806 NNS->getAsNamespace()->getOriginalNamespace());
5808 case NestedNameSpecifier::NamespaceAlias:
5809 // A namespace is canonical; build a nested-name-specifier with
5810 // this namespace and no prefix.
5811 return NestedNameSpecifier::Create(*this, nullptr,
5812 NNS->getAsNamespaceAlias()->getNamespace()
5813 ->getOriginalNamespace());
5815 case NestedNameSpecifier::TypeSpec:
5816 case NestedNameSpecifier::TypeSpecWithTemplate: {
5817 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
5819 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5820 // break it apart into its prefix and identifier, then reconsititute those
5821 // as the canonical nested-name-specifier. This is required to canonicalize
5822 // a dependent nested-name-specifier involving typedefs of dependent-name
5824 // typedef typename T::type T1;
5825 // typedef typename T1::type T2;
5826 if (const auto *DNT = T->getAs<DependentNameType>())
5827 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
5828 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
5830 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5831 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5833 return NestedNameSpecifier::Create(*this, nullptr, false,
5834 const_cast<Type *>(T.getTypePtr()));
5837 case NestedNameSpecifier::Global:
5838 case NestedNameSpecifier::Super:
5839 // The global specifier and __super specifer are canonical and unique.
5843 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5846 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
5847 // Handle the non-qualified case efficiently.
5848 if (!T.hasLocalQualifiers()) {
5849 // Handle the common positive case fast.
5850 if (const auto *AT = dyn_cast<ArrayType>(T))
5854 // Handle the common negative case fast.
5855 if (!isa<ArrayType>(T.getCanonicalType()))
5858 // Apply any qualifiers from the array type to the element type. This
5859 // implements C99 6.7.3p8: "If the specification of an array type includes
5860 // any type qualifiers, the element type is so qualified, not the array type."
5862 // If we get here, we either have type qualifiers on the type, or we have
5863 // sugar such as a typedef in the way. If we have type qualifiers on the type
5864 // we must propagate them down into the element type.
5866 SplitQualType split = T.getSplitDesugaredType();
5867 Qualifiers qs = split.Quals;
5869 // If we have a simple case, just return now.
5870 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
5871 if (!ATy || qs.empty())
5874 // Otherwise, we have an array and we have qualifiers on it. Push the
5875 // qualifiers into the array element type and return a new array type.
5876 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
5878 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
5879 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5881 CAT->getSizeModifier(),
5882 CAT->getIndexTypeCVRQualifiers()));
5883 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
5884 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5885 IAT->getSizeModifier(),
5886 IAT->getIndexTypeCVRQualifiers()));
5888 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
5889 return cast<ArrayType>(
5890 getDependentSizedArrayType(NewEltTy,
5891 DSAT->getSizeExpr(),
5892 DSAT->getSizeModifier(),
5893 DSAT->getIndexTypeCVRQualifiers(),
5894 DSAT->getBracketsRange()));
5896 const auto *VAT = cast<VariableArrayType>(ATy);
5897 return cast<ArrayType>(getVariableArrayType(NewEltTy,
5899 VAT->getSizeModifier(),
5900 VAT->getIndexTypeCVRQualifiers(),
5901 VAT->getBracketsRange()));
5904 QualType ASTContext::getAdjustedParameterType(QualType T) const {
5905 if (T->isArrayType() || T->isFunctionType())
5906 return getDecayedType(T);
5910 QualType ASTContext::getSignatureParameterType(QualType T) const {
5911 T = getVariableArrayDecayedType(T);
5912 T = getAdjustedParameterType(T);
5913 return T.getUnqualifiedType();
5916 QualType ASTContext::getExceptionObjectType(QualType T) const {
5917 // C++ [except.throw]p3:
5918 // A throw-expression initializes a temporary object, called the exception
5919 // object, the type of which is determined by removing any top-level
5920 // cv-qualifiers from the static type of the operand of throw and adjusting
5921 // the type from "array of T" or "function returning T" to "pointer to T"
5922 // or "pointer to function returning T", [...]
5923 T = getVariableArrayDecayedType(T);
5924 if (T->isArrayType() || T->isFunctionType())
5925 T = getDecayedType(T);
5926 return T.getUnqualifiedType();
5929 /// getArrayDecayedType - Return the properly qualified result of decaying the
5930 /// specified array type to a pointer. This operation is non-trivial when
5931 /// handling typedefs etc. The canonical type of "T" must be an array type,
5932 /// this returns a pointer to a properly qualified element of the array.
5934 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
5935 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
5936 // Get the element type with 'getAsArrayType' so that we don't lose any
5937 // typedefs in the element type of the array. This also handles propagation
5938 // of type qualifiers from the array type into the element type if present
5940 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5941 assert(PrettyArrayType && "Not an array type!");
5943 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
5945 // int x[restrict 4] -> int *restrict
5946 QualType Result = getQualifiedType(PtrTy,
5947 PrettyArrayType->getIndexTypeQualifiers());
5949 // int x[_Nullable] -> int * _Nullable
5950 if (auto Nullability = Ty->getNullability(*this)) {
5951 Result = const_cast<ASTContext *>(this)->getAttributedType(
5952 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5957 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5958 return getBaseElementType(array->getElementType());
5961 QualType ASTContext::getBaseElementType(QualType type) const {
5964 SplitQualType split = type.getSplitDesugaredType();
5965 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
5968 type = array->getElementType();
5969 qs.addConsistentQualifiers(split.Quals);
5972 return getQualifiedType(type, qs);
5975 /// getConstantArrayElementCount - Returns number of constant array elements.
5977 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5978 uint64_t ElementCount = 1;
5980 ElementCount *= CA->getSize().getZExtValue();
5981 CA = dyn_cast_or_null<ConstantArrayType>(
5982 CA->getElementType()->getAsArrayTypeUnsafe());
5984 return ElementCount;
5987 /// getFloatingRank - Return a relative rank for floating point types.
5988 /// This routine will assert if passed a built-in type that isn't a float.
5989 static FloatingRank getFloatingRank(QualType T) {
5990 if (const auto *CT = T->getAs<ComplexType>())
5991 return getFloatingRank(CT->getElementType());
5993 switch (T->castAs<BuiltinType>()->getKind()) {
5994 default: llvm_unreachable("getFloatingRank(): not a floating type");
5995 case BuiltinType::Float16: return Float16Rank;
5996 case BuiltinType::Half: return HalfRank;
5997 case BuiltinType::Float: return FloatRank;
5998 case BuiltinType::Double: return DoubleRank;
5999 case BuiltinType::LongDouble: return LongDoubleRank;
6000 case BuiltinType::Float128: return Float128Rank;
6001 case BuiltinType::BFloat16: return BFloat16Rank;
6005 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
6006 /// point or a complex type (based on typeDomain/typeSize).
6007 /// 'typeDomain' is a real floating point or complex type.
6008 /// 'typeSize' is a real floating point or complex type.
6009 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
6010 QualType Domain) const {
6011 FloatingRank EltRank = getFloatingRank(Size);
6012 if (Domain->isComplexType()) {
6014 case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported");
6016 case HalfRank: llvm_unreachable("Complex half is not supported");
6017 case FloatRank: return FloatComplexTy;
6018 case DoubleRank: return DoubleComplexTy;
6019 case LongDoubleRank: return LongDoubleComplexTy;
6020 case Float128Rank: return Float128ComplexTy;
6024 assert(Domain->isRealFloatingType() && "Unknown domain!");
6026 case Float16Rank: return HalfTy;
6027 case BFloat16Rank: return BFloat16Ty;
6028 case HalfRank: return HalfTy;
6029 case FloatRank: return FloatTy;
6030 case DoubleRank: return DoubleTy;
6031 case LongDoubleRank: return LongDoubleTy;
6032 case Float128Rank: return Float128Ty;
6034 llvm_unreachable("getFloatingRank(): illegal value for rank");
6037 /// getFloatingTypeOrder - Compare the rank of the two specified floating
6038 /// point types, ignoring the domain of the type (i.e. 'double' ==
6039 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
6040 /// LHS < RHS, return -1.
6041 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
6042 FloatingRank LHSR = getFloatingRank(LHS);
6043 FloatingRank RHSR = getFloatingRank(RHS);
6052 int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
6053 if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
6055 return getFloatingTypeOrder(LHS, RHS);
6058 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
6059 /// routine will assert if passed a built-in type that isn't an integer or enum,
6060 /// or if it is not canonicalized.
6061 unsigned ASTContext::getIntegerRank(const Type *T) const {
6062 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
6064 // Results in this 'losing' to any type of the same size, but winning if
6066 if (const auto *EIT = dyn_cast<ExtIntType>(T))
6067 return 0 + (EIT->getNumBits() << 3);
6069 switch (cast<BuiltinType>(T)->getKind()) {
6070 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
6071 case BuiltinType::Bool:
6072 return 1 + (getIntWidth(BoolTy) << 3);
6073 case BuiltinType::Char_S:
6074 case BuiltinType::Char_U:
6075 case BuiltinType::SChar:
6076 case BuiltinType::UChar:
6077 return 2 + (getIntWidth(CharTy) << 3);
6078 case BuiltinType::Short:
6079 case BuiltinType::UShort:
6080 return 3 + (getIntWidth(ShortTy) << 3);
6081 case BuiltinType::Int:
6082 case BuiltinType::UInt:
6083 return 4 + (getIntWidth(IntTy) << 3);
6084 case BuiltinType::Long:
6085 case BuiltinType::ULong:
6086 return 5 + (getIntWidth(LongTy) << 3);
6087 case BuiltinType::LongLong:
6088 case BuiltinType::ULongLong:
6089 return 6 + (getIntWidth(LongLongTy) << 3);
6090 case BuiltinType::Int128:
6091 case BuiltinType::UInt128:
6092 return 7 + (getIntWidth(Int128Ty) << 3);
6096 /// Whether this is a promotable bitfield reference according
6097 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
6099 /// \returns the type this bit-field will promote to, or NULL if no
6100 /// promotion occurs.
6101 QualType ASTContext::isPromotableBitField(Expr *E) const {
6102 if (E->isTypeDependent() || E->isValueDependent())
6105 // C++ [conv.prom]p5:
6106 // If the bit-field has an enumerated type, it is treated as any other
6107 // value of that type for promotion purposes.
6108 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
6111 // FIXME: We should not do this unless E->refersToBitField() is true. This
6112 // matters in C where getSourceBitField() will find bit-fields for various
6113 // cases where the source expression is not a bit-field designator.
6115 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
6119 QualType FT = Field->getType();
6121 uint64_t BitWidth = Field->getBitWidthValue(*this);
6122 uint64_t IntSize = getTypeSize(IntTy);
6123 // C++ [conv.prom]p5:
6124 // A prvalue for an integral bit-field can be converted to a prvalue of type
6125 // int if int can represent all the values of the bit-field; otherwise, it
6126 // can be converted to unsigned int if unsigned int can represent all the
6127 // values of the bit-field. If the bit-field is larger yet, no integral
6128 // promotion applies to it.
6130 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
6131 // If an int can represent all values of the original type (as restricted by
6132 // the width, for a bit-field), the value is converted to an int; otherwise,
6133 // it is converted to an unsigned int.
6135 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
6136 // We perform that promotion here to match GCC and C++.
6137 // FIXME: C does not permit promotion of an enum bit-field whose rank is
6138 // greater than that of 'int'. We perform that promotion to match GCC.
6139 if (BitWidth < IntSize)
6142 if (BitWidth == IntSize)
6143 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
6145 // Bit-fields wider than int are not subject to promotions, and therefore act
6146 // like the base type. GCC has some weird bugs in this area that we
6147 // deliberately do not follow (GCC follows a pre-standard resolution to
6148 // C's DR315 which treats bit-width as being part of the type, and this leaks
6149 // into their semantics in some cases).
6153 /// getPromotedIntegerType - Returns the type that Promotable will
6154 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
6156 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
6157 assert(!Promotable.isNull());
6158 assert(Promotable->isPromotableIntegerType());
6159 if (const auto *ET = Promotable->getAs<EnumType>())
6160 return ET->getDecl()->getPromotionType();
6162 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
6163 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
6164 // (3.9.1) can be converted to a prvalue of the first of the following
6165 // types that can represent all the values of its underlying type:
6166 // int, unsigned int, long int, unsigned long int, long long int, or
6167 // unsigned long long int [...]
6168 // FIXME: Is there some better way to compute this?
6169 if (BT->getKind() == BuiltinType::WChar_S ||
6170 BT->getKind() == BuiltinType::WChar_U ||
6171 BT->getKind() == BuiltinType::Char8 ||
6172 BT->getKind() == BuiltinType::Char16 ||
6173 BT->getKind() == BuiltinType::Char32) {
6174 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
6175 uint64_t FromSize = getTypeSize(BT);
6176 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
6177 LongLongTy, UnsignedLongLongTy };
6178 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
6179 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
6180 if (FromSize < ToSize ||
6181 (FromSize == ToSize &&
6182 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
6183 return PromoteTypes[Idx];
6185 llvm_unreachable("char type should fit into long long");
6189 // At this point, we should have a signed or unsigned integer type.
6190 if (Promotable->isSignedIntegerType())
6192 uint64_t PromotableSize = getIntWidth(Promotable);
6193 uint64_t IntSize = getIntWidth(IntTy);
6194 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
6195 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
6198 /// Recurses in pointer/array types until it finds an objc retainable
6199 /// type and returns its ownership.
6200 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
6201 while (!T.isNull()) {
6202 if (T.getObjCLifetime() != Qualifiers::OCL_None)
6203 return T.getObjCLifetime();
6204 if (T->isArrayType())
6205 T = getBaseElementType(T);
6206 else if (const auto *PT = T->getAs<PointerType>())
6207 T = PT->getPointeeType();
6208 else if (const auto *RT = T->getAs<ReferenceType>())
6209 T = RT->getPointeeType();
6214 return Qualifiers::OCL_None;
6217 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
6218 // Incomplete enum types are not treated as integer types.
6219 // FIXME: In C++, enum types are never integer types.
6220 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
6221 return ET->getDecl()->getIntegerType().getTypePtr();
6225 /// getIntegerTypeOrder - Returns the highest ranked integer type:
6226 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
6227 /// LHS < RHS, return -1.
6228 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
6229 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
6230 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
6232 // Unwrap enums to their underlying type.
6233 if (const auto *ET = dyn_cast<EnumType>(LHSC))
6234 LHSC = getIntegerTypeForEnum(ET);
6235 if (const auto *ET = dyn_cast<EnumType>(RHSC))
6236 RHSC = getIntegerTypeForEnum(ET);
6238 if (LHSC == RHSC) return 0;
6240 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
6241 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
6243 unsigned LHSRank = getIntegerRank(LHSC);
6244 unsigned RHSRank = getIntegerRank(RHSC);
6246 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
6247 if (LHSRank == RHSRank) return 0;
6248 return LHSRank > RHSRank ? 1 : -1;
6251 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
6253 // If the unsigned [LHS] type is larger, return it.
6254 if (LHSRank >= RHSRank)
6257 // If the signed type can represent all values of the unsigned type, it
6258 // wins. Because we are dealing with 2's complement and types that are
6259 // powers of two larger than each other, this is always safe.
6263 // If the unsigned [RHS] type is larger, return it.
6264 if (RHSRank >= LHSRank)
6267 // If the signed type can represent all values of the unsigned type, it
6268 // wins. Because we are dealing with 2's complement and types that are
6269 // powers of two larger than each other, this is always safe.
6273 TypedefDecl *ASTContext::getCFConstantStringDecl() const {
6274 if (CFConstantStringTypeDecl)
6275 return CFConstantStringTypeDecl;
6277 assert(!CFConstantStringTagDecl &&
6278 "tag and typedef should be initialized together");
6279 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
6280 CFConstantStringTagDecl->startDefinition();
6290 /// typedef struct __NSConstantString_tag {
6293 /// const char *str;
6295 /// } __NSConstantString;
6297 /// Swift ABI (4.1, 4.2)
6299 /// typedef struct __NSConstantString_tag {
6300 /// uintptr_t _cfisa;
6301 /// uintptr_t _swift_rc;
6302 /// _Atomic(uint64_t) _cfinfoa;
6303 /// const char *_ptr;
6304 /// uint32_t _length;
6305 /// } __NSConstantString;
6309 /// typedef struct __NSConstantString_tag {
6310 /// uintptr_t _cfisa;
6311 /// uintptr_t _swift_rc;
6312 /// _Atomic(uint64_t) _cfinfoa;
6313 /// const char *_ptr;
6314 /// uintptr_t _length;
6315 /// } __NSConstantString;
6317 const auto CFRuntime = getLangOpts().CFRuntime;
6318 if (static_cast<unsigned>(CFRuntime) <
6319 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
6320 Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
6321 Fields[Count++] = { IntTy, "flags" };
6322 Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
6323 Fields[Count++] = { LongTy, "length" };
6325 Fields[Count++] = { getUIntPtrType(), "_cfisa" };
6326 Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
6327 Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
6328 Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
6329 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
6330 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
6331 Fields[Count++] = { IntTy, "_ptr" };
6333 Fields[Count++] = { getUIntPtrType(), "_ptr" };
6337 for (unsigned i = 0; i < Count; ++i) {
6339 FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
6340 SourceLocation(), &Idents.get(Fields[i].Name),
6341 Fields[i].Type, /*TInfo=*/nullptr,
6342 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6343 Field->setAccess(AS_public);
6344 CFConstantStringTagDecl->addDecl(Field);
6347 CFConstantStringTagDecl->completeDefinition();
6348 // This type is designed to be compatible with NSConstantString, but cannot
6349 // use the same name, since NSConstantString is an interface.
6350 auto tagType = getTagDeclType(CFConstantStringTagDecl);
6351 CFConstantStringTypeDecl =
6352 buildImplicitTypedef(tagType, "__NSConstantString");
6354 return CFConstantStringTypeDecl;
6357 RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
6358 if (!CFConstantStringTagDecl)
6359 getCFConstantStringDecl(); // Build the tag and the typedef.
6360 return CFConstantStringTagDecl;
6363 // getCFConstantStringType - Return the type used for constant CFStrings.
6364 QualType ASTContext::getCFConstantStringType() const {
6365 return getTypedefType(getCFConstantStringDecl());
6368 QualType ASTContext::getObjCSuperType() const {
6369 if (ObjCSuperType.isNull()) {
6370 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
6371 TUDecl->addDecl(ObjCSuperTypeDecl);
6372 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
6374 return ObjCSuperType;
6377 void ASTContext::setCFConstantStringType(QualType T) {
6378 const auto *TD = T->castAs<TypedefType>();
6379 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
6380 const auto *TagType =
6381 CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
6382 CFConstantStringTagDecl = TagType->getDecl();
6385 QualType ASTContext::getBlockDescriptorType() const {
6386 if (BlockDescriptorType)
6387 return getTagDeclType(BlockDescriptorType);
6390 // FIXME: Needs the FlagAppleBlock bit.
6391 RD = buildImplicitRecord("__block_descriptor");
6392 RD->startDefinition();
6394 QualType FieldTypes[] = {
6399 static const char *const FieldNames[] = {
6404 for (size_t i = 0; i < 2; ++i) {
6405 FieldDecl *Field = FieldDecl::Create(
6406 *this, RD, SourceLocation(), SourceLocation(),
6407 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6408 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
6409 Field->setAccess(AS_public);
6413 RD->completeDefinition();
6415 BlockDescriptorType = RD;
6417 return getTagDeclType(BlockDescriptorType);
6420 QualType ASTContext::getBlockDescriptorExtendedType() const {
6421 if (BlockDescriptorExtendedType)
6422 return getTagDeclType(BlockDescriptorExtendedType);
6425 // FIXME: Needs the FlagAppleBlock bit.
6426 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
6427 RD->startDefinition();
6429 QualType FieldTypes[] = {
6432 getPointerType(VoidPtrTy),
6433 getPointerType(VoidPtrTy)
6436 static const char *const FieldNames[] = {
6443 for (size_t i = 0; i < 4; ++i) {
6444 FieldDecl *Field = FieldDecl::Create(
6445 *this, RD, SourceLocation(), SourceLocation(),
6446 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
6447 /*BitWidth=*/nullptr,
6448 /*Mutable=*/false, ICIS_NoInit);
6449 Field->setAccess(AS_public);
6453 RD->completeDefinition();
6455 BlockDescriptorExtendedType = RD;
6456 return getTagDeclType(BlockDescriptorExtendedType);
6459 OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
6460 const auto *BT = dyn_cast<BuiltinType>(T);
6463 if (isa<PipeType>(T))
6466 return OCLTK_Default;
6469 switch (BT->getKind()) {
6470 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6471 case BuiltinType::Id: \
6473 #include "clang/Basic/OpenCLImageTypes.def"
6475 case BuiltinType::OCLClkEvent:
6476 return OCLTK_ClkEvent;
6478 case BuiltinType::OCLEvent:
6481 case BuiltinType::OCLQueue:
6484 case BuiltinType::OCLReserveID:
6485 return OCLTK_ReserveID;
6487 case BuiltinType::OCLSampler:
6488 return OCLTK_Sampler;
6491 return OCLTK_Default;
6495 LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
6496 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
6499 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
6500 /// requires copy/dispose. Note that this must match the logic
6501 /// in buildByrefHelpers.
6502 bool ASTContext::BlockRequiresCopying(QualType Ty,
6504 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
6505 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
6506 if (!copyExpr && record->hasTrivialDestructor()) return false;
6511 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
6513 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
6516 if (!Ty->isObjCRetainableType()) return false;
6518 Qualifiers qs = Ty.getQualifiers();
6520 // If we have lifetime, that dominates.
6521 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
6523 case Qualifiers::OCL_None: llvm_unreachable("impossible");
6525 // These are just bits as far as the runtime is concerned.
6526 case Qualifiers::OCL_ExplicitNone:
6527 case Qualifiers::OCL_Autoreleasing:
6530 // These cases should have been taken care of when checking the type's
6532 case Qualifiers::OCL_Weak:
6533 case Qualifiers::OCL_Strong:
6534 llvm_unreachable("impossible");
6536 llvm_unreachable("fell out of lifetime switch!");
6538 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6539 Ty->isObjCObjectPointerType());
6542 bool ASTContext::getByrefLifetime(QualType Ty,
6543 Qualifiers::ObjCLifetime &LifeTime,
6544 bool &HasByrefExtendedLayout) const {
6545 if (!getLangOpts().ObjC ||
6546 getLangOpts().getGC() != LangOptions::NonGC)
6549 HasByrefExtendedLayout = false;
6550 if (Ty->isRecordType()) {
6551 HasByrefExtendedLayout = true;
6552 LifeTime = Qualifiers::OCL_None;
6553 } else if ((LifeTime = Ty.getObjCLifetime())) {
6554 // Honor the ARC qualifiers.
6555 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6557 LifeTime = Qualifiers::OCL_ExplicitNone;
6559 LifeTime = Qualifiers::OCL_None;
6564 CanQualType ASTContext::getNSUIntegerType() const {
6565 assert(Target && "Expected target to be initialized");
6566 const llvm::Triple &T = Target->getTriple();
6567 // Windows is LLP64 rather than LP64
6568 if (T.isOSWindows() && T.isArch64Bit())
6569 return UnsignedLongLongTy;
6570 return UnsignedLongTy;
6573 CanQualType ASTContext::getNSIntegerType() const {
6574 assert(Target && "Expected target to be initialized");
6575 const llvm::Triple &T = Target->getTriple();
6576 // Windows is LLP64 rather than LP64
6577 if (T.isOSWindows() && T.isArch64Bit())
6582 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6583 if (!ObjCInstanceTypeDecl)
6584 ObjCInstanceTypeDecl =
6585 buildImplicitTypedef(getObjCIdType(), "instancetype");
6586 return ObjCInstanceTypeDecl;
6589 // This returns true if a type has been typedefed to BOOL:
6590 // typedef <type> BOOL;
6591 static bool isTypeTypedefedAsBOOL(QualType T) {
6592 if (const auto *TT = dyn_cast<TypedefType>(T))
6593 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6594 return II->isStr("BOOL");
6599 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
6601 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
6602 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6603 return CharUnits::Zero();
6605 CharUnits sz = getTypeSizeInChars(type);
6607 // Make all integer and enum types at least as large as an int
6608 if (sz.isPositive() && type->isIntegralOrEnumerationType())
6609 sz = std::max(sz, getTypeSizeInChars(IntTy));
6610 // Treat arrays as pointers, since that's how they're passed in.
6611 else if (type->isArrayType())
6612 sz = getTypeSizeInChars(VoidPtrTy);
6616 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
6617 return getTargetInfo().getCXXABI().isMicrosoft() &&
6618 VD->isStaticDataMember() &&
6619 VD->getType()->isIntegralOrEnumerationType() &&
6620 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
6623 ASTContext::InlineVariableDefinitionKind
6624 ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6625 if (!VD->isInline())
6626 return InlineVariableDefinitionKind::None;
6628 // In almost all cases, it's a weak definition.
6629 auto *First = VD->getFirstDecl();
6630 if (First->isInlineSpecified() || !First->isStaticDataMember())
6631 return InlineVariableDefinitionKind::Weak;
6633 // If there's a file-context declaration in this translation unit, it's a
6634 // non-discardable definition.
6635 for (auto *D : VD->redecls())
6636 if (D->getLexicalDeclContext()->isFileContext() &&
6637 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
6638 return InlineVariableDefinitionKind::Strong;
6640 // If we've not seen one yet, we don't know.
6641 return InlineVariableDefinitionKind::WeakUnknown;
6644 static std::string charUnitsToString(const CharUnits &CU) {
6645 return llvm::itostr(CU.getQuantity());
6648 /// getObjCEncodingForBlock - Return the encoded type for this block
6650 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6653 const BlockDecl *Decl = Expr->getBlockDecl();
6655 Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
6656 QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
6657 // Encode result type.
6658 if (getLangOpts().EncodeExtendedBlockSig)
6659 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
6662 getObjCEncodingForType(BlockReturnTy, S);
6663 // Compute size of all parameters.
6664 // Start with computing size of a pointer in number of bytes.
6665 // FIXME: There might(should) be a better way of doing this computation!
6666 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6667 CharUnits ParmOffset = PtrSize;
6668 for (auto PI : Decl->parameters()) {
6669 QualType PType = PI->getType();
6670 CharUnits sz = getObjCEncodingTypeSize(PType);
6673 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
6676 // Size of the argument frame
6677 S += charUnitsToString(ParmOffset);
6678 // Block pointer and offset.
6682 ParmOffset = PtrSize;
6683 for (auto PVDecl : Decl->parameters()) {
6684 QualType PType = PVDecl->getOriginalType();
6685 if (const auto *AT =
6686 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6687 // Use array's original type only if it has known number of
6689 if (!isa<ConstantArrayType>(AT))
6690 PType = PVDecl->getType();
6691 } else if (PType->isFunctionType())
6692 PType = PVDecl->getType();
6693 if (getLangOpts().EncodeExtendedBlockSig)
6694 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6695 S, true /*Extended*/);
6697 getObjCEncodingForType(PType, S);
6698 S += charUnitsToString(ParmOffset);
6699 ParmOffset += getObjCEncodingTypeSize(PType);
6706 ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6708 // Encode result type.
6709 getObjCEncodingForType(Decl->getReturnType(), S);
6710 CharUnits ParmOffset;
6711 // Compute size of all parameters.
6712 for (auto PI : Decl->parameters()) {
6713 QualType PType = PI->getType();
6714 CharUnits sz = getObjCEncodingTypeSize(PType);
6718 assert(sz.isPositive() &&
6719 "getObjCEncodingForFunctionDecl - Incomplete param type");
6722 S += charUnitsToString(ParmOffset);
6723 ParmOffset = CharUnits::Zero();
6726 for (auto PVDecl : Decl->parameters()) {
6727 QualType PType = PVDecl->getOriginalType();
6728 if (const auto *AT =
6729 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6730 // Use array's original type only if it has known number of
6732 if (!isa<ConstantArrayType>(AT))
6733 PType = PVDecl->getType();
6734 } else if (PType->isFunctionType())
6735 PType = PVDecl->getType();
6736 getObjCEncodingForType(PType, S);
6737 S += charUnitsToString(ParmOffset);
6738 ParmOffset += getObjCEncodingTypeSize(PType);
6744 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
6745 /// method parameter or return type. If Extended, include class names and
6746 /// block object types.
6747 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6748 QualType T, std::string& S,
6749 bool Extended) const {
6750 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6751 getObjCEncodingForTypeQualifier(QT, S);
6752 // Encode parameter type.
6753 ObjCEncOptions Options = ObjCEncOptions()
6754 .setExpandPointedToStructures()
6755 .setExpandStructures()
6756 .setIsOutermostType();
6758 Options.setEncodeBlockParameters().setEncodeClassNames();
6759 getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
6762 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
6764 std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6765 bool Extended) const {
6766 // FIXME: This is not very efficient.
6767 // Encode return type.
6769 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6770 Decl->getReturnType(), S, Extended);
6771 // Compute size of all parameters.
6772 // Start with computing size of a pointer in number of bytes.
6773 // FIXME: There might(should) be a better way of doing this computation!
6774 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6775 // The first two arguments (self and _cmd) are pointers; account for
6777 CharUnits ParmOffset = 2 * PtrSize;
6778 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
6779 E = Decl->sel_param_end(); PI != E; ++PI) {
6780 QualType PType = (*PI)->getType();
6781 CharUnits sz = getObjCEncodingTypeSize(PType);
6785 assert(sz.isPositive() &&
6786 "getObjCEncodingForMethodDecl - Incomplete param type");
6789 S += charUnitsToString(ParmOffset);
6791 S += charUnitsToString(PtrSize);
6794 ParmOffset = 2 * PtrSize;
6795 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
6796 E = Decl->sel_param_end(); PI != E; ++PI) {
6797 const ParmVarDecl *PVDecl = *PI;
6798 QualType PType = PVDecl->getOriginalType();
6799 if (const auto *AT =
6800 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
6801 // Use array's original type only if it has known number of
6803 if (!isa<ConstantArrayType>(AT))
6804 PType = PVDecl->getType();
6805 } else if (PType->isFunctionType())
6806 PType = PVDecl->getType();
6807 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
6808 PType, S, Extended);
6809 S += charUnitsToString(ParmOffset);
6810 ParmOffset += getObjCEncodingTypeSize(PType);
6816 ObjCPropertyImplDecl *
6817 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6818 const ObjCPropertyDecl *PD,
6819 const Decl *Container) const {
6822 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
6823 for (auto *PID : CID->property_impls())
6824 if (PID->getPropertyDecl() == PD)
6827 const auto *OID = cast<ObjCImplementationDecl>(Container);
6828 for (auto *PID : OID->property_impls())
6829 if (PID->getPropertyDecl() == PD)
6835 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
6836 /// property declaration. If non-NULL, Container must be either an
6837 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6838 /// NULL when getting encodings for protocol properties.
6839 /// Property attributes are stored as a comma-delimited C string. The simple
6840 /// attributes readonly and bycopy are encoded as single characters. The
6841 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
6842 /// encoded as single characters, followed by an identifier. Property types
6843 /// are also encoded as a parametrized attribute. The characters used to encode
6844 /// these attributes are defined by the following enumeration:
6846 /// enum PropertyAttributes {
6847 /// kPropertyReadOnly = 'R', // property is read-only.
6848 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6849 /// kPropertyByref = '&', // property is a reference to the value last assigned
6850 /// kPropertyDynamic = 'D', // property is dynamic
6851 /// kPropertyGetter = 'G', // followed by getter selector name
6852 /// kPropertySetter = 'S', // followed by setter selector name
6853 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
6854 /// kPropertyType = 'T' // followed by old-style type encoding.
6855 /// kPropertyWeak = 'W' // 'weak' property
6856 /// kPropertyStrong = 'P' // property GC'able
6857 /// kPropertyNonAtomic = 'N' // property non-atomic
6861 ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6862 const Decl *Container) const {
6863 // Collect information from the property implementation decl(s).
6864 bool Dynamic = false;
6865 ObjCPropertyImplDecl *SynthesizePID = nullptr;
6867 if (ObjCPropertyImplDecl *PropertyImpDecl =
6868 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6869 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6872 SynthesizePID = PropertyImpDecl;
6875 // FIXME: This is not very efficient.
6876 std::string S = "T";
6878 // Encode result type.
6879 // GCC has some special rules regarding encoding of properties which
6880 // closely resembles encoding of ivars.
6881 getObjCEncodingForPropertyType(PD->getType(), S);
6883 if (PD->isReadOnly()) {
6885 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
6887 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
6889 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
6892 switch (PD->getSetterKind()) {
6893 case ObjCPropertyDecl::Assign: break;
6894 case ObjCPropertyDecl::Copy: S += ",C"; break;
6895 case ObjCPropertyDecl::Retain: S += ",&"; break;
6896 case ObjCPropertyDecl::Weak: S += ",W"; break;
6900 // It really isn't clear at all what this means, since properties
6901 // are "dynamic by default".
6905 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
6908 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
6910 S += PD->getGetterName().getAsString();
6913 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
6915 S += PD->getSetterName().getAsString();
6918 if (SynthesizePID) {
6919 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6921 S += OID->getNameAsString();
6924 // FIXME: OBJCGC: weak & strong
6928 /// getLegacyIntegralTypeEncoding -
6929 /// Another legacy compatibility encoding: 32-bit longs are encoded as
6930 /// 'l' or 'L' , but not always. For typedefs, we need to use
6931 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
6932 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
6933 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
6934 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
6935 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
6936 PointeeTy = UnsignedIntTy;
6938 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
6944 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
6945 const FieldDecl *Field,
6946 QualType *NotEncodedT) const {
6947 // We follow the behavior of gcc, expanding structures which are
6948 // directly pointed to, and expanding embedded structures. Note that
6949 // these rules are sufficient to prevent recursive encoding of the
6951 getObjCEncodingForTypeImpl(T, S,
6953 .setExpandPointedToStructures()
6954 .setExpandStructures()
6955 .setIsOutermostType(),
6956 Field, NotEncodedT);
6959 void ASTContext::getObjCEncodingForPropertyType(QualType T,
6960 std::string& S) const {
6961 // Encode result type.
6962 // GCC has some special rules regarding encoding of properties which
6963 // closely resembles encoding of ivars.
6964 getObjCEncodingForTypeImpl(T, S,
6966 .setExpandPointedToStructures()
6967 .setExpandStructures()
6968 .setIsOutermostType()
6969 .setEncodingProperty(),
6973 static char getObjCEncodingForPrimitiveType(const ASTContext *C,
6974 const BuiltinType *BT) {
6975 BuiltinType::Kind kind = BT->getKind();
6977 case BuiltinType::Void: return 'v';
6978 case BuiltinType::Bool: return 'B';
6979 case BuiltinType::Char8:
6980 case BuiltinType::Char_U:
6981 case BuiltinType::UChar: return 'C';
6982 case BuiltinType::Char16:
6983 case BuiltinType::UShort: return 'S';
6984 case BuiltinType::Char32:
6985 case BuiltinType::UInt: return 'I';
6986 case BuiltinType::ULong:
6987 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
6988 case BuiltinType::UInt128: return 'T';
6989 case BuiltinType::ULongLong: return 'Q';
6990 case BuiltinType::Char_S:
6991 case BuiltinType::SChar: return 'c';
6992 case BuiltinType::Short: return 's';
6993 case BuiltinType::WChar_S:
6994 case BuiltinType::WChar_U:
6995 case BuiltinType::Int: return 'i';
6996 case BuiltinType::Long:
6997 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
6998 case BuiltinType::LongLong: return 'q';
6999 case BuiltinType::Int128: return 't';
7000 case BuiltinType::Float: return 'f';
7001 case BuiltinType::Double: return 'd';
7002 case BuiltinType::LongDouble: return 'D';
7003 case BuiltinType::NullPtr: return '*'; // like char*
7005 case BuiltinType::BFloat16:
7006 case BuiltinType::Float16:
7007 case BuiltinType::Float128:
7008 case BuiltinType::Half:
7009 case BuiltinType::ShortAccum:
7010 case BuiltinType::Accum:
7011 case BuiltinType::LongAccum:
7012 case BuiltinType::UShortAccum:
7013 case BuiltinType::UAccum:
7014 case BuiltinType::ULongAccum:
7015 case BuiltinType::ShortFract:
7016 case BuiltinType::Fract:
7017 case BuiltinType::LongFract:
7018 case BuiltinType::UShortFract:
7019 case BuiltinType::UFract:
7020 case BuiltinType::ULongFract:
7021 case BuiltinType::SatShortAccum:
7022 case BuiltinType::SatAccum:
7023 case BuiltinType::SatLongAccum:
7024 case BuiltinType::SatUShortAccum:
7025 case BuiltinType::SatUAccum:
7026 case BuiltinType::SatULongAccum:
7027 case BuiltinType::SatShortFract:
7028 case BuiltinType::SatFract:
7029 case BuiltinType::SatLongFract:
7030 case BuiltinType::SatUShortFract:
7031 case BuiltinType::SatUFract:
7032 case BuiltinType::SatULongFract:
7033 // FIXME: potentially need @encodes for these!
7036 #define SVE_TYPE(Name, Id, SingletonId) \
7037 case BuiltinType::Id:
7038 #include "clang/Basic/AArch64SVEACLETypes.def"
7040 DiagnosticsEngine &Diags = C->getDiagnostics();
7041 unsigned DiagID = Diags.getCustomDiagID(
7042 DiagnosticsEngine::Error, "cannot yet @encode type %0");
7043 Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
7047 case BuiltinType::ObjCId:
7048 case BuiltinType::ObjCClass:
7049 case BuiltinType::ObjCSel:
7050 llvm_unreachable("@encoding ObjC primitive type");
7052 // OpenCL and placeholder types don't need @encodings.
7053 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7054 case BuiltinType::Id:
7055 #include "clang/Basic/OpenCLImageTypes.def"
7056 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7057 case BuiltinType::Id:
7058 #include "clang/Basic/OpenCLExtensionTypes.def"
7059 case BuiltinType::OCLEvent:
7060 case BuiltinType::OCLClkEvent:
7061 case BuiltinType::OCLQueue:
7062 case BuiltinType::OCLReserveID:
7063 case BuiltinType::OCLSampler:
7064 case BuiltinType::Dependent:
7065 #define BUILTIN_TYPE(KIND, ID)
7066 #define PLACEHOLDER_TYPE(KIND, ID) \
7067 case BuiltinType::KIND:
7068 #include "clang/AST/BuiltinTypes.def"
7069 llvm_unreachable("invalid builtin type for @encode");
7071 llvm_unreachable("invalid BuiltinType::Kind value");
7074 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
7075 EnumDecl *Enum = ET->getDecl();
7077 // The encoding of an non-fixed enum type is always 'i', regardless of size.
7078 if (!Enum->isFixed())
7081 // The encoding of a fixed enum type matches its fixed underlying type.
7082 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
7083 return getObjCEncodingForPrimitiveType(C, BT);
7086 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
7087 QualType T, const FieldDecl *FD) {
7088 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
7090 // The NeXT runtime encodes bit fields as b followed by the number of bits.
7091 // The GNU runtime requires more information; bitfields are encoded as b,
7092 // then the offset (in bits) of the first element, then the type of the
7093 // bitfield, then the size in bits. For example, in this structure:
7100 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
7101 // runtime, but b32i2 for the GNU runtime. The reason for this extra
7102 // information is not especially sensible, but we're stuck with it for
7103 // compatibility with GCC, although providing it breaks anything that
7104 // actually uses runtime introspection and wants to work on both runtimes...
7105 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
7108 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
7109 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
7112 const RecordDecl *RD = FD->getParent();
7113 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
7114 Offset = RL.getFieldOffset(FD->getFieldIndex());
7117 S += llvm::utostr(Offset);
7119 if (const auto *ET = T->getAs<EnumType>())
7120 S += ObjCEncodingForEnumType(Ctx, ET);
7122 const auto *BT = T->castAs<BuiltinType>();
7123 S += getObjCEncodingForPrimitiveType(Ctx, BT);
7126 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
7129 // FIXME: Use SmallString for accumulating string.
7130 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
7131 const ObjCEncOptions Options,
7132 const FieldDecl *FD,
7133 QualType *NotEncodedT) const {
7134 CanQualType CT = getCanonicalType(T);
7135 switch (CT->getTypeClass()) {
7138 if (FD && FD->isBitField())
7139 return EncodeBitField(this, S, T, FD);
7140 if (const auto *BT = dyn_cast<BuiltinType>(CT))
7141 S += getObjCEncodingForPrimitiveType(this, BT);
7143 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
7148 getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
7155 getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
7160 // encoding for pointer or reference types.
7162 case Type::LValueReference:
7163 case Type::RValueReference: {
7165 if (isa<PointerType>(CT)) {
7166 const auto *PT = T->castAs<PointerType>();
7167 if (PT->isObjCSelType()) {
7171 PointeeTy = PT->getPointeeType();
7173 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
7176 bool isReadOnly = false;
7177 // For historical/compatibility reasons, the read-only qualifier of the
7178 // pointee gets emitted _before_ the '^'. The read-only qualifier of
7179 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
7180 // Also, do not emit the 'r' for anything but the outermost type!
7181 if (isa<TypedefType>(T.getTypePtr())) {
7182 if (Options.IsOutermostType() && T.isConstQualified()) {
7186 } else if (Options.IsOutermostType()) {
7187 QualType P = PointeeTy;
7188 while (auto PT = P->getAs<PointerType>())
7189 P = PT->getPointeeType();
7190 if (P.isConstQualified()) {
7196 // Another legacy compatibility encoding. Some ObjC qualifier and type
7197 // combinations need to be rearranged.
7198 // Rewrite "in const" from "nr" to "rn"
7199 if (StringRef(S).endswith("nr"))
7200 S.replace(S.end()-2, S.end(), "rn");
7203 if (PointeeTy->isCharType()) {
7204 // char pointer types should be encoded as '*' unless it is a
7205 // type that has been typedef'd to 'BOOL'.
7206 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
7210 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
7211 // GCC binary compat: Need to convert "struct objc_class *" to "#".
7212 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
7216 // GCC binary compat: Need to convert "struct objc_object *" to "@".
7217 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
7224 getLegacyIntegralTypeEncoding(PointeeTy);
7226 ObjCEncOptions NewOptions;
7227 if (Options.ExpandPointedToStructures())
7228 NewOptions.setExpandStructures();
7229 getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
7230 /*Field=*/nullptr, NotEncodedT);
7234 case Type::ConstantArray:
7235 case Type::IncompleteArray:
7236 case Type::VariableArray: {
7237 const auto *AT = cast<ArrayType>(CT);
7239 if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
7240 // Incomplete arrays are encoded as a pointer to the array element.
7243 getObjCEncodingForTypeImpl(
7244 AT->getElementType(), S,
7245 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
7249 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
7250 S += llvm::utostr(CAT->getSize().getZExtValue());
7252 //Variable length arrays are encoded as a regular array with 0 elements.
7253 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
7254 "Unknown array type!");
7258 getObjCEncodingForTypeImpl(
7259 AT->getElementType(), S,
7260 Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
7267 case Type::FunctionNoProto:
7268 case Type::FunctionProto:
7272 case Type::Record: {
7273 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
7274 S += RDecl->isUnion() ? '(' : '{';
7275 // Anonymous structures print as '?'
7276 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
7278 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
7279 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
7280 llvm::raw_string_ostream OS(S);
7281 printTemplateArgumentList(OS, TemplateArgs.asArray(),
7282 getPrintingPolicy());
7287 if (Options.ExpandStructures()) {
7289 if (!RDecl->isUnion()) {
7290 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
7292 for (const auto *Field : RDecl->fields()) {
7295 S += Field->getNameAsString();
7299 // Special case bit-fields.
7300 if (Field->isBitField()) {
7301 getObjCEncodingForTypeImpl(Field->getType(), S,
7302 ObjCEncOptions().setExpandStructures(),
7305 QualType qt = Field->getType();
7306 getLegacyIntegralTypeEncoding(qt);
7307 getObjCEncodingForTypeImpl(
7309 ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
7315 S += RDecl->isUnion() ? ')' : '}';
7319 case Type::BlockPointer: {
7320 const auto *BT = T->castAs<BlockPointerType>();
7321 S += "@?"; // Unlike a pointer-to-function, which is "^?".
7322 if (Options.EncodeBlockParameters()) {
7323 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
7326 // Block return type
7327 getObjCEncodingForTypeImpl(FT->getReturnType(), S,
7328 Options.forComponentType(), FD, NotEncodedT);
7332 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
7333 for (const auto &I : FPT->param_types())
7334 getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
7342 case Type::ObjCObject: {
7343 // hack to match legacy encoding of *id and *Class
7344 QualType Ty = getObjCObjectPointerType(CT);
7345 if (Ty->isObjCIdType()) {
7346 S += "{objc_object=}";
7349 else if (Ty->isObjCClassType()) {
7350 S += "{objc_class=}";
7353 // TODO: Double check to make sure this intentionally falls through.
7357 case Type::ObjCInterface: {
7358 // Ignore protocol qualifiers when mangling at this level.
7359 // @encode(class_name)
7360 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
7362 S += OI->getObjCRuntimeNameAsString();
7363 if (Options.ExpandStructures()) {
7365 SmallVector<const ObjCIvarDecl*, 32> Ivars;
7366 DeepCollectObjCIvars(OI, true, Ivars);
7367 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
7368 const FieldDecl *Field = Ivars[i];
7369 if (Field->isBitField())
7370 getObjCEncodingForTypeImpl(Field->getType(), S,
7371 ObjCEncOptions().setExpandStructures(),
7374 getObjCEncodingForTypeImpl(Field->getType(), S,
7375 ObjCEncOptions().setExpandStructures(), FD,
7383 case Type::ObjCObjectPointer: {
7384 const auto *OPT = T->castAs<ObjCObjectPointerType>();
7385 if (OPT->isObjCIdType()) {
7390 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
7391 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
7392 // Since this is a binary compatibility issue, need to consult with
7393 // runtime folks. Fortunately, this is a *very* obscure construct.
7398 if (OPT->isObjCQualifiedIdType()) {
7399 getObjCEncodingForTypeImpl(
7401 Options.keepingOnly(ObjCEncOptions()
7402 .setExpandPointedToStructures()
7403 .setExpandStructures()),
7405 if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
7406 // Note that we do extended encoding of protocol qualifer list
7407 // Only when doing ivar or property encoding.
7409 for (const auto *I : OPT->quals()) {
7411 S += I->getObjCRuntimeNameAsString();
7420 if (OPT->getInterfaceDecl() &&
7421 (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
7423 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
7424 for (const auto *I : OPT->quals()) {
7426 S += I->getObjCRuntimeNameAsString();
7434 // gcc just blithely ignores member pointers.
7435 // FIXME: we should do better than that. 'M' is available.
7436 case Type::MemberPointer:
7437 // This matches gcc's encoding, even though technically it is insufficient.
7438 //FIXME. We should do a better job than gcc.
7440 case Type::ExtVector:
7441 // Until we have a coherent encoding of these three types, issue warning.
7446 case Type::ConstantMatrix:
7451 // We could see an undeduced auto type here during error recovery.
7454 case Type::DeducedTemplateSpecialization:
7459 #define ABSTRACT_TYPE(KIND, BASE)
7460 #define TYPE(KIND, BASE)
7461 #define DEPENDENT_TYPE(KIND, BASE) \
7463 #define NON_CANONICAL_TYPE(KIND, BASE) \
7465 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
7467 #include "clang/AST/TypeNodes.inc"
7468 llvm_unreachable("@encode for dependent type!");
7470 llvm_unreachable("bad type kind!");
7473 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
7475 const FieldDecl *FD,
7477 QualType *NotEncodedT) const {
7478 assert(RDecl && "Expected non-null RecordDecl");
7479 assert(!RDecl->isUnion() && "Should not be called for unions");
7480 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
7483 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
7484 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
7485 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
7488 for (const auto &BI : CXXRec->bases()) {
7489 if (!BI.isVirtual()) {
7490 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7491 if (base->isEmpty())
7493 uint64_t offs = toBits(layout.getBaseClassOffset(base));
7494 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7495 std::make_pair(offs, base));
7501 for (auto *Field : RDecl->fields()) {
7502 uint64_t offs = layout.getFieldOffset(i);
7503 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7504 std::make_pair(offs, Field));
7508 if (CXXRec && includeVBases) {
7509 for (const auto &BI : CXXRec->vbases()) {
7510 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
7511 if (base->isEmpty())
7513 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
7514 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
7515 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
7516 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
7517 std::make_pair(offs, base));
7523 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
7525 size = layout.getSize();
7529 uint64_t CurOffs = 0;
7531 std::multimap<uint64_t, NamedDecl *>::iterator
7532 CurLayObj = FieldOrBaseOffsets.begin();
7534 if (CXXRec && CXXRec->isDynamicClass() &&
7535 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
7538 std::string recname = CXXRec->getNameAsString();
7539 if (recname.empty()) recname = "?";
7545 CurOffs += getTypeSize(VoidPtrTy);
7549 if (!RDecl->hasFlexibleArrayMember()) {
7550 // Mark the end of the structure.
7551 uint64_t offs = toBits(size);
7552 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
7553 std::make_pair(offs, nullptr));
7556 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
7558 assert(CurOffs <= CurLayObj->first);
7559 if (CurOffs < CurLayObj->first) {
7560 uint64_t padding = CurLayObj->first - CurOffs;
7561 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7562 // packing/alignment of members is different that normal, in which case
7563 // the encoding will be out-of-sync with the real layout.
7564 // If the runtime switches to just consider the size of types without
7565 // taking into account alignment, we could make padding explicit in the
7566 // encoding (e.g. using arrays of chars). The encoding strings would be
7567 // longer then though.
7572 NamedDecl *dcl = CurLayObj->second;
7574 break; // reached end of structure.
7576 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
7577 // We expand the bases without their virtual bases since those are going
7578 // in the initial structure. Note that this differs from gcc which
7579 // expands virtual bases each time one is encountered in the hierarchy,
7580 // making the encoding type bigger than it really is.
7581 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7583 assert(!base->isEmpty());
7585 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
7588 const auto *field = cast<FieldDecl>(dcl);
7591 S += field->getNameAsString();
7595 if (field->isBitField()) {
7596 EncodeBitField(this, S, field->getType(), field);
7598 CurOffs += field->getBitWidthValue(*this);
7601 QualType qt = field->getType();
7602 getLegacyIntegralTypeEncoding(qt);
7603 getObjCEncodingForTypeImpl(
7604 qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
7607 CurOffs += getTypeSize(field->getType());
7614 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
7615 std::string& S) const {
7616 if (QT & Decl::OBJC_TQ_In)
7618 if (QT & Decl::OBJC_TQ_Inout)
7620 if (QT & Decl::OBJC_TQ_Out)
7622 if (QT & Decl::OBJC_TQ_Bycopy)
7624 if (QT & Decl::OBJC_TQ_Byref)
7626 if (QT & Decl::OBJC_TQ_Oneway)
7630 TypedefDecl *ASTContext::getObjCIdDecl() const {
7632 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
7633 T = getObjCObjectPointerType(T);
7634 ObjCIdDecl = buildImplicitTypedef(T, "id");
7639 TypedefDecl *ASTContext::getObjCSelDecl() const {
7641 QualType T = getPointerType(ObjCBuiltinSelTy);
7642 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
7647 TypedefDecl *ASTContext::getObjCClassDecl() const {
7648 if (!ObjCClassDecl) {
7649 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
7650 T = getObjCObjectPointerType(T);
7651 ObjCClassDecl = buildImplicitTypedef(T, "Class");
7653 return ObjCClassDecl;
7656 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7657 if (!ObjCProtocolClassDecl) {
7658 ObjCProtocolClassDecl
7659 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
7661 &Idents.get("Protocol"),
7662 /*typeParamList=*/nullptr,
7663 /*PrevDecl=*/nullptr,
7664 SourceLocation(), true);
7667 return ObjCProtocolClassDecl;
7670 //===----------------------------------------------------------------------===//
7671 // __builtin_va_list Construction Functions
7672 //===----------------------------------------------------------------------===//
7674 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7676 // typedef char* __builtin[_ms]_va_list;
7677 QualType T = Context->getPointerType(Context->CharTy);
7678 return Context->buildImplicitTypedef(T, Name);
7681 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7682 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7685 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7686 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
7689 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7690 // typedef void* __builtin_va_list;
7691 QualType T = Context->getPointerType(Context->VoidTy);
7692 return Context->buildImplicitTypedef(T, "__builtin_va_list");
7695 static TypedefDecl *
7696 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
7698 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
7699 if (Context->getLangOpts().CPlusPlus) {
7700 // namespace std { struct __va_list {
7702 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7703 Context->getTranslationUnitDecl(),
7704 /*Inline*/ false, SourceLocation(),
7705 SourceLocation(), &Context->Idents.get("std"),
7706 /*PrevDecl*/ nullptr);
7708 VaListTagDecl->setDeclContext(NS);
7711 VaListTagDecl->startDefinition();
7713 const size_t NumFields = 5;
7714 QualType FieldTypes[NumFields];
7715 const char *FieldNames[NumFields];
7718 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7719 FieldNames[0] = "__stack";
7722 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7723 FieldNames[1] = "__gr_top";
7726 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7727 FieldNames[2] = "__vr_top";
7730 FieldTypes[3] = Context->IntTy;
7731 FieldNames[3] = "__gr_offs";
7734 FieldTypes[4] = Context->IntTy;
7735 FieldNames[4] = "__vr_offs";
7738 for (unsigned i = 0; i < NumFields; ++i) {
7739 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7743 &Context->Idents.get(FieldNames[i]),
7744 FieldTypes[i], /*TInfo=*/nullptr,
7745 /*BitWidth=*/nullptr,
7748 Field->setAccess(AS_public);
7749 VaListTagDecl->addDecl(Field);
7751 VaListTagDecl->completeDefinition();
7752 Context->VaListTagDecl = VaListTagDecl;
7753 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7755 // } __builtin_va_list;
7756 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
7759 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7760 // typedef struct __va_list_tag {
7761 RecordDecl *VaListTagDecl;
7763 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7764 VaListTagDecl->startDefinition();
7766 const size_t NumFields = 5;
7767 QualType FieldTypes[NumFields];
7768 const char *FieldNames[NumFields];
7770 // unsigned char gpr;
7771 FieldTypes[0] = Context->UnsignedCharTy;
7772 FieldNames[0] = "gpr";
7774 // unsigned char fpr;
7775 FieldTypes[1] = Context->UnsignedCharTy;
7776 FieldNames[1] = "fpr";
7778 // unsigned short reserved;
7779 FieldTypes[2] = Context->UnsignedShortTy;
7780 FieldNames[2] = "reserved";
7782 // void* overflow_arg_area;
7783 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7784 FieldNames[3] = "overflow_arg_area";
7786 // void* reg_save_area;
7787 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7788 FieldNames[4] = "reg_save_area";
7791 for (unsigned i = 0; i < NumFields; ++i) {
7792 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7795 &Context->Idents.get(FieldNames[i]),
7796 FieldTypes[i], /*TInfo=*/nullptr,
7797 /*BitWidth=*/nullptr,
7800 Field->setAccess(AS_public);
7801 VaListTagDecl->addDecl(Field);
7803 VaListTagDecl->completeDefinition();
7804 Context->VaListTagDecl = VaListTagDecl;
7805 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7808 TypedefDecl *VaListTagTypedefDecl =
7809 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7811 QualType VaListTagTypedefType =
7812 Context->getTypedefType(VaListTagTypedefDecl);
7814 // typedef __va_list_tag __builtin_va_list[1];
7815 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7816 QualType VaListTagArrayType
7817 = Context->getConstantArrayType(VaListTagTypedefType,
7818 Size, nullptr, ArrayType::Normal, 0);
7819 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7822 static TypedefDecl *
7823 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
7824 // struct __va_list_tag {
7825 RecordDecl *VaListTagDecl;
7826 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7827 VaListTagDecl->startDefinition();
7829 const size_t NumFields = 4;
7830 QualType FieldTypes[NumFields];
7831 const char *FieldNames[NumFields];
7833 // unsigned gp_offset;
7834 FieldTypes[0] = Context->UnsignedIntTy;
7835 FieldNames[0] = "gp_offset";
7837 // unsigned fp_offset;
7838 FieldTypes[1] = Context->UnsignedIntTy;
7839 FieldNames[1] = "fp_offset";
7841 // void* overflow_arg_area;
7842 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7843 FieldNames[2] = "overflow_arg_area";
7845 // void* reg_save_area;
7846 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7847 FieldNames[3] = "reg_save_area";
7850 for (unsigned i = 0; i < NumFields; ++i) {
7851 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7855 &Context->Idents.get(FieldNames[i]),
7856 FieldTypes[i], /*TInfo=*/nullptr,
7857 /*BitWidth=*/nullptr,
7860 Field->setAccess(AS_public);
7861 VaListTagDecl->addDecl(Field);
7863 VaListTagDecl->completeDefinition();
7864 Context->VaListTagDecl = VaListTagDecl;
7865 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7869 // typedef struct __va_list_tag __builtin_va_list[1];
7870 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7871 QualType VaListTagArrayType = Context->getConstantArrayType(
7872 VaListTagType, Size, nullptr, ArrayType::Normal, 0);
7873 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7876 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7877 // typedef int __builtin_va_list[4];
7878 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
7879 QualType IntArrayType = Context->getConstantArrayType(
7880 Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
7881 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
7884 static TypedefDecl *
7885 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
7887 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
7888 if (Context->getLangOpts().CPlusPlus) {
7889 // namespace std { struct __va_list {
7891 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7892 Context->getTranslationUnitDecl(),
7893 /*Inline*/false, SourceLocation(),
7894 SourceLocation(), &Context->Idents.get("std"),
7895 /*PrevDecl*/ nullptr);
7897 VaListDecl->setDeclContext(NS);
7900 VaListDecl->startDefinition();
7903 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7907 &Context->Idents.get("__ap"),
7908 Context->getPointerType(Context->VoidTy),
7910 /*BitWidth=*/nullptr,
7913 Field->setAccess(AS_public);
7914 VaListDecl->addDecl(Field);
7917 VaListDecl->completeDefinition();
7918 Context->VaListTagDecl = VaListDecl;
7920 // typedef struct __va_list __builtin_va_list;
7921 QualType T = Context->getRecordType(VaListDecl);
7922 return Context->buildImplicitTypedef(T, "__builtin_va_list");
7925 static TypedefDecl *
7926 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
7927 // struct __va_list_tag {
7928 RecordDecl *VaListTagDecl;
7929 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7930 VaListTagDecl->startDefinition();
7932 const size_t NumFields = 4;
7933 QualType FieldTypes[NumFields];
7934 const char *FieldNames[NumFields];
7937 FieldTypes[0] = Context->LongTy;
7938 FieldNames[0] = "__gpr";
7941 FieldTypes[1] = Context->LongTy;
7942 FieldNames[1] = "__fpr";
7944 // void *__overflow_arg_area;
7945 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7946 FieldNames[2] = "__overflow_arg_area";
7948 // void *__reg_save_area;
7949 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7950 FieldNames[3] = "__reg_save_area";
7953 for (unsigned i = 0; i < NumFields; ++i) {
7954 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7958 &Context->Idents.get(FieldNames[i]),
7959 FieldTypes[i], /*TInfo=*/nullptr,
7960 /*BitWidth=*/nullptr,
7963 Field->setAccess(AS_public);
7964 VaListTagDecl->addDecl(Field);
7966 VaListTagDecl->completeDefinition();
7967 Context->VaListTagDecl = VaListTagDecl;
7968 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7972 // typedef __va_list_tag __builtin_va_list[1];
7973 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7974 QualType VaListTagArrayType = Context->getConstantArrayType(
7975 VaListTagType, Size, nullptr, ArrayType::Normal, 0);
7977 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
7980 static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
7981 // typedef struct __va_list_tag {
7982 RecordDecl *VaListTagDecl;
7983 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
7984 VaListTagDecl->startDefinition();
7986 const size_t NumFields = 3;
7987 QualType FieldTypes[NumFields];
7988 const char *FieldNames[NumFields];
7990 // void *CurrentSavedRegisterArea;
7991 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7992 FieldNames[0] = "__current_saved_reg_area_pointer";
7994 // void *SavedRegAreaEnd;
7995 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7996 FieldNames[1] = "__saved_reg_area_end_pointer";
7998 // void *OverflowArea;
7999 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
8000 FieldNames[2] = "__overflow_area_pointer";
8003 for (unsigned i = 0; i < NumFields; ++i) {
8004 FieldDecl *Field = FieldDecl::Create(
8005 const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
8006 SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
8009 /*Mutable=*/false, ICIS_NoInit);
8010 Field->setAccess(AS_public);
8011 VaListTagDecl->addDecl(Field);
8013 VaListTagDecl->completeDefinition();
8014 Context->VaListTagDecl = VaListTagDecl;
8015 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
8018 TypedefDecl *VaListTagTypedefDecl =
8019 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
8021 QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
8023 // typedef __va_list_tag __builtin_va_list[1];
8024 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
8025 QualType VaListTagArrayType = Context->getConstantArrayType(
8026 VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
8028 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
8031 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
8032 TargetInfo::BuiltinVaListKind Kind) {
8034 case TargetInfo::CharPtrBuiltinVaList:
8035 return CreateCharPtrBuiltinVaListDecl(Context);
8036 case TargetInfo::VoidPtrBuiltinVaList:
8037 return CreateVoidPtrBuiltinVaListDecl(Context);
8038 case TargetInfo::AArch64ABIBuiltinVaList:
8039 return CreateAArch64ABIBuiltinVaListDecl(Context);
8040 case TargetInfo::PowerABIBuiltinVaList:
8041 return CreatePowerABIBuiltinVaListDecl(Context);
8042 case TargetInfo::X86_64ABIBuiltinVaList:
8043 return CreateX86_64ABIBuiltinVaListDecl(Context);
8044 case TargetInfo::PNaClABIBuiltinVaList:
8045 return CreatePNaClABIBuiltinVaListDecl(Context);
8046 case TargetInfo::AAPCSABIBuiltinVaList:
8047 return CreateAAPCSABIBuiltinVaListDecl(Context);
8048 case TargetInfo::SystemZBuiltinVaList:
8049 return CreateSystemZBuiltinVaListDecl(Context);
8050 case TargetInfo::HexagonBuiltinVaList:
8051 return CreateHexagonBuiltinVaListDecl(Context);
8054 llvm_unreachable("Unhandled __builtin_va_list type kind");
8057 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
8058 if (!BuiltinVaListDecl) {
8059 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
8060 assert(BuiltinVaListDecl->isImplicit());
8063 return BuiltinVaListDecl;
8066 Decl *ASTContext::getVaListTagDecl() const {
8067 // Force the creation of VaListTagDecl by building the __builtin_va_list
8070 (void)getBuiltinVaListDecl();
8072 return VaListTagDecl;
8075 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
8076 if (!BuiltinMSVaListDecl)
8077 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
8079 return BuiltinMSVaListDecl;
8082 bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
8083 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
8086 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
8087 assert(ObjCConstantStringType.isNull() &&
8088 "'NSConstantString' type already set!");
8090 ObjCConstantStringType = getObjCInterfaceType(Decl);
8093 /// Retrieve the template name that corresponds to a non-empty
8096 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
8097 UnresolvedSetIterator End) const {
8098 unsigned size = End - Begin;
8099 assert(size > 1 && "set is not overloaded!");
8101 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
8102 size * sizeof(FunctionTemplateDecl*));
8103 auto *OT = new (memory) OverloadedTemplateStorage(size);
8105 NamedDecl **Storage = OT->getStorage();
8106 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
8108 assert(isa<FunctionTemplateDecl>(D) ||
8109 isa<UnresolvedUsingValueDecl>(D) ||
8110 (isa<UsingShadowDecl>(D) &&
8111 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
8115 return TemplateName(OT);
8118 /// Retrieve a template name representing an unqualified-id that has been
8119 /// assumed to name a template for ADL purposes.
8120 TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
8121 auto *OT = new (*this) AssumedTemplateStorage(Name);
8122 return TemplateName(OT);
8125 /// Retrieve the template name that represents a qualified
8126 /// template name such as \c std::vector.
8128 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
8129 bool TemplateKeyword,
8130 TemplateDecl *Template) const {
8131 assert(NNS && "Missing nested-name-specifier in qualified template name");
8133 // FIXME: Canonicalization?
8134 llvm::FoldingSetNodeID ID;
8135 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
8137 void *InsertPos = nullptr;
8138 QualifiedTemplateName *QTN =
8139 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8141 QTN = new (*this, alignof(QualifiedTemplateName))
8142 QualifiedTemplateName(NNS, TemplateKeyword, Template);
8143 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
8146 return TemplateName(QTN);
8149 /// Retrieve the template name that represents a dependent
8150 /// template name such as \c MetaFun::template apply.
8152 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8153 const IdentifierInfo *Name) const {
8154 assert((!NNS || NNS->isDependent()) &&
8155 "Nested name specifier must be dependent");
8157 llvm::FoldingSetNodeID ID;
8158 DependentTemplateName::Profile(ID, NNS, Name);
8160 void *InsertPos = nullptr;
8161 DependentTemplateName *QTN =
8162 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8165 return TemplateName(QTN);
8167 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8168 if (CanonNNS == NNS) {
8169 QTN = new (*this, alignof(DependentTemplateName))
8170 DependentTemplateName(NNS, Name);
8172 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
8173 QTN = new (*this, alignof(DependentTemplateName))
8174 DependentTemplateName(NNS, Name, Canon);
8175 DependentTemplateName *CheckQTN =
8176 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8177 assert(!CheckQTN && "Dependent type name canonicalization broken");
8181 DependentTemplateNames.InsertNode(QTN, InsertPos);
8182 return TemplateName(QTN);
8185 /// Retrieve the template name that represents a dependent
8186 /// template name such as \c MetaFun::template operator+.
8188 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
8189 OverloadedOperatorKind Operator) const {
8190 assert((!NNS || NNS->isDependent()) &&
8191 "Nested name specifier must be dependent");
8193 llvm::FoldingSetNodeID ID;
8194 DependentTemplateName::Profile(ID, NNS, Operator);
8196 void *InsertPos = nullptr;
8197 DependentTemplateName *QTN
8198 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8201 return TemplateName(QTN);
8203 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
8204 if (CanonNNS == NNS) {
8205 QTN = new (*this, alignof(DependentTemplateName))
8206 DependentTemplateName(NNS, Operator);
8208 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
8209 QTN = new (*this, alignof(DependentTemplateName))
8210 DependentTemplateName(NNS, Operator, Canon);
8212 DependentTemplateName *CheckQTN
8213 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
8214 assert(!CheckQTN && "Dependent template name canonicalization broken");
8218 DependentTemplateNames.InsertNode(QTN, InsertPos);
8219 return TemplateName(QTN);
8223 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
8224 TemplateName replacement) const {
8225 llvm::FoldingSetNodeID ID;
8226 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
8228 void *insertPos = nullptr;
8229 SubstTemplateTemplateParmStorage *subst
8230 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
8233 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
8234 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
8237 return TemplateName(subst);
8241 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
8242 const TemplateArgument &ArgPack) const {
8243 auto &Self = const_cast<ASTContext &>(*this);
8244 llvm::FoldingSetNodeID ID;
8245 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
8247 void *InsertPos = nullptr;
8248 SubstTemplateTemplateParmPackStorage *Subst
8249 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
8252 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
8253 ArgPack.pack_size(),
8254 ArgPack.pack_begin());
8255 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
8258 return TemplateName(Subst);
8261 /// getFromTargetType - Given one of the integer types provided by
8262 /// TargetInfo, produce the corresponding type. The unsigned @p Type
8263 /// is actually a value of type @c TargetInfo::IntType.
8264 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
8266 case TargetInfo::NoInt: return {};
8267 case TargetInfo::SignedChar: return SignedCharTy;
8268 case TargetInfo::UnsignedChar: return UnsignedCharTy;
8269 case TargetInfo::SignedShort: return ShortTy;
8270 case TargetInfo::UnsignedShort: return UnsignedShortTy;
8271 case TargetInfo::SignedInt: return IntTy;
8272 case TargetInfo::UnsignedInt: return UnsignedIntTy;
8273 case TargetInfo::SignedLong: return LongTy;
8274 case TargetInfo::UnsignedLong: return UnsignedLongTy;
8275 case TargetInfo::SignedLongLong: return LongLongTy;
8276 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
8279 llvm_unreachable("Unhandled TargetInfo::IntType value");
8282 //===----------------------------------------------------------------------===//
8284 //===----------------------------------------------------------------------===//
8286 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
8287 /// garbage collection attribute.
8289 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
8290 if (getLangOpts().getGC() == LangOptions::NonGC)
8291 return Qualifiers::GCNone;
8293 assert(getLangOpts().ObjC);
8294 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
8296 // Default behaviour under objective-C's gc is for ObjC pointers
8297 // (or pointers to them) be treated as though they were declared
8299 if (GCAttrs == Qualifiers::GCNone) {
8300 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
8301 return Qualifiers::Strong;
8302 else if (Ty->isPointerType())
8303 return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
8305 // It's not valid to set GC attributes on anything that isn't a
8308 QualType CT = Ty->getCanonicalTypeInternal();
8309 while (const auto *AT = dyn_cast<ArrayType>(CT))
8310 CT = AT->getElementType();
8311 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
8317 //===----------------------------------------------------------------------===//
8318 // Type Compatibility Testing
8319 //===----------------------------------------------------------------------===//
8321 /// areCompatVectorTypes - Return true if the two specified vector types are
8323 static bool areCompatVectorTypes(const VectorType *LHS,
8324 const VectorType *RHS) {
8325 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8326 return LHS->getElementType() == RHS->getElementType() &&
8327 LHS->getNumElements() == RHS->getNumElements();
8330 /// areCompatMatrixTypes - Return true if the two specified matrix types are
8332 static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
8333 const ConstantMatrixType *RHS) {
8334 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
8335 return LHS->getElementType() == RHS->getElementType() &&
8336 LHS->getNumRows() == RHS->getNumRows() &&
8337 LHS->getNumColumns() == RHS->getNumColumns();
8340 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
8341 QualType SecondVec) {
8342 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
8343 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
8345 if (hasSameUnqualifiedType(FirstVec, SecondVec))
8348 // Treat Neon vector types and most AltiVec vector types as if they are the
8349 // equivalent GCC vector types.
8350 const auto *First = FirstVec->castAs<VectorType>();
8351 const auto *Second = SecondVec->castAs<VectorType>();
8352 if (First->getNumElements() == Second->getNumElements() &&
8353 hasSameType(First->getElementType(), Second->getElementType()) &&
8354 First->getVectorKind() != VectorType::AltiVecPixel &&
8355 First->getVectorKind() != VectorType::AltiVecBool &&
8356 Second->getVectorKind() != VectorType::AltiVecPixel &&
8357 Second->getVectorKind() != VectorType::AltiVecBool)
8363 bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
8366 if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
8367 if (Attr->getAttrKind() == attr::ObjCOwnership)
8370 Ty = Attr->getModifiedType();
8372 // X *__strong (...)
8373 } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
8374 Ty = Paren->getInnerType();
8376 // We do not want to look through typedefs, typeof(expr),
8377 // typeof(type), or any other way that the type is somehow
8385 //===----------------------------------------------------------------------===//
8386 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
8387 //===----------------------------------------------------------------------===//
8389 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
8390 /// inheritance hierarchy of 'rProto'.
8392 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
8393 ObjCProtocolDecl *rProto) const {
8394 if (declaresSameEntity(lProto, rProto))
8396 for (auto *PI : rProto->protocols())
8397 if (ProtocolCompatibleWithProtocol(lProto, PI))
8402 /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
8403 /// Class<pr1, ...>.
8404 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
8405 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
8406 for (auto *lhsProto : lhs->quals()) {
8408 for (auto *rhsProto : rhs->quals()) {
8409 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
8420 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
8421 /// ObjCQualifiedIDType.
8422 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
8423 const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
8425 // Allow id<P..> and an 'id' in all cases.
8426 if (lhs->isObjCIdType() || rhs->isObjCIdType())
8429 // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
8430 if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
8431 rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
8434 if (lhs->isObjCQualifiedIdType()) {
8435 if (rhs->qual_empty()) {
8436 // If the RHS is a unqualified interface pointer "NSString*",
8437 // make sure we check the class hierarchy.
8438 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8439 for (auto *I : lhs->quals()) {
8440 // when comparing an id<P> on lhs with a static type on rhs,
8441 // see if static class implements all of id's protocols, directly or
8442 // through its super class and categories.
8443 if (!rhsID->ClassImplementsProtocol(I, true))
8447 // If there are no qualifiers and no interface, we have an 'id'.
8450 // Both the right and left sides have qualifiers.
8451 for (auto *lhsProto : lhs->quals()) {
8454 // when comparing an id<P> on lhs with a static type on rhs,
8455 // see if static class implements all of id's protocols, directly or
8456 // through its super class and categories.
8457 for (auto *rhsProto : rhs->quals()) {
8458 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8459 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8464 // If the RHS is a qualified interface pointer "NSString<P>*",
8465 // make sure we check the class hierarchy.
8466 if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
8467 for (auto *I : lhs->quals()) {
8468 // when comparing an id<P> on lhs with a static type on rhs,
8469 // see if static class implements all of id's protocols, directly or
8470 // through its super class and categories.
8471 if (rhsID->ClassImplementsProtocol(I, true)) {
8484 assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
8486 if (lhs->getInterfaceType()) {
8487 // If both the right and left sides have qualifiers.
8488 for (auto *lhsProto : lhs->quals()) {
8491 // when comparing an id<P> on rhs with a static type on lhs,
8492 // see if static class implements all of id's protocols, directly or
8493 // through its super class and categories.
8494 // First, lhs protocols in the qualifier list must be found, direct
8495 // or indirect in rhs's qualifier list or it is a mismatch.
8496 for (auto *rhsProto : rhs->quals()) {
8497 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8498 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8507 // Static class's protocols, or its super class or category protocols
8508 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
8509 if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
8510 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
8511 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
8512 // This is rather dubious but matches gcc's behavior. If lhs has
8513 // no type qualifier and its class has no static protocol(s)
8514 // assume that it is mismatch.
8515 if (LHSInheritedProtocols.empty() && lhs->qual_empty())
8517 for (auto *lhsProto : LHSInheritedProtocols) {
8519 for (auto *rhsProto : rhs->quals()) {
8520 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
8521 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
8535 /// canAssignObjCInterfaces - Return true if the two interface types are
8536 /// compatible for assignment from RHS to LHS. This handles validation of any
8537 /// protocol qualifiers on the LHS or RHS.
8538 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
8539 const ObjCObjectPointerType *RHSOPT) {
8540 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8541 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8543 // If either type represents the built-in 'id' type, return true.
8544 if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
8547 // Function object that propagates a successful result or handles
8549 auto finish = [&](bool succeeded) -> bool {
8553 if (!RHS->isKindOfType())
8556 // Strip off __kindof and protocol qualifiers, then check whether
8557 // we can assign the other way.
8558 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8559 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
8562 // Casts from or to id<P> are allowed when the other side has compatible
8564 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
8565 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
8568 // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
8569 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
8570 return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
8573 // Casts from Class to Class<Foo>, or vice-versa, are allowed.
8574 if (LHS->isObjCClass() && RHS->isObjCClass()) {
8578 // If we have 2 user-defined types, fall into that path.
8579 if (LHS->getInterface() && RHS->getInterface()) {
8580 return finish(canAssignObjCInterfaces(LHS, RHS));
8586 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
8587 /// for providing type-safety for objective-c pointers used to pass/return
8588 /// arguments in block literals. When passed as arguments, passing 'A*' where
8589 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
8590 /// not OK. For the return type, the opposite is not OK.
8591 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
8592 const ObjCObjectPointerType *LHSOPT,
8593 const ObjCObjectPointerType *RHSOPT,
8594 bool BlockReturnType) {
8596 // Function object that propagates a successful result or handles
8598 auto finish = [&](bool succeeded) -> bool {
8602 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
8603 if (!Expected->isKindOfType())
8606 // Strip off __kindof and protocol qualifiers, then check whether
8607 // we can assign the other way.
8608 return canAssignObjCInterfacesInBlockPointer(
8609 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
8610 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
8614 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
8617 if (LHSOPT->isObjCBuiltinType()) {
8618 return finish(RHSOPT->isObjCBuiltinType() ||
8619 RHSOPT->isObjCQualifiedIdType());
8622 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
8623 if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
8624 // Use for block parameters previous type checking for compatibility.
8625 return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
8626 // Or corrected type checking as in non-compat mode.
8627 (!BlockReturnType &&
8628 ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
8630 return finish(ObjCQualifiedIdTypesAreCompatible(
8631 (BlockReturnType ? LHSOPT : RHSOPT),
8632 (BlockReturnType ? RHSOPT : LHSOPT), false));
8635 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
8636 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
8637 if (LHS && RHS) { // We have 2 user-defined types.
8639 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
8640 return finish(BlockReturnType);
8641 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
8642 return finish(!BlockReturnType);
8650 /// Comparison routine for Objective-C protocols to be used with
8651 /// llvm::array_pod_sort.
8652 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8653 ObjCProtocolDecl * const *rhs) {
8654 return (*lhs)->getName().compare((*rhs)->getName());
8657 /// getIntersectionOfProtocols - This routine finds the intersection of set
8658 /// of protocols inherited from two distinct objective-c pointer objects with
8659 /// the given common base.
8660 /// It is used to build composite qualifier list of the composite type of
8661 /// the conditional expression involving two objective-c pointer objects.
8663 void getIntersectionOfProtocols(ASTContext &Context,
8664 const ObjCInterfaceDecl *CommonBase,
8665 const ObjCObjectPointerType *LHSOPT,
8666 const ObjCObjectPointerType *RHSOPT,
8667 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
8669 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8670 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8671 assert(LHS->getInterface() && "LHS must have an interface base");
8672 assert(RHS->getInterface() && "RHS must have an interface base");
8674 // Add all of the protocols for the LHS.
8675 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8677 // Start with the protocol qualifiers.
8678 for (auto proto : LHS->quals()) {
8679 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
8682 // Also add the protocols associated with the LHS interface.
8683 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8685 // Add all of the protocols for the RHS.
8686 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8688 // Start with the protocol qualifiers.
8689 for (auto proto : RHS->quals()) {
8690 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
8693 // Also add the protocols associated with the RHS interface.
8694 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8696 // Compute the intersection of the collected protocol sets.
8697 for (auto proto : LHSProtocolSet) {
8698 if (RHSProtocolSet.count(proto))
8699 IntersectionSet.push_back(proto);
8702 // Compute the set of protocols that is implied by either the common type or
8703 // the protocols within the intersection.
8704 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8705 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8707 // Remove any implied protocols from the list of inherited protocols.
8708 if (!ImpliedProtocols.empty()) {
8709 IntersectionSet.erase(
8710 std::remove_if(IntersectionSet.begin(),
8711 IntersectionSet.end(),
8712 [&](ObjCProtocolDecl *proto) -> bool {
8713 return ImpliedProtocols.count(proto) > 0;
8715 IntersectionSet.end());
8718 // Sort the remaining protocols by name.
8719 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8720 compareObjCProtocolsByName);
8723 /// Determine whether the first type is a subtype of the second.
8724 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8726 // Common case: two object pointers.
8727 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8728 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
8729 if (lhsOPT && rhsOPT)
8730 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8732 // Two block pointers.
8733 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8734 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
8735 if (lhsBlock && rhsBlock)
8736 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8738 // If either is an unqualified 'id' and the other is a block, it's
8740 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8741 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8747 // Check that the given Objective-C type argument lists are equivalent.
8748 static bool sameObjCTypeArgs(ASTContext &ctx,
8749 const ObjCInterfaceDecl *iface,
8750 ArrayRef<QualType> lhsArgs,
8751 ArrayRef<QualType> rhsArgs,
8753 if (lhsArgs.size() != rhsArgs.size())
8756 ObjCTypeParamList *typeParams = iface->getTypeParamList();
8757 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
8758 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8761 switch (typeParams->begin()[i]->getVariance()) {
8762 case ObjCTypeParamVariance::Invariant:
8764 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8765 rhsArgs[i].stripObjCKindOfType(ctx))) {
8770 case ObjCTypeParamVariance::Covariant:
8771 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8775 case ObjCTypeParamVariance::Contravariant:
8776 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8785 QualType ASTContext::areCommonBaseCompatible(
8786 const ObjCObjectPointerType *Lptr,
8787 const ObjCObjectPointerType *Rptr) {
8788 const ObjCObjectType *LHS = Lptr->getObjectType();
8789 const ObjCObjectType *RHS = Rptr->getObjectType();
8790 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8791 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
8793 if (!LDecl || !RDecl)
8796 // When either LHS or RHS is a kindof type, we should return a kindof type.
8797 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8799 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8801 // Follow the left-hand side up the class hierarchy until we either hit a
8802 // root or find the RHS. Record the ancestors in case we don't find it.
8803 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8806 // Record this ancestor. We'll need this if the common type isn't in the
8807 // path from the LHS to the root.
8808 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
8810 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8811 // Get the type arguments.
8812 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8813 bool anyChanges = false;
8814 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8815 // Both have type arguments, compare them.
8816 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8817 LHS->getTypeArgs(), RHS->getTypeArgs(),
8818 /*stripKindOf=*/true))
8820 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8821 // If only one has type arguments, the result will not have type
8827 // Compute the intersection of protocols.
8828 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8829 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8831 if (!Protocols.empty())
8834 // If anything in the LHS will have changed, build a new result type.
8835 // If we need to return a kindof type but LHS is not a kindof type, we
8836 // build a new result type.
8837 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
8838 QualType Result = getObjCInterfaceType(LHS->getInterface());
8839 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
8840 anyKindOf || LHS->isKindOfType());
8841 return getObjCObjectPointerType(Result);
8844 return getObjCObjectPointerType(QualType(LHS, 0));
8847 // Find the superclass.
8848 QualType LHSSuperType = LHS->getSuperClassType();
8849 if (LHSSuperType.isNull())
8852 LHS = LHSSuperType->castAs<ObjCObjectType>();
8855 // We didn't find anything by following the LHS to its root; now check
8856 // the RHS against the cached set of ancestors.
8858 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8859 if (KnownLHS != LHSAncestors.end()) {
8860 LHS = KnownLHS->second;
8862 // Get the type arguments.
8863 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8864 bool anyChanges = false;
8865 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8866 // Both have type arguments, compare them.
8867 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8868 LHS->getTypeArgs(), RHS->getTypeArgs(),
8869 /*stripKindOf=*/true))
8871 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8872 // If only one has type arguments, the result will not have type
8878 // Compute the intersection of protocols.
8879 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8880 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8882 if (!Protocols.empty())
8885 // If we need to return a kindof type but RHS is not a kindof type, we
8886 // build a new result type.
8887 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
8888 QualType Result = getObjCInterfaceType(RHS->getInterface());
8889 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
8890 anyKindOf || RHS->isKindOfType());
8891 return getObjCObjectPointerType(Result);
8894 return getObjCObjectPointerType(QualType(RHS, 0));
8897 // Find the superclass of the RHS.
8898 QualType RHSSuperType = RHS->getSuperClassType();
8899 if (RHSSuperType.isNull())
8902 RHS = RHSSuperType->castAs<ObjCObjectType>();
8908 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8909 const ObjCObjectType *RHS) {
8910 assert(LHS->getInterface() && "LHS is not an interface type");
8911 assert(RHS->getInterface() && "RHS is not an interface type");
8913 // Verify that the base decls are compatible: the RHS must be a subclass of
8915 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8916 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8920 // If the LHS has protocol qualifiers, determine whether all of them are
8921 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8923 if (LHS->getNumProtocols() > 0) {
8924 // OK if conversion of LHS to SuperClass results in narrowing of types
8925 // ; i.e., SuperClass may implement at least one of the protocols
8926 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8927 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8928 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8929 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8930 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8932 for (auto *RHSPI : RHS->quals())
8933 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
8934 // If there is no protocols associated with RHS, it is not a match.
8935 if (SuperClassInheritedProtocols.empty())
8938 for (const auto *LHSProto : LHS->quals()) {
8939 bool SuperImplementsProtocol = false;
8940 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8941 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8942 SuperImplementsProtocol = true;
8945 if (!SuperImplementsProtocol)
8950 // If the LHS is specialized, we may need to check type arguments.
8951 if (LHS->isSpecialized()) {
8952 // Follow the superclass chain until we've matched the LHS class in the
8953 // hierarchy. This substitutes type arguments through.
8954 const ObjCObjectType *RHSSuper = RHS;
8955 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8956 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8958 // If the RHS is specializd, compare type arguments.
8959 if (RHSSuper->isSpecialized() &&
8960 !sameObjCTypeArgs(*this, LHS->getInterface(),
8961 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
8962 /*stripKindOf=*/true)) {
8970 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8971 // get the "pointed to" types
8972 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8973 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
8975 if (!LHSOPT || !RHSOPT)
8978 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8979 canAssignObjCInterfaces(RHSOPT, LHSOPT);
8982 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8983 return canAssignObjCInterfaces(
8984 getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
8985 getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
8988 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
8989 /// both shall have the identically qualified version of a compatible type.
8990 /// C99 6.2.7p1: Two types have compatible types if their types are the
8991 /// same. See 6.7.[2,3,5] for additional rules.
8992 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8993 bool CompareUnqualified) {
8994 if (getLangOpts().CPlusPlus)
8995 return hasSameType(LHS, RHS);
8997 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
9000 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
9001 return typesAreCompatible(LHS, RHS);
9004 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
9005 return !mergeTypes(LHS, RHS, true).isNull();
9008 /// mergeTransparentUnionType - if T is a transparent union type and a member
9009 /// of T is compatible with SubType, return the merged type, else return
9011 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
9012 bool OfBlockPointer,
9014 if (const RecordType *UT = T->getAsUnionType()) {
9015 RecordDecl *UD = UT->getDecl();
9016 if (UD->hasAttr<TransparentUnionAttr>()) {
9017 for (const auto *I : UD->fields()) {
9018 QualType ET = I->getType().getUnqualifiedType();
9019 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
9029 /// mergeFunctionParameterTypes - merge two types which appear as function
9031 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
9032 bool OfBlockPointer,
9034 // GNU extension: two types are compatible if they appear as a function
9035 // argument, one of the types is a transparent union type and the other
9036 // type is compatible with a union member
9037 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
9039 if (!lmerge.isNull())
9042 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
9044 if (!rmerge.isNull())
9047 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
9050 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
9051 bool OfBlockPointer, bool Unqualified,
9053 const auto *lbase = lhs->castAs<FunctionType>();
9054 const auto *rbase = rhs->castAs<FunctionType>();
9055 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
9056 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
9057 bool allLTypes = true;
9058 bool allRTypes = true;
9060 // Check return type
9062 if (OfBlockPointer) {
9063 QualType RHS = rbase->getReturnType();
9064 QualType LHS = lbase->getReturnType();
9065 bool UnqualifiedResult = Unqualified;
9066 if (!UnqualifiedResult)
9067 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
9068 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
9071 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
9073 if (retType.isNull())
9077 retType = retType.getUnqualifiedType();
9079 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
9080 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
9082 LRetType = LRetType.getUnqualifiedType();
9083 RRetType = RRetType.getUnqualifiedType();
9086 if (getCanonicalType(retType) != LRetType)
9088 if (getCanonicalType(retType) != RRetType)
9091 // FIXME: double check this
9092 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
9093 // rbase->getRegParmAttr() != 0 &&
9094 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
9095 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
9096 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
9098 // Compatible functions must have compatible calling conventions
9099 if (lbaseInfo.getCC() != rbaseInfo.getCC())
9102 // Regparm is part of the calling convention.
9103 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
9105 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
9108 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
9110 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
9112 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
9115 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
9116 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
9118 if (lbaseInfo.getNoReturn() != NoReturn)
9120 if (rbaseInfo.getNoReturn() != NoReturn)
9123 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
9125 if (lproto && rproto) { // two C99 style function prototypes
9127 (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
9128 "C++ shouldn't be here");
9129 // Compatible functions must have the same number of parameters
9130 if (lproto->getNumParams() != rproto->getNumParams())
9133 // Variadic and non-variadic functions aren't compatible
9134 if (lproto->isVariadic() != rproto->isVariadic())
9137 if (lproto->getMethodQuals() != rproto->getMethodQuals())
9140 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
9141 bool canUseLeft, canUseRight;
9142 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
9151 // Check parameter type compatibility
9152 SmallVector<QualType, 10> types;
9153 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
9154 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
9155 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
9156 QualType paramType = mergeFunctionParameterTypes(
9157 lParamType, rParamType, OfBlockPointer, Unqualified);
9158 if (paramType.isNull())
9162 paramType = paramType.getUnqualifiedType();
9164 types.push_back(paramType);
9166 lParamType = lParamType.getUnqualifiedType();
9167 rParamType = rParamType.getUnqualifiedType();
9170 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
9172 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
9176 if (allLTypes) return lhs;
9177 if (allRTypes) return rhs;
9179 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
9180 EPI.ExtInfo = einfo;
9181 EPI.ExtParameterInfos =
9182 newParamInfos.empty() ? nullptr : newParamInfos.data();
9183 return getFunctionType(retType, types, EPI);
9186 if (lproto) allRTypes = false;
9187 if (rproto) allLTypes = false;
9189 const FunctionProtoType *proto = lproto ? lproto : rproto;
9191 assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
9192 if (proto->isVariadic())
9194 // Check that the types are compatible with the types that
9195 // would result from default argument promotions (C99 6.7.5.3p15).
9196 // The only types actually affected are promotable integer
9197 // types and floats, which would be passed as a different
9198 // type depending on whether the prototype is visible.
9199 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
9200 QualType paramTy = proto->getParamType(i);
9202 // Look at the converted type of enum types, since that is the type used
9203 // to pass enum values.
9204 if (const auto *Enum = paramTy->getAs<EnumType>()) {
9205 paramTy = Enum->getDecl()->getIntegerType();
9206 if (paramTy.isNull())
9210 if (paramTy->isPromotableIntegerType() ||
9211 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
9215 if (allLTypes) return lhs;
9216 if (allRTypes) return rhs;
9218 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
9219 EPI.ExtInfo = einfo;
9220 return getFunctionType(retType, proto->getParamTypes(), EPI);
9223 if (allLTypes) return lhs;
9224 if (allRTypes) return rhs;
9225 return getFunctionNoProtoType(retType, einfo);
9228 /// Given that we have an enum type and a non-enum type, try to merge them.
9229 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
9230 QualType other, bool isBlockReturnType) {
9231 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
9232 // a signed integer type, or an unsigned integer type.
9233 // Compatibility is based on the underlying type, not the promotion
9235 QualType underlyingType = ET->getDecl()->getIntegerType();
9236 if (underlyingType.isNull())
9238 if (Context.hasSameType(underlyingType, other))
9241 // In block return types, we're more permissive and accept any
9242 // integral type of the same size.
9243 if (isBlockReturnType && other->isIntegerType() &&
9244 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
9250 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
9251 bool OfBlockPointer,
9252 bool Unqualified, bool BlockReturnType) {
9253 // C++ [expr]: If an expression initially has the type "reference to T", the
9254 // type is adjusted to "T" prior to any further analysis, the expression
9255 // designates the object or function denoted by the reference, and the
9256 // expression is an lvalue unless the reference is an rvalue reference and
9257 // the expression is a function call (possibly inside parentheses).
9258 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
9259 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
9262 LHS = LHS.getUnqualifiedType();
9263 RHS = RHS.getUnqualifiedType();
9266 QualType LHSCan = getCanonicalType(LHS),
9267 RHSCan = getCanonicalType(RHS);
9269 // If two types are identical, they are compatible.
9270 if (LHSCan == RHSCan)
9273 // If the qualifiers are different, the types aren't compatible... mostly.
9274 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9275 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9276 if (LQuals != RQuals) {
9277 // If any of these qualifiers are different, we have a type
9279 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9280 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
9281 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
9282 LQuals.hasUnaligned() != RQuals.hasUnaligned())
9285 // Exactly one GC qualifier difference is allowed: __strong is
9286 // okay if the other type has no GC qualifier but is an Objective
9287 // C object pointer (i.e. implicitly strong by default). We fix
9288 // this by pretending that the unqualified type was actually
9289 // qualified __strong.
9290 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9291 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9292 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9294 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9297 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
9298 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
9300 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
9301 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
9306 // Okay, qualifiers are equal.
9308 Type::TypeClass LHSClass = LHSCan->getTypeClass();
9309 Type::TypeClass RHSClass = RHSCan->getTypeClass();
9311 // We want to consider the two function types to be the same for these
9312 // comparisons, just force one to the other.
9313 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
9314 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
9316 // Same as above for arrays
9317 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
9318 LHSClass = Type::ConstantArray;
9319 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
9320 RHSClass = Type::ConstantArray;
9322 // ObjCInterfaces are just specialized ObjCObjects.
9323 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
9324 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
9326 // Canonicalize ExtVector -> Vector.
9327 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
9328 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
9330 // If the canonical type classes don't match.
9331 if (LHSClass != RHSClass) {
9332 // Note that we only have special rules for turning block enum
9333 // returns into block int returns, not vice-versa.
9334 if (const auto *ETy = LHS->getAs<EnumType>()) {
9335 return mergeEnumWithInteger(*this, ETy, RHS, false);
9337 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
9338 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
9340 // allow block pointer type to match an 'id' type.
9341 if (OfBlockPointer && !BlockReturnType) {
9342 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
9344 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
9351 // The canonical type classes match.
9353 #define TYPE(Class, Base)
9354 #define ABSTRACT_TYPE(Class, Base)
9355 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
9356 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
9357 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
9358 #include "clang/AST/TypeNodes.inc"
9359 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
9362 case Type::DeducedTemplateSpecialization:
9363 case Type::LValueReference:
9364 case Type::RValueReference:
9365 case Type::MemberPointer:
9366 llvm_unreachable("C++ should never be in mergeTypes");
9368 case Type::ObjCInterface:
9369 case Type::IncompleteArray:
9370 case Type::VariableArray:
9371 case Type::FunctionProto:
9372 case Type::ExtVector:
9373 llvm_unreachable("Types are eliminated above");
9377 // Merge two pointer types, while trying to preserve typedef info
9378 QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
9379 QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
9381 LHSPointee = LHSPointee.getUnqualifiedType();
9382 RHSPointee = RHSPointee.getUnqualifiedType();
9384 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
9386 if (ResultType.isNull())
9388 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9390 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9392 return getPointerType(ResultType);
9394 case Type::BlockPointer:
9396 // Merge two block pointer types, while trying to preserve typedef info
9397 QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
9398 QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
9400 LHSPointee = LHSPointee.getUnqualifiedType();
9401 RHSPointee = RHSPointee.getUnqualifiedType();
9403 if (getLangOpts().OpenCL) {
9404 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
9405 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
9406 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
9407 // 6.12.5) thus the following check is asymmetric.
9408 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
9410 LHSPteeQual.removeAddressSpace();
9411 RHSPteeQual.removeAddressSpace();
9413 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
9415 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
9417 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
9419 if (ResultType.isNull())
9421 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
9423 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
9425 return getBlockPointerType(ResultType);
9429 // Merge two pointer types, while trying to preserve typedef info
9430 QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
9431 QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
9433 LHSValue = LHSValue.getUnqualifiedType();
9434 RHSValue = RHSValue.getUnqualifiedType();
9436 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
9438 if (ResultType.isNull())
9440 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
9442 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
9444 return getAtomicType(ResultType);
9446 case Type::ConstantArray:
9448 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
9449 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
9450 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
9453 QualType LHSElem = getAsArrayType(LHS)->getElementType();
9454 QualType RHSElem = getAsArrayType(RHS)->getElementType();
9456 LHSElem = LHSElem.getUnqualifiedType();
9457 RHSElem = RHSElem.getUnqualifiedType();
9460 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
9461 if (ResultType.isNull())
9464 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
9465 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
9467 // If either side is a variable array, and both are complete, check whether
9468 // the current dimension is definite.
9470 auto SizeFetch = [this](const VariableArrayType* VAT,
9471 const ConstantArrayType* CAT)
9472 -> std::pair<bool,llvm::APInt> {
9474 llvm::APSInt TheInt;
9475 Expr *E = VAT->getSizeExpr();
9476 if (E && E->isIntegerConstantExpr(TheInt, *this))
9477 return std::make_pair(true, TheInt);
9479 return std::make_pair(false, TheInt);
9481 return std::make_pair(true, CAT->getSize());
9483 return std::make_pair(false, llvm::APInt());
9487 bool HaveLSize, HaveRSize;
9488 llvm::APInt LSize, RSize;
9489 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
9490 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
9491 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
9492 return {}; // Definite, but unequal, array dimension
9495 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9497 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9500 return getConstantArrayType(ResultType, LCAT->getSize(),
9501 LCAT->getSizeExpr(),
9502 ArrayType::ArraySizeModifier(), 0);
9504 return getConstantArrayType(ResultType, RCAT->getSize(),
9505 RCAT->getSizeExpr(),
9506 ArrayType::ArraySizeModifier(), 0);
9507 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
9509 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
9512 // FIXME: This isn't correct! But tricky to implement because
9513 // the array's size has to be the size of LHS, but the type
9514 // has to be different.
9518 // FIXME: This isn't correct! But tricky to implement because
9519 // the array's size has to be the size of RHS, but the type
9520 // has to be different.
9523 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
9524 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
9525 return getIncompleteArrayType(ResultType,
9526 ArrayType::ArraySizeModifier(), 0);
9528 case Type::FunctionNoProto:
9529 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
9534 // Only exactly equal builtin types are compatible, which is tested above.
9537 // Distinct complex types are incompatible.
9540 // FIXME: The merged type should be an ExtVector!
9541 if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
9542 RHSCan->castAs<VectorType>()))
9545 case Type::ConstantMatrix:
9546 if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
9547 RHSCan->castAs<ConstantMatrixType>()))
9550 case Type::ObjCObject: {
9551 // Check if the types are assignment compatible.
9552 // FIXME: This should be type compatibility, e.g. whether
9553 // "LHS x; RHS x;" at global scope is legal.
9554 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
9555 RHS->castAs<ObjCObjectType>()))
9559 case Type::ObjCObjectPointer:
9560 if (OfBlockPointer) {
9561 if (canAssignObjCInterfacesInBlockPointer(
9562 LHS->castAs<ObjCObjectPointerType>(),
9563 RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
9567 if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
9568 RHS->castAs<ObjCObjectPointerType>()))
9572 assert(LHS != RHS &&
9573 "Equivalent pipe types should have already been handled!");
9575 case Type::ExtInt: {
9576 // Merge two ext-int types, while trying to preserve typedef info.
9577 bool LHSUnsigned = LHS->castAs<ExtIntType>()->isUnsigned();
9578 bool RHSUnsigned = RHS->castAs<ExtIntType>()->isUnsigned();
9579 unsigned LHSBits = LHS->castAs<ExtIntType>()->getNumBits();
9580 unsigned RHSBits = RHS->castAs<ExtIntType>()->getNumBits();
9582 // Like unsigned/int, shouldn't have a type if they dont match.
9583 if (LHSUnsigned != RHSUnsigned)
9586 if (LHSBits != RHSBits)
9592 llvm_unreachable("Invalid Type::Class!");
9595 bool ASTContext::mergeExtParameterInfo(
9596 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
9597 bool &CanUseFirst, bool &CanUseSecond,
9598 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
9599 assert(NewParamInfos.empty() && "param info list not empty");
9600 CanUseFirst = CanUseSecond = true;
9601 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
9602 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
9604 // Fast path: if the first type doesn't have ext parameter infos,
9605 // we match if and only if the second type also doesn't have them.
9606 if (!FirstHasInfo && !SecondHasInfo)
9609 bool NeedParamInfo = false;
9610 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
9611 : SecondFnType->getExtParameterInfos().size();
9613 for (size_t I = 0; I < E; ++I) {
9614 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
9616 FirstParam = FirstFnType->getExtParameterInfo(I);
9618 SecondParam = SecondFnType->getExtParameterInfo(I);
9620 // Cannot merge unless everything except the noescape flag matches.
9621 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
9624 bool FirstNoEscape = FirstParam.isNoEscape();
9625 bool SecondNoEscape = SecondParam.isNoEscape();
9626 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
9627 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
9628 if (NewParamInfos.back().getOpaqueValue())
9629 NeedParamInfo = true;
9630 if (FirstNoEscape != IsNoEscape)
9631 CanUseFirst = false;
9632 if (SecondNoEscape != IsNoEscape)
9633 CanUseSecond = false;
9637 NewParamInfos.clear();
9642 void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
9643 ObjCLayouts[CD] = nullptr;
9646 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
9647 /// 'RHS' attributes and returns the merged version; including for function
9649 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
9650 QualType LHSCan = getCanonicalType(LHS),
9651 RHSCan = getCanonicalType(RHS);
9652 // If two types are identical, they are compatible.
9653 if (LHSCan == RHSCan)
9655 if (RHSCan->isFunctionType()) {
9656 if (!LHSCan->isFunctionType())
9658 QualType OldReturnType =
9659 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
9660 QualType NewReturnType =
9661 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
9662 QualType ResReturnType =
9663 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
9664 if (ResReturnType.isNull())
9666 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9667 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9668 // In either case, use OldReturnType to build the new function type.
9669 const auto *F = LHS->castAs<FunctionType>();
9670 if (const auto *FPT = cast<FunctionProtoType>(F)) {
9671 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9672 EPI.ExtInfo = getFunctionExtInfo(LHS);
9673 QualType ResultType =
9674 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
9681 // If the qualifiers are different, the types can still be merged.
9682 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9683 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9684 if (LQuals != RQuals) {
9685 // If any of these qualifiers are different, we have a type mismatch.
9686 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9687 LQuals.getAddressSpace() != RQuals.getAddressSpace())
9690 // Exactly one GC qualifier difference is allowed: __strong is
9691 // okay if the other type has no GC qualifier but is an Objective
9692 // C object pointer (i.e. implicitly strong by default). We fix
9693 // this by pretending that the unqualified type was actually
9694 // qualified __strong.
9695 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9696 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9697 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
9699 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
9702 if (GC_L == Qualifiers::Strong)
9704 if (GC_R == Qualifiers::Strong)
9709 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9710 QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
9711 QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
9712 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9713 if (ResQT == LHSBaseQT)
9715 if (ResQT == RHSBaseQT)
9721 //===----------------------------------------------------------------------===//
9722 // Integer Predicates
9723 //===----------------------------------------------------------------------===//
9725 unsigned ASTContext::getIntWidth(QualType T) const {
9726 if (const auto *ET = T->getAs<EnumType>())
9727 T = ET->getDecl()->getIntegerType();
9728 if (T->isBooleanType())
9730 if(const auto *EIT = T->getAs<ExtIntType>())
9731 return EIT->getNumBits();
9732 // For builtin types, just use the standard type sizing method
9733 return (unsigned)getTypeSize(T);
9736 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
9737 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9740 // Turn <4 x signed int> -> <4 x unsigned int>
9741 if (const auto *VTy = T->getAs<VectorType>())
9742 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
9743 VTy->getNumElements(), VTy->getVectorKind());
9745 // For enums, we return the unsigned version of the base type.
9746 if (const auto *ETy = T->getAs<EnumType>())
9747 T = ETy->getDecl()->getIntegerType();
9749 switch (T->castAs<BuiltinType>()->getKind()) {
9750 case BuiltinType::Char_S:
9751 case BuiltinType::SChar:
9752 return UnsignedCharTy;
9753 case BuiltinType::Short:
9754 return UnsignedShortTy;
9755 case BuiltinType::Int:
9756 return UnsignedIntTy;
9757 case BuiltinType::Long:
9758 return UnsignedLongTy;
9759 case BuiltinType::LongLong:
9760 return UnsignedLongLongTy;
9761 case BuiltinType::Int128:
9762 return UnsignedInt128Ty;
9764 case BuiltinType::ShortAccum:
9765 return UnsignedShortAccumTy;
9766 case BuiltinType::Accum:
9767 return UnsignedAccumTy;
9768 case BuiltinType::LongAccum:
9769 return UnsignedLongAccumTy;
9770 case BuiltinType::SatShortAccum:
9771 return SatUnsignedShortAccumTy;
9772 case BuiltinType::SatAccum:
9773 return SatUnsignedAccumTy;
9774 case BuiltinType::SatLongAccum:
9775 return SatUnsignedLongAccumTy;
9776 case BuiltinType::ShortFract:
9777 return UnsignedShortFractTy;
9778 case BuiltinType::Fract:
9779 return UnsignedFractTy;
9780 case BuiltinType::LongFract:
9781 return UnsignedLongFractTy;
9782 case BuiltinType::SatShortFract:
9783 return SatUnsignedShortFractTy;
9784 case BuiltinType::SatFract:
9785 return SatUnsignedFractTy;
9786 case BuiltinType::SatLongFract:
9787 return SatUnsignedLongFractTy;
9789 llvm_unreachable("Unexpected signed integer or fixed point type");
9793 ASTMutationListener::~ASTMutationListener() = default;
9795 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9796 QualType ReturnType) {}
9798 //===----------------------------------------------------------------------===//
9799 // Builtin Type Computation
9800 //===----------------------------------------------------------------------===//
9802 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
9803 /// pointer over the consumed characters. This returns the resultant type. If
9804 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9805 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9806 /// a vector of "i*".
9808 /// RequiresICE is filled in on return to indicate whether the value is required
9809 /// to be an Integer Constant Expression.
9810 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
9811 ASTContext::GetBuiltinTypeError &Error,
9813 bool AllowTypeModifiers) {
9816 bool Signed = false, Unsigned = false;
9817 RequiresICE = false;
9819 // Read the prefixed modifiers first.
9822 bool IsSpecial = false;
9826 default: Done = true; --Str; break;
9831 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9832 assert(!Signed && "Can't use 'S' modifier multiple times!");
9836 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
9837 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
9841 assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
9842 assert(HowLong <= 2 && "Can't have LLLL modifier");
9846 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
9847 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9848 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
9852 if (Context.getTargetInfo().getLongWidth() == 32)
9856 // This modifier represents int64 type.
9857 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9858 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
9862 switch (Context.getTargetInfo().getInt64Type()) {
9864 llvm_unreachable("Unexpected integer type");
9865 case TargetInfo::SignedLong:
9868 case TargetInfo::SignedLongLong:
9874 // This modifier represents int32 type.
9875 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9876 assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
9880 switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
9882 llvm_unreachable("Unexpected integer type");
9883 case TargetInfo::SignedInt:
9886 case TargetInfo::SignedLong:
9889 case TargetInfo::SignedLongLong:
9895 assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
9896 assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
9900 if (Context.getLangOpts().OpenCL)
9910 // Read the base type.
9912 default: llvm_unreachable("Unknown builtin type letter!");
9914 assert(HowLong == 0 && !Signed && !Unsigned &&
9915 "Bad modifiers used with 'y'!");
9916 Type = Context.BFloat16Ty;
9919 assert(HowLong == 0 && !Signed && !Unsigned &&
9920 "Bad modifiers used with 'v'!");
9921 Type = Context.VoidTy;
9924 assert(HowLong == 0 && !Signed && !Unsigned &&
9925 "Bad modifiers used with 'h'!");
9926 Type = Context.HalfTy;
9929 assert(HowLong == 0 && !Signed && !Unsigned &&
9930 "Bad modifiers used with 'f'!");
9931 Type = Context.FloatTy;
9934 assert(HowLong < 3 && !Signed && !Unsigned &&
9935 "Bad modifiers used with 'd'!");
9937 Type = Context.LongDoubleTy;
9938 else if (HowLong == 2)
9939 Type = Context.Float128Ty;
9941 Type = Context.DoubleTy;
9944 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9946 Type = Context.UnsignedShortTy;
9948 Type = Context.ShortTy;
9952 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9953 else if (HowLong == 2)
9954 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9955 else if (HowLong == 1)
9956 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9958 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9961 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9963 Type = Context.SignedCharTy;
9965 Type = Context.UnsignedCharTy;
9967 Type = Context.CharTy;
9969 case 'b': // boolean
9970 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9971 Type = Context.BoolTy;
9973 case 'z': // size_t.
9974 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9975 Type = Context.getSizeType();
9977 case 'w': // wchar_t.
9978 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9979 Type = Context.getWideCharType();
9982 Type = Context.getCFConstantStringType();
9985 Type = Context.getObjCIdType();
9988 Type = Context.getObjCSelType();
9991 Type = Context.getObjCSuperType();
9994 Type = Context.getBuiltinVaListType();
9995 assert(!Type.isNull() && "builtin va list type not initialized!");
9998 // This is a "reference" to a va_list; however, what exactly
9999 // this means depends on how va_list is defined. There are two
10000 // different kinds of va_list: ones passed by value, and ones
10001 // passed by reference. An example of a by-value va_list is
10002 // x86, where va_list is a char*. An example of by-ref va_list
10003 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
10004 // we want this argument to be a char*&; for x86-64, we want
10005 // it to be a __va_list_tag*.
10006 Type = Context.getBuiltinVaListType();
10007 assert(!Type.isNull() && "builtin va list type not initialized!");
10008 if (Type->isArrayType())
10009 Type = Context.getArrayDecayedType(Type);
10011 Type = Context.getLValueReferenceType(Type);
10015 unsigned NumElements = strtoul(Str, &End, 10);
10016 assert(End != Str && "Missing vector size");
10019 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10020 RequiresICE, false);
10021 assert(!RequiresICE && "Can't require vector ICE");
10023 Type = Context.getScalableVectorType(ElementType, NumElements);
10028 unsigned NumElements = strtoul(Str, &End, 10);
10029 assert(End != Str && "Missing vector size");
10032 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
10033 RequiresICE, false);
10034 assert(!RequiresICE && "Can't require vector ICE");
10036 // TODO: No way to make AltiVec vectors in builtins yet.
10037 Type = Context.getVectorType(ElementType, NumElements,
10038 VectorType::GenericVector);
10044 unsigned NumElements = strtoul(Str, &End, 10);
10045 assert(End != Str && "Missing vector size");
10049 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10051 Type = Context.getExtVectorType(ElementType, NumElements);
10055 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
10057 assert(!RequiresICE && "Can't require complex ICE");
10058 Type = Context.getComplexType(ElementType);
10062 Type = Context.getPointerDiffType();
10065 Type = Context.getFILEType();
10066 if (Type.isNull()) {
10067 Error = ASTContext::GE_Missing_stdio;
10073 Type = Context.getsigjmp_bufType();
10075 Type = Context.getjmp_bufType();
10077 if (Type.isNull()) {
10078 Error = ASTContext::GE_Missing_setjmp;
10083 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
10084 Type = Context.getucontext_tType();
10086 if (Type.isNull()) {
10087 Error = ASTContext::GE_Missing_ucontext;
10092 Type = Context.getProcessIDType();
10096 // If there are modifiers and if we're allowed to parse them, go for it.
10097 Done = !AllowTypeModifiers;
10099 switch (char c = *Str++) {
10100 default: Done = true; --Str; break;
10103 // Both pointers and references can have their pointee types
10104 // qualified with an address space.
10106 unsigned AddrSpace = strtoul(Str, &End, 10);
10108 // Note AddrSpace == 0 is not the same as an unspecified address space.
10109 Type = Context.getAddrSpaceQualType(
10111 Context.getLangASForBuiltinAddressSpace(AddrSpace));
10115 Type = Context.getPointerType(Type);
10117 Type = Context.getLValueReferenceType(Type);
10120 // FIXME: There's no way to have a built-in with an rvalue ref arg.
10122 Type = Type.withConst();
10125 Type = Context.getVolatileType(Type);
10128 Type = Type.withRestrict();
10133 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
10134 "Integer constant 'I' type must be an integer");
10139 /// GetBuiltinType - Return the type for the specified builtin.
10140 QualType ASTContext::GetBuiltinType(unsigned Id,
10141 GetBuiltinTypeError &Error,
10142 unsigned *IntegerConstantArgs) const {
10143 const char *TypeStr = BuiltinInfo.getTypeString(Id);
10144 if (TypeStr[0] == '\0') {
10145 Error = GE_Missing_type;
10149 SmallVector<QualType, 8> ArgTypes;
10151 bool RequiresICE = false;
10153 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
10154 RequiresICE, true);
10155 if (Error != GE_None)
10158 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
10160 while (TypeStr[0] && TypeStr[0] != '.') {
10161 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
10162 if (Error != GE_None)
10165 // If this argument is required to be an IntegerConstantExpression and the
10166 // caller cares, fill in the bitmask we return.
10167 if (RequiresICE && IntegerConstantArgs)
10168 *IntegerConstantArgs |= 1 << ArgTypes.size();
10170 // Do array -> pointer decay. The builtin should use the decayed type.
10171 if (Ty->isArrayType())
10172 Ty = getArrayDecayedType(Ty);
10174 ArgTypes.push_back(Ty);
10177 if (Id == Builtin::BI__GetExceptionInfo)
10180 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
10181 "'.' should only occur at end of builtin type list!");
10183 bool Variadic = (TypeStr[0] == '.');
10185 FunctionType::ExtInfo EI(getDefaultCallingConvention(
10186 Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
10187 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
10190 // We really shouldn't be making a no-proto type here.
10191 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
10192 return getFunctionNoProtoType(ResType, EI);
10194 FunctionProtoType::ExtProtoInfo EPI;
10196 EPI.Variadic = Variadic;
10197 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
10198 EPI.ExceptionSpec.Type =
10199 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
10201 return getFunctionType(ResType, ArgTypes, EPI);
10204 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
10205 const FunctionDecl *FD) {
10206 if (!FD->isExternallyVisible())
10207 return GVA_Internal;
10209 // Non-user-provided functions get emitted as weak definitions with every
10210 // use, no matter whether they've been explicitly instantiated etc.
10211 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
10212 if (!MD->isUserProvided())
10213 return GVA_DiscardableODR;
10215 GVALinkage External;
10216 switch (FD->getTemplateSpecializationKind()) {
10217 case TSK_Undeclared:
10218 case TSK_ExplicitSpecialization:
10219 External = GVA_StrongExternal;
10222 case TSK_ExplicitInstantiationDefinition:
10223 return GVA_StrongODR;
10225 // C++11 [temp.explicit]p10:
10226 // [ Note: The intent is that an inline function that is the subject of
10227 // an explicit instantiation declaration will still be implicitly
10228 // instantiated when used so that the body can be considered for
10229 // inlining, but that no out-of-line copy of the inline function would be
10230 // generated in the translation unit. -- end note ]
10231 case TSK_ExplicitInstantiationDeclaration:
10232 return GVA_AvailableExternally;
10234 case TSK_ImplicitInstantiation:
10235 External = GVA_DiscardableODR;
10239 if (!FD->isInlined())
10242 if ((!Context.getLangOpts().CPlusPlus &&
10243 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10244 !FD->hasAttr<DLLExportAttr>()) ||
10245 FD->hasAttr<GNUInlineAttr>()) {
10246 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
10248 // GNU or C99 inline semantics. Determine whether this symbol should be
10249 // externally visible.
10250 if (FD->isInlineDefinitionExternallyVisible())
10253 // C99 inline semantics, where the symbol is not externally visible.
10254 return GVA_AvailableExternally;
10257 // Functions specified with extern and inline in -fms-compatibility mode
10258 // forcibly get emitted. While the body of the function cannot be later
10259 // replaced, the function definition cannot be discarded.
10260 if (FD->isMSExternInline())
10261 return GVA_StrongODR;
10263 return GVA_DiscardableODR;
10266 static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
10267 const Decl *D, GVALinkage L) {
10268 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
10269 // dllexport/dllimport on inline functions.
10270 if (D->hasAttr<DLLImportAttr>()) {
10271 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
10272 return GVA_AvailableExternally;
10273 } else if (D->hasAttr<DLLExportAttr>()) {
10274 if (L == GVA_DiscardableODR)
10275 return GVA_StrongODR;
10276 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
10277 D->hasAttr<CUDAGlobalAttr>()) {
10278 // Device-side functions with __global__ attribute must always be
10279 // visible externally so they can be launched from host.
10280 if (L == GVA_DiscardableODR || L == GVA_Internal)
10281 return GVA_StrongODR;
10286 /// Adjust the GVALinkage for a declaration based on what an external AST source
10287 /// knows about whether there can be other definitions of this declaration.
10289 adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
10291 ExternalASTSource *Source = Ctx.getExternalSource();
10295 switch (Source->hasExternalDefinitions(D)) {
10296 case ExternalASTSource::EK_Never:
10297 // Other translation units rely on us to provide the definition.
10298 if (L == GVA_DiscardableODR)
10299 return GVA_StrongODR;
10302 case ExternalASTSource::EK_Always:
10303 return GVA_AvailableExternally;
10305 case ExternalASTSource::EK_ReplyHazy:
10311 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
10312 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
10313 adjustGVALinkageForAttributes(*this, FD,
10314 basicGVALinkageForFunction(*this, FD)));
10317 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
10318 const VarDecl *VD) {
10319 if (!VD->isExternallyVisible())
10320 return GVA_Internal;
10322 if (VD->isStaticLocal()) {
10323 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
10324 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
10325 LexicalContext = LexicalContext->getLexicalParent();
10327 // ObjC Blocks can create local variables that don't have a FunctionDecl
10329 if (!LexicalContext)
10330 return GVA_DiscardableODR;
10332 // Otherwise, let the static local variable inherit its linkage from the
10333 // nearest enclosing function.
10334 auto StaticLocalLinkage =
10335 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
10337 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
10338 // be emitted in any object with references to the symbol for the object it
10339 // contains, whether inline or out-of-line."
10340 // Similar behavior is observed with MSVC. An alternative ABI could use
10341 // StrongODR/AvailableExternally to match the function, but none are
10342 // known/supported currently.
10343 if (StaticLocalLinkage == GVA_StrongODR ||
10344 StaticLocalLinkage == GVA_AvailableExternally)
10345 return GVA_DiscardableODR;
10346 return StaticLocalLinkage;
10349 // MSVC treats in-class initialized static data members as definitions.
10350 // By giving them non-strong linkage, out-of-line definitions won't
10351 // cause link errors.
10352 if (Context.isMSStaticDataMemberInlineDefinition(VD))
10353 return GVA_DiscardableODR;
10355 // Most non-template variables have strong linkage; inline variables are
10356 // linkonce_odr or (occasionally, for compatibility) weak_odr.
10357 GVALinkage StrongLinkage;
10358 switch (Context.getInlineVariableDefinitionKind(VD)) {
10359 case ASTContext::InlineVariableDefinitionKind::None:
10360 StrongLinkage = GVA_StrongExternal;
10362 case ASTContext::InlineVariableDefinitionKind::Weak:
10363 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
10364 StrongLinkage = GVA_DiscardableODR;
10366 case ASTContext::InlineVariableDefinitionKind::Strong:
10367 StrongLinkage = GVA_StrongODR;
10371 switch (VD->getTemplateSpecializationKind()) {
10372 case TSK_Undeclared:
10373 return StrongLinkage;
10375 case TSK_ExplicitSpecialization:
10376 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10377 VD->isStaticDataMember()
10381 case TSK_ExplicitInstantiationDefinition:
10382 return GVA_StrongODR;
10384 case TSK_ExplicitInstantiationDeclaration:
10385 return GVA_AvailableExternally;
10387 case TSK_ImplicitInstantiation:
10388 return GVA_DiscardableODR;
10391 llvm_unreachable("Invalid Linkage!");
10394 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
10395 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
10396 adjustGVALinkageForAttributes(*this, VD,
10397 basicGVALinkageForVariable(*this, VD)));
10400 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
10401 if (const auto *VD = dyn_cast<VarDecl>(D)) {
10402 if (!VD->isFileVarDecl())
10404 // Global named register variables (GNU extension) are never emitted.
10405 if (VD->getStorageClass() == SC_Register)
10407 if (VD->getDescribedVarTemplate() ||
10408 isa<VarTemplatePartialSpecializationDecl>(VD))
10410 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10411 // We never need to emit an uninstantiated function template.
10412 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10414 } else if (isa<PragmaCommentDecl>(D))
10416 else if (isa<PragmaDetectMismatchDecl>(D))
10418 else if (isa<OMPRequiresDecl>(D))
10420 else if (isa<OMPThreadPrivateDecl>(D))
10421 return !D->getDeclContext()->isDependentContext();
10422 else if (isa<OMPAllocateDecl>(D))
10423 return !D->getDeclContext()->isDependentContext();
10424 else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
10425 return !D->getDeclContext()->isDependentContext();
10426 else if (isa<ImportDecl>(D))
10431 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
10432 assert(getExternalSource() && "It's from an AST file; must have a source.");
10433 // On Windows, PCH files are built together with an object file. If this
10434 // declaration comes from such a PCH and DeclMustBeEmitted would return
10435 // true, it would have returned true and the decl would have been emitted
10436 // into that object file, so it doesn't need to be emitted here.
10437 // Note that decls are still emitted if they're referenced, as usual;
10438 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
10439 // if it's not referenced.
10441 // Explicit template instantiation definitions are tricky. If there was an
10442 // explicit template instantiation decl in the PCH before, it will look like
10443 // the definition comes from there, even if that was just the declaration.
10444 // (Explicit instantiation defs of variable templates always get emitted.)
10445 bool IsExpInstDef =
10446 isa<FunctionDecl>(D) &&
10447 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
10448 TSK_ExplicitInstantiationDefinition;
10450 // Implicit member function definitions, such as operator= might not be
10451 // marked as template specializations, since they're not coming from a
10452 // template but synthesized directly on the class.
10454 isa<CXXMethodDecl>(D) &&
10455 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
10456 TSK_ExplicitInstantiationDefinition;
10458 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
10462 // If this is a member of a class template, we do not need to emit it.
10463 if (D->getDeclContext()->isDependentContext())
10466 // Weak references don't produce any output by themselves.
10467 if (D->hasAttr<WeakRefAttr>())
10470 // Aliases and used decls are required.
10471 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
10474 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
10475 // Forward declarations aren't required.
10476 if (!FD->doesThisDeclarationHaveABody())
10477 return FD->doesDeclarationForceExternallyVisibleDefinition();
10479 // Constructors and destructors are required.
10480 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
10483 // The key function for a class is required. This rule only comes
10484 // into play when inline functions can be key functions, though.
10485 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
10486 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
10487 const CXXRecordDecl *RD = MD->getParent();
10488 if (MD->isOutOfLine() && RD->isDynamicClass()) {
10489 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
10490 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
10496 GVALinkage Linkage = GetGVALinkageForFunction(FD);
10498 // static, static inline, always_inline, and extern inline functions can
10499 // always be deferred. Normal inline functions can be deferred in C99/C++.
10500 // Implicit template instantiations can also be deferred in C++.
10501 return !isDiscardableGVALinkage(Linkage);
10504 const auto *VD = cast<VarDecl>(D);
10505 assert(VD->isFileVarDecl() && "Expected file scoped var");
10507 // If the decl is marked as `declare target to`, it should be emitted for the
10508 // host and for the device.
10509 if (LangOpts.OpenMP &&
10510 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
10513 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
10514 !isMSStaticDataMemberInlineDefinition(VD))
10517 // Variables that can be needed in other TUs are required.
10518 auto Linkage = GetGVALinkageForVariable(VD);
10519 if (!isDiscardableGVALinkage(Linkage))
10522 // We never need to emit a variable that is available in another TU.
10523 if (Linkage == GVA_AvailableExternally)
10526 // Variables that have destruction with side-effects are required.
10527 if (VD->needsDestruction(*this))
10530 // Variables that have initialization with side-effects are required.
10531 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
10532 // We can get a value-dependent initializer during error recovery.
10533 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
10536 // Likewise, variables with tuple-like bindings are required if their
10537 // bindings have side-effects.
10538 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
10539 for (const auto *BD : DD->bindings())
10540 if (const auto *BindingVD = BD->getHoldingVar())
10541 if (DeclMustBeEmitted(BindingVD))
10547 void ASTContext::forEachMultiversionedFunctionVersion(
10548 const FunctionDecl *FD,
10549 llvm::function_ref<void(FunctionDecl *)> Pred) const {
10550 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
10551 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
10552 FD = FD->getMostRecentDecl();
10553 for (auto *CurDecl :
10554 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
10555 FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
10556 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
10557 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
10558 SeenDecls.insert(CurFD);
10564 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
10566 bool IsBuiltin) const {
10567 // Pass through to the C++ ABI object
10569 return ABI->getDefaultMethodCallConv(IsVariadic);
10571 // Builtins ignore user-specified default calling convention and remain the
10572 // Target's default calling convention.
10574 switch (LangOpts.getDefaultCallingConv()) {
10575 case LangOptions::DCC_None:
10577 case LangOptions::DCC_CDecl:
10579 case LangOptions::DCC_FastCall:
10580 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
10581 return CC_X86FastCall;
10583 case LangOptions::DCC_StdCall:
10585 return CC_X86StdCall;
10587 case LangOptions::DCC_VectorCall:
10588 // __vectorcall cannot be applied to variadic functions.
10590 return CC_X86VectorCall;
10592 case LangOptions::DCC_RegCall:
10593 // __regcall cannot be applied to variadic functions.
10595 return CC_X86RegCall;
10599 return Target->getDefaultCallingConv();
10602 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
10603 // Pass through to the C++ ABI object
10604 return ABI->isNearlyEmpty(RD);
10607 VTableContextBase *ASTContext::getVTableContext() {
10608 if (!VTContext.get()) {
10609 auto ABI = Target->getCXXABI();
10610 if (ABI.isMicrosoft())
10611 VTContext.reset(new MicrosoftVTableContext(*this));
10613 auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
10614 ? ItaniumVTableContext::Relative
10615 : ItaniumVTableContext::Pointer;
10616 VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
10619 return VTContext.get();
10622 MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
10625 switch (T->getCXXABI().getKind()) {
10626 case TargetCXXABI::Fuchsia:
10627 case TargetCXXABI::GenericAArch64:
10628 case TargetCXXABI::GenericItanium:
10629 case TargetCXXABI::GenericARM:
10630 case TargetCXXABI::GenericMIPS:
10631 case TargetCXXABI::iOS:
10632 case TargetCXXABI::iOS64:
10633 case TargetCXXABI::WebAssembly:
10634 case TargetCXXABI::WatchOS:
10635 case TargetCXXABI::XL:
10636 return ItaniumMangleContext::create(*this, getDiagnostics());
10637 case TargetCXXABI::Microsoft:
10638 return MicrosoftMangleContext::create(*this, getDiagnostics());
10640 llvm_unreachable("Unsupported ABI");
10643 CXXABI::~CXXABI() = default;
10645 size_t ASTContext::getSideTableAllocatedMemory() const {
10646 return ASTRecordLayouts.getMemorySize() +
10647 llvm::capacity_in_bytes(ObjCLayouts) +
10648 llvm::capacity_in_bytes(KeyFunctions) +
10649 llvm::capacity_in_bytes(ObjCImpls) +
10650 llvm::capacity_in_bytes(BlockVarCopyInits) +
10651 llvm::capacity_in_bytes(DeclAttrs) +
10652 llvm::capacity_in_bytes(TemplateOrInstantiation) +
10653 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
10654 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
10655 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
10656 llvm::capacity_in_bytes(OverriddenMethods) +
10657 llvm::capacity_in_bytes(Types) +
10658 llvm::capacity_in_bytes(VariableArrayTypes);
10661 /// getIntTypeForBitwidth -
10662 /// sets integer QualTy according to specified details:
10663 /// bitwidth, signed/unsigned.
10664 /// Returns empty type if there is no appropriate target types.
10665 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
10666 unsigned Signed) const {
10667 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
10668 CanQualType QualTy = getFromTargetType(Ty);
10669 if (!QualTy && DestWidth == 128)
10670 return Signed ? Int128Ty : UnsignedInt128Ty;
10674 /// getRealTypeForBitwidth -
10675 /// sets floating point QualTy according to specified bitwidth.
10676 /// Returns empty type if there is no appropriate target types.
10677 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
10678 bool ExplicitIEEE) const {
10679 TargetInfo::RealType Ty =
10680 getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitIEEE);
10682 case TargetInfo::Float:
10684 case TargetInfo::Double:
10686 case TargetInfo::LongDouble:
10687 return LongDoubleTy;
10688 case TargetInfo::Float128:
10690 case TargetInfo::NoFloat:
10694 llvm_unreachable("Unhandled TargetInfo::RealType value");
10697 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
10699 MangleNumbers[ND] = Number;
10702 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
10703 auto I = MangleNumbers.find(ND);
10704 return I != MangleNumbers.end() ? I->second : 1;
10707 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
10709 StaticLocalNumbers[VD] = Number;
10712 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
10713 auto I = StaticLocalNumbers.find(VD);
10714 return I != StaticLocalNumbers.end() ? I->second : 1;
10717 MangleNumberingContext &
10718 ASTContext::getManglingNumberContext(const DeclContext *DC) {
10719 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
10720 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
10722 MCtx = createMangleNumberingContext();
10726 MangleNumberingContext &
10727 ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
10728 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
10729 std::unique_ptr<MangleNumberingContext> &MCtx =
10730 ExtraMangleNumberingContexts[D];
10732 MCtx = createMangleNumberingContext();
10736 std::unique_ptr<MangleNumberingContext>
10737 ASTContext::createMangleNumberingContext() const {
10738 return ABI->createMangleNumberingContext();
10741 const CXXConstructorDecl *
10742 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
10743 return ABI->getCopyConstructorForExceptionObject(
10744 cast<CXXRecordDecl>(RD->getFirstDecl()));
10747 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
10748 CXXConstructorDecl *CD) {
10749 return ABI->addCopyConstructorForExceptionObject(
10750 cast<CXXRecordDecl>(RD->getFirstDecl()),
10751 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10754 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10755 TypedefNameDecl *DD) {
10756 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10760 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10761 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10764 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10765 DeclaratorDecl *DD) {
10766 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10769 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10770 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10773 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10774 ParamIndices[D] = index;
10777 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10778 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
10779 assert(I != ParamIndices.end() &&
10780 "ParmIndices lacks entry set by ParmVarDecl");
10784 QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
10785 unsigned Length) const {
10786 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
10787 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
10788 EltTy = EltTy.withConst();
10790 EltTy = adjustStringLiteralBaseType(EltTy);
10792 // Get an array type for the string, according to C99 6.4.5. This includes
10793 // the null terminator character.
10794 return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
10795 ArrayType::Normal, /*IndexTypeQuals*/ 0);
10799 ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
10800 StringLiteral *&Result = StringLiteralCache[Key];
10802 Result = StringLiteral::Create(
10803 *this, Key, StringLiteral::Ascii,
10804 /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
10810 ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
10811 assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
10813 llvm::FoldingSetNodeID ID;
10814 MSGuidDecl::Profile(ID, Parts);
10817 if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
10820 QualType GUIDType = getMSGuidType().withConst();
10821 MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
10822 MSGuidDecls.InsertNode(New, InsertPos);
10826 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10827 const llvm::Triple &T = getTargetInfo().getTriple();
10828 if (!T.isOSDarwin())
10831 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10832 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10835 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10836 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10837 uint64_t Size = sizeChars.getQuantity();
10838 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10839 unsigned Align = alignChars.getQuantity();
10840 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10841 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10845 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10846 const ObjCMethodDecl *MethodImpl) {
10847 // No point trying to match an unavailable/deprecated mothod.
10848 if (MethodDecl->hasAttr<UnavailableAttr>()
10849 || MethodDecl->hasAttr<DeprecatedAttr>())
10851 if (MethodDecl->getObjCDeclQualifier() !=
10852 MethodImpl->getObjCDeclQualifier())
10854 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
10857 if (MethodDecl->param_size() != MethodImpl->param_size())
10860 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10861 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10862 EF = MethodDecl->param_end();
10863 IM != EM && IF != EF; ++IM, ++IF) {
10864 const ParmVarDecl *DeclVar = (*IF);
10865 const ParmVarDecl *ImplVar = (*IM);
10866 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10868 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10872 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
10875 uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
10877 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
10878 AS = LangAS::Default;
10880 AS = QT->getPointeeType().getAddressSpace();
10882 return getTargetInfo().getNullPointerValue(AS);
10885 unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10886 if (isTargetAddressSpace(AS))
10887 return toTargetAddressSpace(AS);
10889 return (*AddrSpaceMap)[(unsigned)AS];
10892 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10893 assert(Ty->isFixedPointType());
10895 if (Ty->isSaturatedFixedPointType()) return Ty;
10897 switch (Ty->castAs<BuiltinType>()->getKind()) {
10899 llvm_unreachable("Not a fixed point type!");
10900 case BuiltinType::ShortAccum:
10901 return SatShortAccumTy;
10902 case BuiltinType::Accum:
10904 case BuiltinType::LongAccum:
10905 return SatLongAccumTy;
10906 case BuiltinType::UShortAccum:
10907 return SatUnsignedShortAccumTy;
10908 case BuiltinType::UAccum:
10909 return SatUnsignedAccumTy;
10910 case BuiltinType::ULongAccum:
10911 return SatUnsignedLongAccumTy;
10912 case BuiltinType::ShortFract:
10913 return SatShortFractTy;
10914 case BuiltinType::Fract:
10916 case BuiltinType::LongFract:
10917 return SatLongFractTy;
10918 case BuiltinType::UShortFract:
10919 return SatUnsignedShortFractTy;
10920 case BuiltinType::UFract:
10921 return SatUnsignedFractTy;
10922 case BuiltinType::ULongFract:
10923 return SatUnsignedLongFractTy;
10927 LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10928 if (LangOpts.OpenCL)
10929 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10932 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10934 return getLangASFromTargetAS(AS);
10937 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10938 // doesn't include ASTContext.h
10940 clang::LazyGenerationalUpdatePtr<
10941 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10942 clang::LazyGenerationalUpdatePtr<
10943 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10944 const clang::ASTContext &Ctx, Decl *Value);
10946 unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10947 assert(Ty->isFixedPointType());
10949 const TargetInfo &Target = getTargetInfo();
10950 switch (Ty->castAs<BuiltinType>()->getKind()) {
10952 llvm_unreachable("Not a fixed point type!");
10953 case BuiltinType::ShortAccum:
10954 case BuiltinType::SatShortAccum:
10955 return Target.getShortAccumScale();
10956 case BuiltinType::Accum:
10957 case BuiltinType::SatAccum:
10958 return Target.getAccumScale();
10959 case BuiltinType::LongAccum:
10960 case BuiltinType::SatLongAccum:
10961 return Target.getLongAccumScale();
10962 case BuiltinType::UShortAccum:
10963 case BuiltinType::SatUShortAccum:
10964 return Target.getUnsignedShortAccumScale();
10965 case BuiltinType::UAccum:
10966 case BuiltinType::SatUAccum:
10967 return Target.getUnsignedAccumScale();
10968 case BuiltinType::ULongAccum:
10969 case BuiltinType::SatULongAccum:
10970 return Target.getUnsignedLongAccumScale();
10971 case BuiltinType::ShortFract:
10972 case BuiltinType::SatShortFract:
10973 return Target.getShortFractScale();
10974 case BuiltinType::Fract:
10975 case BuiltinType::SatFract:
10976 return Target.getFractScale();
10977 case BuiltinType::LongFract:
10978 case BuiltinType::SatLongFract:
10979 return Target.getLongFractScale();
10980 case BuiltinType::UShortFract:
10981 case BuiltinType::SatUShortFract:
10982 return Target.getUnsignedShortFractScale();
10983 case BuiltinType::UFract:
10984 case BuiltinType::SatUFract:
10985 return Target.getUnsignedFractScale();
10986 case BuiltinType::ULongFract:
10987 case BuiltinType::SatULongFract:
10988 return Target.getUnsignedLongFractScale();
10992 unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10993 assert(Ty->isFixedPointType());
10995 const TargetInfo &Target = getTargetInfo();
10996 switch (Ty->castAs<BuiltinType>()->getKind()) {
10998 llvm_unreachable("Not a fixed point type!");
10999 case BuiltinType::ShortAccum:
11000 case BuiltinType::SatShortAccum:
11001 return Target.getShortAccumIBits();
11002 case BuiltinType::Accum:
11003 case BuiltinType::SatAccum:
11004 return Target.getAccumIBits();
11005 case BuiltinType::LongAccum:
11006 case BuiltinType::SatLongAccum:
11007 return Target.getLongAccumIBits();
11008 case BuiltinType::UShortAccum:
11009 case BuiltinType::SatUShortAccum:
11010 return Target.getUnsignedShortAccumIBits();
11011 case BuiltinType::UAccum:
11012 case BuiltinType::SatUAccum:
11013 return Target.getUnsignedAccumIBits();
11014 case BuiltinType::ULongAccum:
11015 case BuiltinType::SatULongAccum:
11016 return Target.getUnsignedLongAccumIBits();
11017 case BuiltinType::ShortFract:
11018 case BuiltinType::SatShortFract:
11019 case BuiltinType::Fract:
11020 case BuiltinType::SatFract:
11021 case BuiltinType::LongFract:
11022 case BuiltinType::SatLongFract:
11023 case BuiltinType::UShortFract:
11024 case BuiltinType::SatUShortFract:
11025 case BuiltinType::UFract:
11026 case BuiltinType::SatUFract:
11027 case BuiltinType::ULongFract:
11028 case BuiltinType::SatULongFract:
11033 FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
11034 assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
11035 "Can only get the fixed point semantics for a "
11036 "fixed point or integer type.");
11037 if (Ty->isIntegerType())
11038 return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
11039 Ty->isSignedIntegerType());
11041 bool isSigned = Ty->isSignedFixedPointType();
11042 return FixedPointSemantics(
11043 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
11044 Ty->isSaturatedFixedPointType(),
11045 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
11048 APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
11049 assert(Ty->isFixedPointType());
11050 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
11053 APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
11054 assert(Ty->isFixedPointType());
11055 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
11058 QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
11059 assert(Ty->isUnsignedFixedPointType() &&
11060 "Expected unsigned fixed point type");
11062 switch (Ty->castAs<BuiltinType>()->getKind()) {
11063 case BuiltinType::UShortAccum:
11064 return ShortAccumTy;
11065 case BuiltinType::UAccum:
11067 case BuiltinType::ULongAccum:
11068 return LongAccumTy;
11069 case BuiltinType::SatUShortAccum:
11070 return SatShortAccumTy;
11071 case BuiltinType::SatUAccum:
11073 case BuiltinType::SatULongAccum:
11074 return SatLongAccumTy;
11075 case BuiltinType::UShortFract:
11076 return ShortFractTy;
11077 case BuiltinType::UFract:
11079 case BuiltinType::ULongFract:
11080 return LongFractTy;
11081 case BuiltinType::SatUShortFract:
11082 return SatShortFractTy;
11083 case BuiltinType::SatUFract:
11085 case BuiltinType::SatULongFract:
11086 return SatLongFractTy;
11088 llvm_unreachable("Unexpected unsigned fixed point type");
11093 ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
11094 assert(TD != nullptr);
11095 ParsedTargetAttr ParsedAttr = TD->parse();
11097 ParsedAttr.Features.erase(
11098 llvm::remove_if(ParsedAttr.Features,
11099 [&](const std::string &Feat) {
11100 return !Target->isValidFeatureName(
11101 StringRef{Feat}.substr(1));
11103 ParsedAttr.Features.end());
11107 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11108 const FunctionDecl *FD) const {
11110 getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
11112 Target->initFeatureMap(FeatureMap, getDiagnostics(),
11113 Target->getTargetOpts().CPU,
11114 Target->getTargetOpts().Features);
11117 // Fills in the supplied string map with the set of target features for the
11118 // passed in function.
11119 void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
11120 GlobalDecl GD) const {
11121 StringRef TargetCPU = Target->getTargetOpts().CPU;
11122 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
11123 if (const auto *TD = FD->getAttr<TargetAttr>()) {
11124 ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
11126 // Make a copy of the features as passed on the command line into the
11127 // beginning of the additional features from the function to override.
11128 ParsedAttr.Features.insert(
11129 ParsedAttr.Features.begin(),
11130 Target->getTargetOpts().FeaturesAsWritten.begin(),
11131 Target->getTargetOpts().FeaturesAsWritten.end());
11133 if (ParsedAttr.Architecture != "" &&
11134 Target->isValidCPUName(ParsedAttr.Architecture))
11135 TargetCPU = ParsedAttr.Architecture;
11137 // Now populate the feature map, first with the TargetCPU which is either
11138 // the default or a new one from the target attribute string. Then we'll use
11139 // the passed in features (FeaturesAsWritten) along with the new ones from
11141 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
11142 ParsedAttr.Features);
11143 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
11144 llvm::SmallVector<StringRef, 32> FeaturesTmp;
11145 Target->getCPUSpecificCPUDispatchFeatures(
11146 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
11147 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
11148 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
11150 Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
11151 Target->getTargetOpts().Features);
11155 OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
11156 OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
11157 return *OMPTraitInfoVector.back();
11160 const DiagnosticBuilder &
11161 clang::operator<<(const DiagnosticBuilder &DB,
11162 const ASTContext::SectionInfo &Section) {
11164 return DB << Section.Decl;
11165 return DB << "a prior #pragma section";