1 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the ASTContext interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTContext.h"
15 #include "CXXABI.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Comment.h"
20 #include "clang/AST/CommentCommandTraits.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/Mangle.h"
28 #include "clang/AST/MangleNumberingContext.h"
29 #include "clang/AST/RecordLayout.h"
30 #include "clang/AST/RecursiveASTVisitor.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/AST/VTableBuilder.h"
33 #include "clang/Basic/Builtins.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/Triple.h"
39 #include "llvm/Support/Capacity.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <map>
43 
44 using namespace clang;
45 
46 unsigned ASTContext::NumImplicitDefaultConstructors;
47 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
48 unsigned ASTContext::NumImplicitCopyConstructors;
49 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
50 unsigned ASTContext::NumImplicitMoveConstructors;
51 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
52 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
54 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
56 unsigned ASTContext::NumImplicitDestructors;
57 unsigned ASTContext::NumImplicitDestructorsDeclared;
58 
59 enum FloatingRank {
60   HalfRank, FloatRank, DoubleRank, LongDoubleRank
61 };
62 
getRawCommentForDeclNoCache(const Decl * D) const63 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
64   if (!CommentsLoaded && ExternalSource) {
65     ExternalSource->ReadComments();
66 
67 #ifndef NDEBUG
68     ArrayRef<RawComment *> RawComments = Comments.getComments();
69     assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70                           BeforeThanCompare<RawComment>(SourceMgr)));
71 #endif
72 
73     CommentsLoaded = true;
74   }
75 
76   assert(D);
77 
78   // User can not attach documentation to implicit declarations.
79   if (D->isImplicit())
80     return nullptr;
81 
82   // User can not attach documentation to implicit instantiations.
83   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
85       return nullptr;
86   }
87 
88   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89     if (VD->isStaticDataMember() &&
90         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
91       return nullptr;
92   }
93 
94   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95     if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
96       return nullptr;
97   }
98 
99   if (const ClassTemplateSpecializationDecl *CTSD =
100           dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101     TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102     if (TSK == TSK_ImplicitInstantiation ||
103         TSK == TSK_Undeclared)
104       return nullptr;
105   }
106 
107   if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108     if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
109       return nullptr;
110   }
111   if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112     // When tag declaration (but not definition!) is part of the
113     // decl-specifier-seq of some other declaration, it doesn't get comment
114     if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
115       return nullptr;
116   }
117   // TODO: handle comments for function parameters properly.
118   if (isa<ParmVarDecl>(D))
119     return nullptr;
120 
121   // TODO: we could look up template parameter documentation in the template
122   // documentation.
123   if (isa<TemplateTypeParmDecl>(D) ||
124       isa<NonTypeTemplateParmDecl>(D) ||
125       isa<TemplateTemplateParmDecl>(D))
126     return nullptr;
127 
128   ArrayRef<RawComment *> RawComments = Comments.getComments();
129 
130   // If there are no comments anywhere, we won't find anything.
131   if (RawComments.empty())
132     return nullptr;
133 
134   // Find declaration location.
135   // For Objective-C declarations we generally don't expect to have multiple
136   // declarators, thus use declaration starting location as the "declaration
137   // location".
138   // For all other declarations multiple declarators are used quite frequently,
139   // so we use the location of the identifier as the "declaration location".
140   SourceLocation DeclLoc;
141   if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
142       isa<ObjCPropertyDecl>(D) ||
143       isa<RedeclarableTemplateDecl>(D) ||
144       isa<ClassTemplateSpecializationDecl>(D))
145     DeclLoc = D->getLocStart();
146   else {
147     DeclLoc = D->getLocation();
148     if (DeclLoc.isMacroID()) {
149       if (isa<TypedefDecl>(D)) {
150         // If location of the typedef name is in a macro, it is because being
151         // declared via a macro. Try using declaration's starting location as
152         // the "declaration location".
153         DeclLoc = D->getLocStart();
154       } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155         // If location of the tag decl is inside a macro, but the spelling of
156         // the tag name comes from a macro argument, it looks like a special
157         // macro like NS_ENUM is being used to define the tag decl.  In that
158         // case, adjust the source location to the expansion loc so that we can
159         // attach the comment to the tag decl.
160         if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161             TD->isCompleteDefinition())
162           DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163       }
164     }
165   }
166 
167   // If the declaration doesn't map directly to a location in a file, we
168   // can't find the comment.
169   if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
170     return nullptr;
171 
172   // Find the comment that occurs just after this declaration.
173   ArrayRef<RawComment *>::iterator Comment;
174   {
175     // When searching for comments during parsing, the comment we are looking
176     // for is usually among the last two comments we parsed -- check them
177     // first.
178     RawComment CommentAtDeclLoc(
179         SourceMgr, SourceRange(DeclLoc), false,
180         LangOpts.CommentOpts.ParseAllComments);
181     BeforeThanCompare<RawComment> Compare(SourceMgr);
182     ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183     bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184     if (!Found && RawComments.size() >= 2) {
185       MaybeBeforeDecl--;
186       Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187     }
188 
189     if (Found) {
190       Comment = MaybeBeforeDecl + 1;
191       assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192                                          &CommentAtDeclLoc, Compare));
193     } else {
194       // Slow path.
195       Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196                                  &CommentAtDeclLoc, Compare);
197     }
198   }
199 
200   // Decompose the location for the declaration and find the beginning of the
201   // file buffer.
202   std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203 
204   // First check whether we have a trailing comment.
205   if (Comment != RawComments.end() &&
206       (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
207       (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
208        isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
209     std::pair<FileID, unsigned> CommentBeginDecomp
210       = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
211     // Check that Doxygen trailing comment comes after the declaration, starts
212     // on the same line and in the same file as the declaration.
213     if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214         SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215           == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216                                      CommentBeginDecomp.second)) {
217       return *Comment;
218     }
219   }
220 
221   // The comment just after the declaration was not a trailing comment.
222   // Let's look at the previous comment.
223   if (Comment == RawComments.begin())
224     return nullptr;
225   --Comment;
226 
227   // Check that we actually have a non-member Doxygen comment.
228   if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
229     return nullptr;
230 
231   // Decompose the end of the comment.
232   std::pair<FileID, unsigned> CommentEndDecomp
233     = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
234 
235   // If the comment and the declaration aren't in the same file, then they
236   // aren't related.
237   if (DeclLocDecomp.first != CommentEndDecomp.first)
238     return nullptr;
239 
240   // Get the corresponding buffer.
241   bool Invalid = false;
242   const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243                                                &Invalid).data();
244   if (Invalid)
245     return nullptr;
246 
247   // Extract text between the comment and declaration.
248   StringRef Text(Buffer + CommentEndDecomp.second,
249                  DeclLocDecomp.second - CommentEndDecomp.second);
250 
251   // There should be no other declarations or preprocessor directives between
252   // comment and declaration.
253   if (Text.find_first_of(";{}#@") != StringRef::npos)
254     return nullptr;
255 
256   return *Comment;
257 }
258 
259 namespace {
260 /// If we have a 'templated' declaration for a template, adjust 'D' to
261 /// refer to the actual template.
262 /// If we have an implicit instantiation, adjust 'D' to refer to template.
adjustDeclToTemplate(const Decl * D)263 const Decl *adjustDeclToTemplate(const Decl *D) {
264   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
265     // Is this function declaration part of a function template?
266     if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
267       return FTD;
268 
269     // Nothing to do if function is not an implicit instantiation.
270     if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271       return D;
272 
273     // Function is an implicit instantiation of a function template?
274     if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275       return FTD;
276 
277     // Function is instantiated from a member definition of a class template?
278     if (const FunctionDecl *MemberDecl =
279             FD->getInstantiatedFromMemberFunction())
280       return MemberDecl;
281 
282     return D;
283   }
284   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285     // Static data member is instantiated from a member definition of a class
286     // template?
287     if (VD->isStaticDataMember())
288       if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289         return MemberDecl;
290 
291     return D;
292   }
293   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294     // Is this class declaration part of a class template?
295     if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296       return CTD;
297 
298     // Class is an implicit instantiation of a class template or partial
299     // specialization?
300     if (const ClassTemplateSpecializationDecl *CTSD =
301             dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302       if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303         return D;
304       llvm::PointerUnion<ClassTemplateDecl *,
305                          ClassTemplatePartialSpecializationDecl *>
306           PU = CTSD->getSpecializedTemplateOrPartial();
307       return PU.is<ClassTemplateDecl*>() ?
308           static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309           static_cast<const Decl*>(
310               PU.get<ClassTemplatePartialSpecializationDecl *>());
311     }
312 
313     // Class is instantiated from a member definition of a class template?
314     if (const MemberSpecializationInfo *Info =
315                    CRD->getMemberSpecializationInfo())
316       return Info->getInstantiatedFrom();
317 
318     return D;
319   }
320   if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321     // Enum is instantiated from a member definition of a class template?
322     if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323       return MemberDecl;
324 
325     return D;
326   }
327   // FIXME: Adjust alias templates?
328   return D;
329 }
330 } // anonymous namespace
331 
getRawCommentForAnyRedecl(const Decl * D,const Decl ** OriginalDecl) const332 const RawComment *ASTContext::getRawCommentForAnyRedecl(
333                                                 const Decl *D,
334                                                 const Decl **OriginalDecl) const {
335   D = adjustDeclToTemplate(D);
336 
337   // Check whether we have cached a comment for this declaration already.
338   {
339     llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340         RedeclComments.find(D);
341     if (Pos != RedeclComments.end()) {
342       const RawCommentAndCacheFlags &Raw = Pos->second;
343       if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344         if (OriginalDecl)
345           *OriginalDecl = Raw.getOriginalDecl();
346         return Raw.getRaw();
347       }
348     }
349   }
350 
351   // Search for comments attached to declarations in the redeclaration chain.
352   const RawComment *RC = nullptr;
353   const Decl *OriginalDeclForRC = nullptr;
354   for (auto I : D->redecls()) {
355     llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
356         RedeclComments.find(I);
357     if (Pos != RedeclComments.end()) {
358       const RawCommentAndCacheFlags &Raw = Pos->second;
359       if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360         RC = Raw.getRaw();
361         OriginalDeclForRC = Raw.getOriginalDecl();
362         break;
363       }
364     } else {
365       RC = getRawCommentForDeclNoCache(I);
366       OriginalDeclForRC = I;
367       RawCommentAndCacheFlags Raw;
368       if (RC) {
369         // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
370         // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
371         Raw.setKind(RawCommentAndCacheFlags::FromDecl);
372         Raw.setRaw(RC);
373       } else
374         Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
375       Raw.setOriginalDecl(I);
376       RedeclComments[I] = Raw;
377       if (RC)
378         break;
379     }
380   }
381 
382   // If we found a comment, it should be a documentation comment.
383   assert(!RC || RC->isDocumentation());
384 
385   if (OriginalDecl)
386     *OriginalDecl = OriginalDeclForRC;
387 
388   // Update cache for every declaration in the redeclaration chain.
389   RawCommentAndCacheFlags Raw;
390   Raw.setRaw(RC);
391   Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
392   Raw.setOriginalDecl(OriginalDeclForRC);
393 
394   for (auto I : D->redecls()) {
395     RawCommentAndCacheFlags &R = RedeclComments[I];
396     if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
397       R = Raw;
398   }
399 
400   return RC;
401 }
402 
addRedeclaredMethods(const ObjCMethodDecl * ObjCMethod,SmallVectorImpl<const NamedDecl * > & Redeclared)403 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
404                    SmallVectorImpl<const NamedDecl *> &Redeclared) {
405   const DeclContext *DC = ObjCMethod->getDeclContext();
406   if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
407     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
408     if (!ID)
409       return;
410     // Add redeclared method here.
411     for (const auto *Ext : ID->known_extensions()) {
412       if (ObjCMethodDecl *RedeclaredMethod =
413             Ext->getMethod(ObjCMethod->getSelector(),
414                                   ObjCMethod->isInstanceMethod()))
415         Redeclared.push_back(RedeclaredMethod);
416     }
417   }
418 }
419 
cloneFullComment(comments::FullComment * FC,const Decl * D) const420 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
421                                                     const Decl *D) const {
422   comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
423   ThisDeclInfo->CommentDecl = D;
424   ThisDeclInfo->IsFilled = false;
425   ThisDeclInfo->fill();
426   ThisDeclInfo->CommentDecl = FC->getDecl();
427   if (!ThisDeclInfo->TemplateParameters)
428     ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
429   comments::FullComment *CFC =
430     new (*this) comments::FullComment(FC->getBlocks(),
431                                       ThisDeclInfo);
432   return CFC;
433 }
434 
getLocalCommentForDeclUncached(const Decl * D) const435 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
436   const RawComment *RC = getRawCommentForDeclNoCache(D);
437   return RC ? RC->parse(*this, nullptr, D) : nullptr;
438 }
439 
getCommentForDecl(const Decl * D,const Preprocessor * PP) const440 comments::FullComment *ASTContext::getCommentForDecl(
441                                               const Decl *D,
442                                               const Preprocessor *PP) const {
443   if (D->isInvalidDecl())
444     return nullptr;
445   D = adjustDeclToTemplate(D);
446 
447   const Decl *Canonical = D->getCanonicalDecl();
448   llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
449       ParsedComments.find(Canonical);
450 
451   if (Pos != ParsedComments.end()) {
452     if (Canonical != D) {
453       comments::FullComment *FC = Pos->second;
454       comments::FullComment *CFC = cloneFullComment(FC, D);
455       return CFC;
456     }
457     return Pos->second;
458   }
459 
460   const Decl *OriginalDecl;
461 
462   const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
463   if (!RC) {
464     if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
465       SmallVector<const NamedDecl*, 8> Overridden;
466       const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
467       if (OMD && OMD->isPropertyAccessor())
468         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
469           if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
470             return cloneFullComment(FC, D);
471       if (OMD)
472         addRedeclaredMethods(OMD, Overridden);
473       getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
474       for (unsigned i = 0, e = Overridden.size(); i < e; i++)
475         if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
476           return cloneFullComment(FC, D);
477     }
478     else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
479       // Attach any tag type's documentation to its typedef if latter
480       // does not have one of its own.
481       QualType QT = TD->getUnderlyingType();
482       if (const TagType *TT = QT->getAs<TagType>())
483         if (const Decl *TD = TT->getDecl())
484           if (comments::FullComment *FC = getCommentForDecl(TD, PP))
485             return cloneFullComment(FC, D);
486     }
487     else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
488       while (IC->getSuperClass()) {
489         IC = IC->getSuperClass();
490         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
491           return cloneFullComment(FC, D);
492       }
493     }
494     else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
495       if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
496         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
497           return cloneFullComment(FC, D);
498     }
499     else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
500       if (!(RD = RD->getDefinition()))
501         return nullptr;
502       // Check non-virtual bases.
503       for (const auto &I : RD->bases()) {
504         if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
505           continue;
506         QualType Ty = I.getType();
507         if (Ty.isNull())
508           continue;
509         if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
510           if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
511             continue;
512 
513           if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
514             return cloneFullComment(FC, D);
515         }
516       }
517       // Check virtual bases.
518       for (const auto &I : RD->vbases()) {
519         if (I.getAccessSpecifier() != AS_public)
520           continue;
521         QualType Ty = I.getType();
522         if (Ty.isNull())
523           continue;
524         if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
525           if (!(VirtualBase= VirtualBase->getDefinition()))
526             continue;
527           if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
528             return cloneFullComment(FC, D);
529         }
530       }
531     }
532     return nullptr;
533   }
534 
535   // If the RawComment was attached to other redeclaration of this Decl, we
536   // should parse the comment in context of that other Decl.  This is important
537   // because comments can contain references to parameter names which can be
538   // different across redeclarations.
539   if (D != OriginalDecl)
540     return getCommentForDecl(OriginalDecl, PP);
541 
542   comments::FullComment *FC = RC->parse(*this, PP, D);
543   ParsedComments[Canonical] = FC;
544   return FC;
545 }
546 
547 void
Profile(llvm::FoldingSetNodeID & ID,TemplateTemplateParmDecl * Parm)548 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
549                                                TemplateTemplateParmDecl *Parm) {
550   ID.AddInteger(Parm->getDepth());
551   ID.AddInteger(Parm->getPosition());
552   ID.AddBoolean(Parm->isParameterPack());
553 
554   TemplateParameterList *Params = Parm->getTemplateParameters();
555   ID.AddInteger(Params->size());
556   for (TemplateParameterList::const_iterator P = Params->begin(),
557                                           PEnd = Params->end();
558        P != PEnd; ++P) {
559     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
560       ID.AddInteger(0);
561       ID.AddBoolean(TTP->isParameterPack());
562       continue;
563     }
564 
565     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
566       ID.AddInteger(1);
567       ID.AddBoolean(NTTP->isParameterPack());
568       ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
569       if (NTTP->isExpandedParameterPack()) {
570         ID.AddBoolean(true);
571         ID.AddInteger(NTTP->getNumExpansionTypes());
572         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
573           QualType T = NTTP->getExpansionType(I);
574           ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
575         }
576       } else
577         ID.AddBoolean(false);
578       continue;
579     }
580 
581     TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
582     ID.AddInteger(2);
583     Profile(ID, TTP);
584   }
585 }
586 
587 TemplateTemplateParmDecl *
getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl * TTP) const588 ASTContext::getCanonicalTemplateTemplateParmDecl(
589                                           TemplateTemplateParmDecl *TTP) const {
590   // Check if we already have a canonical template template parameter.
591   llvm::FoldingSetNodeID ID;
592   CanonicalTemplateTemplateParm::Profile(ID, TTP);
593   void *InsertPos = nullptr;
594   CanonicalTemplateTemplateParm *Canonical
595     = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
596   if (Canonical)
597     return Canonical->getParam();
598 
599   // Build a canonical template parameter list.
600   TemplateParameterList *Params = TTP->getTemplateParameters();
601   SmallVector<NamedDecl *, 4> CanonParams;
602   CanonParams.reserve(Params->size());
603   for (TemplateParameterList::const_iterator P = Params->begin(),
604                                           PEnd = Params->end();
605        P != PEnd; ++P) {
606     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
607       CanonParams.push_back(
608                   TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
609                                                SourceLocation(),
610                                                SourceLocation(),
611                                                TTP->getDepth(),
612                                                TTP->getIndex(), nullptr, false,
613                                                TTP->isParameterPack()));
614     else if (NonTypeTemplateParmDecl *NTTP
615              = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
616       QualType T = getCanonicalType(NTTP->getType());
617       TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
618       NonTypeTemplateParmDecl *Param;
619       if (NTTP->isExpandedParameterPack()) {
620         SmallVector<QualType, 2> ExpandedTypes;
621         SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
622         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
623           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
624           ExpandedTInfos.push_back(
625                                 getTrivialTypeSourceInfo(ExpandedTypes.back()));
626         }
627 
628         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
629                                                 SourceLocation(),
630                                                 SourceLocation(),
631                                                 NTTP->getDepth(),
632                                                 NTTP->getPosition(), nullptr,
633                                                 T,
634                                                 TInfo,
635                                                 ExpandedTypes.data(),
636                                                 ExpandedTypes.size(),
637                                                 ExpandedTInfos.data());
638       } else {
639         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
640                                                 SourceLocation(),
641                                                 SourceLocation(),
642                                                 NTTP->getDepth(),
643                                                 NTTP->getPosition(), nullptr,
644                                                 T,
645                                                 NTTP->isParameterPack(),
646                                                 TInfo);
647       }
648       CanonParams.push_back(Param);
649 
650     } else
651       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
652                                            cast<TemplateTemplateParmDecl>(*P)));
653   }
654 
655   TemplateTemplateParmDecl *CanonTTP
656     = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
657                                        SourceLocation(), TTP->getDepth(),
658                                        TTP->getPosition(),
659                                        TTP->isParameterPack(),
660                                        nullptr,
661                          TemplateParameterList::Create(*this, SourceLocation(),
662                                                        SourceLocation(),
663                                                        CanonParams.data(),
664                                                        CanonParams.size(),
665                                                        SourceLocation()));
666 
667   // Get the new insert position for the node we care about.
668   Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
669   assert(!Canonical && "Shouldn't be in the map!");
670   (void)Canonical;
671 
672   // Create the canonical template template parameter entry.
673   Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
674   CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
675   return CanonTTP;
676 }
677 
createCXXABI(const TargetInfo & T)678 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
679   if (!LangOpts.CPlusPlus) return nullptr;
680 
681   switch (T.getCXXABI().getKind()) {
682   case TargetCXXABI::GenericARM: // Same as Itanium at this level
683   case TargetCXXABI::iOS:
684   case TargetCXXABI::iOS64:
685   case TargetCXXABI::WatchOS:
686   case TargetCXXABI::GenericAArch64:
687   case TargetCXXABI::GenericMIPS:
688   case TargetCXXABI::GenericItanium:
689   case TargetCXXABI::WebAssembly:
690     return CreateItaniumCXXABI(*this);
691   case TargetCXXABI::Microsoft:
692     return CreateMicrosoftCXXABI(*this);
693   }
694   llvm_unreachable("Invalid CXXABI type!");
695 }
696 
getAddressSpaceMap(const TargetInfo & T,const LangOptions & LOpts)697 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
698                                              const LangOptions &LOpts) {
699   if (LOpts.FakeAddressSpaceMap) {
700     // The fake address space map must have a distinct entry for each
701     // language-specific address space.
702     static const unsigned FakeAddrSpaceMap[] = {
703       1, // opencl_global
704       2, // opencl_local
705       3, // opencl_constant
706       4, // opencl_generic
707       5, // cuda_device
708       6, // cuda_constant
709       7  // cuda_shared
710     };
711     return &FakeAddrSpaceMap;
712   } else {
713     return &T.getAddressSpaceMap();
714   }
715 }
716 
isAddrSpaceMapManglingEnabled(const TargetInfo & TI,const LangOptions & LangOpts)717 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
718                                           const LangOptions &LangOpts) {
719   switch (LangOpts.getAddressSpaceMapMangling()) {
720   case LangOptions::ASMM_Target:
721     return TI.useAddressSpaceMapMangling();
722   case LangOptions::ASMM_On:
723     return true;
724   case LangOptions::ASMM_Off:
725     return false;
726   }
727   llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
728 }
729 
ASTContext(LangOptions & LOpts,SourceManager & SM,IdentifierTable & idents,SelectorTable & sels,Builtin::Context & builtins)730 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
731                        IdentifierTable &idents, SelectorTable &sels,
732                        Builtin::Context &builtins)
733     : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
734       DependentTemplateSpecializationTypes(this_()),
735       SubstTemplateTemplateParmPacks(this_()),
736       GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
737       UInt128Decl(nullptr), Float128StubDecl(nullptr),
738       BuiltinVaListDecl(nullptr), BuiltinMSVaListDecl(nullptr),
739       ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), ObjCClassDecl(nullptr),
740       ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
741       CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
742       FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
743       ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
744       BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
745       FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
746       MakeIntegerSeqDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
747       SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
748       AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
749       PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
750       BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
751       Listener(nullptr), Comments(SM), CommentsLoaded(false),
752       CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
753   TUDecl = TranslationUnitDecl::Create(*this);
754 }
755 
~ASTContext()756 ASTContext::~ASTContext() {
757   ReleaseParentMapEntries();
758 
759   // Release the DenseMaps associated with DeclContext objects.
760   // FIXME: Is this the ideal solution?
761   ReleaseDeclContextMaps();
762 
763   // Call all of the deallocation functions on all of their targets.
764   for (DeallocationMap::const_iterator I = Deallocations.begin(),
765            E = Deallocations.end(); I != E; ++I)
766     for (unsigned J = 0, N = I->second.size(); J != N; ++J)
767       (I->first)((I->second)[J]);
768 
769   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
770   // because they can contain DenseMaps.
771   for (llvm::DenseMap<const ObjCContainerDecl*,
772        const ASTRecordLayout*>::iterator
773        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
774     // Increment in loop to prevent using deallocated memory.
775     if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
776       R->Destroy(*this);
777 
778   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
779        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
780     // Increment in loop to prevent using deallocated memory.
781     if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
782       R->Destroy(*this);
783   }
784 
785   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
786                                                     AEnd = DeclAttrs.end();
787        A != AEnd; ++A)
788     A->second->~AttrVec();
789 
790   for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
791        MaterializedTemporaryValues)
792     MTVPair.second->~APValue();
793 
794   llvm::DeleteContainerSeconds(MangleNumberingContexts);
795 }
796 
ReleaseParentMapEntries()797 void ASTContext::ReleaseParentMapEntries() {
798   if (!PointerParents) return;
799   for (const auto &Entry : *PointerParents) {
800     if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
801       delete Entry.second.get<ast_type_traits::DynTypedNode *>();
802     } else if (Entry.second.is<ParentVector *>()) {
803       delete Entry.second.get<ParentVector *>();
804     }
805   }
806   for (const auto &Entry : *OtherParents) {
807     if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
808       delete Entry.second.get<ast_type_traits::DynTypedNode *>();
809     } else if (Entry.second.is<ParentVector *>()) {
810       delete Entry.second.get<ParentVector *>();
811     }
812   }
813 }
814 
AddDeallocation(void (* Callback)(void *),void * Data)815 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
816   Deallocations[Callback].push_back(Data);
817 }
818 
819 void
setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source)820 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
821   ExternalSource = Source;
822 }
823 
PrintStats() const824 void ASTContext::PrintStats() const {
825   llvm::errs() << "\n*** AST Context Stats:\n";
826   llvm::errs() << "  " << Types.size() << " types total.\n";
827 
828   unsigned counts[] = {
829 #define TYPE(Name, Parent) 0,
830 #define ABSTRACT_TYPE(Name, Parent)
831 #include "clang/AST/TypeNodes.def"
832     0 // Extra
833   };
834 
835   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
836     Type *T = Types[i];
837     counts[(unsigned)T->getTypeClass()]++;
838   }
839 
840   unsigned Idx = 0;
841   unsigned TotalBytes = 0;
842 #define TYPE(Name, Parent)                                              \
843   if (counts[Idx])                                                      \
844     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
845                  << " types\n";                                         \
846   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
847   ++Idx;
848 #define ABSTRACT_TYPE(Name, Parent)
849 #include "clang/AST/TypeNodes.def"
850 
851   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
852 
853   // Implicit special member functions.
854   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
855                << NumImplicitDefaultConstructors
856                << " implicit default constructors created\n";
857   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
858                << NumImplicitCopyConstructors
859                << " implicit copy constructors created\n";
860   if (getLangOpts().CPlusPlus)
861     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
862                  << NumImplicitMoveConstructors
863                  << " implicit move constructors created\n";
864   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
865                << NumImplicitCopyAssignmentOperators
866                << " implicit copy assignment operators created\n";
867   if (getLangOpts().CPlusPlus)
868     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
869                  << NumImplicitMoveAssignmentOperators
870                  << " implicit move assignment operators created\n";
871   llvm::errs() << NumImplicitDestructorsDeclared << "/"
872                << NumImplicitDestructors
873                << " implicit destructors created\n";
874 
875   if (ExternalSource) {
876     llvm::errs() << "\n";
877     ExternalSource->PrintStats();
878   }
879 
880   BumpAlloc.PrintStats();
881 }
882 
mergeDefinitionIntoModule(NamedDecl * ND,Module * M,bool NotifyListeners)883 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
884                                            bool NotifyListeners) {
885   if (NotifyListeners)
886     if (auto *Listener = getASTMutationListener())
887       Listener->RedefinedHiddenDefinition(ND, M);
888 
889   if (getLangOpts().ModulesLocalVisibility)
890     MergedDefModules[ND].push_back(M);
891   else
892     ND->setHidden(false);
893 }
894 
deduplicateMergedDefinitonsFor(NamedDecl * ND)895 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
896   auto It = MergedDefModules.find(ND);
897   if (It == MergedDefModules.end())
898     return;
899 
900   auto &Merged = It->second;
901   llvm::DenseSet<Module*> Found;
902   for (Module *&M : Merged)
903     if (!Found.insert(M).second)
904       M = nullptr;
905   Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
906 }
907 
getExternCContextDecl() const908 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
909   if (!ExternCContext)
910     ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
911 
912   return ExternCContext;
913 }
914 
915 BuiltinTemplateDecl *
buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,const IdentifierInfo * II) const916 ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
917                                      const IdentifierInfo *II) const {
918   auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
919   BuiltinTemplate->setImplicit();
920   TUDecl->addDecl(BuiltinTemplate);
921 
922   return BuiltinTemplate;
923 }
924 
925 BuiltinTemplateDecl *
getMakeIntegerSeqDecl() const926 ASTContext::getMakeIntegerSeqDecl() const {
927   if (!MakeIntegerSeqDecl)
928     MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
929                                                   getMakeIntegerSeqName());
930   return MakeIntegerSeqDecl;
931 }
932 
buildImplicitRecord(StringRef Name,RecordDecl::TagKind TK) const933 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
934                                             RecordDecl::TagKind TK) const {
935   SourceLocation Loc;
936   RecordDecl *NewDecl;
937   if (getLangOpts().CPlusPlus)
938     NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
939                                     Loc, &Idents.get(Name));
940   else
941     NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
942                                  &Idents.get(Name));
943   NewDecl->setImplicit();
944   NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
945       const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
946   return NewDecl;
947 }
948 
buildImplicitTypedef(QualType T,StringRef Name) const949 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
950                                               StringRef Name) const {
951   TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
952   TypedefDecl *NewDecl = TypedefDecl::Create(
953       const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
954       SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
955   NewDecl->setImplicit();
956   return NewDecl;
957 }
958 
getInt128Decl() const959 TypedefDecl *ASTContext::getInt128Decl() const {
960   if (!Int128Decl)
961     Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
962   return Int128Decl;
963 }
964 
getUInt128Decl() const965 TypedefDecl *ASTContext::getUInt128Decl() const {
966   if (!UInt128Decl)
967     UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
968   return UInt128Decl;
969 }
970 
getFloat128StubType() const971 TypeDecl *ASTContext::getFloat128StubType() const {
972   assert(LangOpts.CPlusPlus && "should only be called for c++");
973   if (!Float128StubDecl)
974     Float128StubDecl = buildImplicitRecord("__float128");
975 
976   return Float128StubDecl;
977 }
978 
InitBuiltinType(CanQualType & R,BuiltinType::Kind K)979 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
980   BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
981   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
982   Types.push_back(Ty);
983 }
984 
InitBuiltinTypes(const TargetInfo & Target,const TargetInfo * AuxTarget)985 void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
986                                   const TargetInfo *AuxTarget) {
987   assert((!this->Target || this->Target == &Target) &&
988          "Incorrect target reinitialization");
989   assert(VoidTy.isNull() && "Context reinitialized?");
990 
991   this->Target = &Target;
992   this->AuxTarget = AuxTarget;
993 
994   ABI.reset(createCXXABI(Target));
995   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
996   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
997 
998   // C99 6.2.5p19.
999   InitBuiltinType(VoidTy,              BuiltinType::Void);
1000 
1001   // C99 6.2.5p2.
1002   InitBuiltinType(BoolTy,              BuiltinType::Bool);
1003   // C99 6.2.5p3.
1004   if (LangOpts.CharIsSigned)
1005     InitBuiltinType(CharTy,            BuiltinType::Char_S);
1006   else
1007     InitBuiltinType(CharTy,            BuiltinType::Char_U);
1008   // C99 6.2.5p4.
1009   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
1010   InitBuiltinType(ShortTy,             BuiltinType::Short);
1011   InitBuiltinType(IntTy,               BuiltinType::Int);
1012   InitBuiltinType(LongTy,              BuiltinType::Long);
1013   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
1014 
1015   // C99 6.2.5p6.
1016   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
1017   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
1018   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
1019   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
1020   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
1021 
1022   // C99 6.2.5p10.
1023   InitBuiltinType(FloatTy,             BuiltinType::Float);
1024   InitBuiltinType(DoubleTy,            BuiltinType::Double);
1025   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
1026 
1027   // GNU extension, 128-bit integers.
1028   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
1029   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
1030 
1031   // C++ 3.9.1p5
1032   if (TargetInfo::isTypeSigned(Target.getWCharType()))
1033     InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
1034   else  // -fshort-wchar makes wchar_t be unsigned.
1035     InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
1036   if (LangOpts.CPlusPlus && LangOpts.WChar)
1037     WideCharTy = WCharTy;
1038   else {
1039     // C99 (or C++ using -fno-wchar).
1040     WideCharTy = getFromTargetType(Target.getWCharType());
1041   }
1042 
1043   WIntTy = getFromTargetType(Target.getWIntType());
1044 
1045   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1046     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
1047   else // C99
1048     Char16Ty = getFromTargetType(Target.getChar16Type());
1049 
1050   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1051     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
1052   else // C99
1053     Char32Ty = getFromTargetType(Target.getChar32Type());
1054 
1055   // Placeholder type for type-dependent expressions whose type is
1056   // completely unknown. No code should ever check a type against
1057   // DependentTy and users should never see it; however, it is here to
1058   // help diagnose failures to properly check for type-dependent
1059   // expressions.
1060   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
1061 
1062   // Placeholder type for functions.
1063   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
1064 
1065   // Placeholder type for bound members.
1066   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
1067 
1068   // Placeholder type for pseudo-objects.
1069   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
1070 
1071   // "any" type; useful for debugger-like clients.
1072   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
1073 
1074   // Placeholder type for unbridged ARC casts.
1075   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
1076 
1077   // Placeholder type for builtin functions.
1078   InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
1079 
1080   // Placeholder type for OMP array sections.
1081   if (LangOpts.OpenMP)
1082     InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1083 
1084   // C99 6.2.5p11.
1085   FloatComplexTy      = getComplexType(FloatTy);
1086   DoubleComplexTy     = getComplexType(DoubleTy);
1087   LongDoubleComplexTy = getComplexType(LongDoubleTy);
1088 
1089   // Builtin types for 'id', 'Class', and 'SEL'.
1090   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1091   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1092   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1093 
1094   if (LangOpts.OpenCL) {
1095     InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1096     InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1097     InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1098     InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1099     InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1100     InitBuiltinType(OCLImage2dDepthTy, BuiltinType::OCLImage2dDepth);
1101     InitBuiltinType(OCLImage2dArrayDepthTy, BuiltinType::OCLImage2dArrayDepth);
1102     InitBuiltinType(OCLImage2dMSAATy, BuiltinType::OCLImage2dMSAA);
1103     InitBuiltinType(OCLImage2dArrayMSAATy, BuiltinType::OCLImage2dArrayMSAA);
1104     InitBuiltinType(OCLImage2dMSAADepthTy, BuiltinType::OCLImage2dMSAADepth);
1105     InitBuiltinType(OCLImage2dArrayMSAADepthTy,
1106                     BuiltinType::OCLImage2dArrayMSAADepth);
1107     InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
1108 
1109     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1110     InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1111     InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1112     InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1113     InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1114     InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
1115   }
1116 
1117   // Builtin type for __objc_yes and __objc_no
1118   ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1119                        SignedCharTy : BoolTy);
1120 
1121   ObjCConstantStringType = QualType();
1122 
1123   ObjCSuperType = QualType();
1124 
1125   // void * type
1126   VoidPtrTy = getPointerType(VoidTy);
1127 
1128   // nullptr type (C++0x 2.14.7)
1129   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
1130 
1131   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1132   InitBuiltinType(HalfTy, BuiltinType::Half);
1133 
1134   // Builtin type used to help define __builtin_va_list.
1135   VaListTagDecl = nullptr;
1136 }
1137 
getDiagnostics() const1138 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1139   return SourceMgr.getDiagnostics();
1140 }
1141 
getDeclAttrs(const Decl * D)1142 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1143   AttrVec *&Result = DeclAttrs[D];
1144   if (!Result) {
1145     void *Mem = Allocate(sizeof(AttrVec));
1146     Result = new (Mem) AttrVec;
1147   }
1148 
1149   return *Result;
1150 }
1151 
1152 /// \brief Erase the attributes corresponding to the given declaration.
eraseDeclAttrs(const Decl * D)1153 void ASTContext::eraseDeclAttrs(const Decl *D) {
1154   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1155   if (Pos != DeclAttrs.end()) {
1156     Pos->second->~AttrVec();
1157     DeclAttrs.erase(Pos);
1158   }
1159 }
1160 
1161 // FIXME: Remove ?
1162 MemberSpecializationInfo *
getInstantiatedFromStaticDataMember(const VarDecl * Var)1163 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1164   assert(Var->isStaticDataMember() && "Not a static data member");
1165   return getTemplateOrSpecializationInfo(Var)
1166       .dyn_cast<MemberSpecializationInfo *>();
1167 }
1168 
1169 ASTContext::TemplateOrSpecializationInfo
getTemplateOrSpecializationInfo(const VarDecl * Var)1170 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1171   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1172       TemplateOrInstantiation.find(Var);
1173   if (Pos == TemplateOrInstantiation.end())
1174     return TemplateOrSpecializationInfo();
1175 
1176   return Pos->second;
1177 }
1178 
1179 void
setInstantiatedFromStaticDataMember(VarDecl * Inst,VarDecl * Tmpl,TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)1180 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1181                                                 TemplateSpecializationKind TSK,
1182                                           SourceLocation PointOfInstantiation) {
1183   assert(Inst->isStaticDataMember() && "Not a static data member");
1184   assert(Tmpl->isStaticDataMember() && "Not a static data member");
1185   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1186                                             Tmpl, TSK, PointOfInstantiation));
1187 }
1188 
1189 void
setTemplateOrSpecializationInfo(VarDecl * Inst,TemplateOrSpecializationInfo TSI)1190 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1191                                             TemplateOrSpecializationInfo TSI) {
1192   assert(!TemplateOrInstantiation[Inst] &&
1193          "Already noted what the variable was instantiated from");
1194   TemplateOrInstantiation[Inst] = TSI;
1195 }
1196 
getClassScopeSpecializationPattern(const FunctionDecl * FD)1197 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1198                                                      const FunctionDecl *FD){
1199   assert(FD && "Specialization is 0");
1200   llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1201     = ClassScopeSpecializationPattern.find(FD);
1202   if (Pos == ClassScopeSpecializationPattern.end())
1203     return nullptr;
1204 
1205   return Pos->second;
1206 }
1207 
setClassScopeSpecializationPattern(FunctionDecl * FD,FunctionDecl * Pattern)1208 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1209                                         FunctionDecl *Pattern) {
1210   assert(FD && "Specialization is 0");
1211   assert(Pattern && "Class scope specialization pattern is 0");
1212   ClassScopeSpecializationPattern[FD] = Pattern;
1213 }
1214 
1215 NamedDecl *
getInstantiatedFromUsingDecl(UsingDecl * UUD)1216 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
1217   llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
1218     = InstantiatedFromUsingDecl.find(UUD);
1219   if (Pos == InstantiatedFromUsingDecl.end())
1220     return nullptr;
1221 
1222   return Pos->second;
1223 }
1224 
1225 void
setInstantiatedFromUsingDecl(UsingDecl * Inst,NamedDecl * Pattern)1226 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1227   assert((isa<UsingDecl>(Pattern) ||
1228           isa<UnresolvedUsingValueDecl>(Pattern) ||
1229           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1230          "pattern decl is not a using decl");
1231   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1232   InstantiatedFromUsingDecl[Inst] = Pattern;
1233 }
1234 
1235 UsingShadowDecl *
getInstantiatedFromUsingShadowDecl(UsingShadowDecl * Inst)1236 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1237   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1238     = InstantiatedFromUsingShadowDecl.find(Inst);
1239   if (Pos == InstantiatedFromUsingShadowDecl.end())
1240     return nullptr;
1241 
1242   return Pos->second;
1243 }
1244 
1245 void
setInstantiatedFromUsingShadowDecl(UsingShadowDecl * Inst,UsingShadowDecl * Pattern)1246 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1247                                                UsingShadowDecl *Pattern) {
1248   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1249   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1250 }
1251 
getInstantiatedFromUnnamedFieldDecl(FieldDecl * Field)1252 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1253   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1254     = InstantiatedFromUnnamedFieldDecl.find(Field);
1255   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1256     return nullptr;
1257 
1258   return Pos->second;
1259 }
1260 
setInstantiatedFromUnnamedFieldDecl(FieldDecl * Inst,FieldDecl * Tmpl)1261 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1262                                                      FieldDecl *Tmpl) {
1263   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1264   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1265   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1266          "Already noted what unnamed field was instantiated from");
1267 
1268   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1269 }
1270 
1271 ASTContext::overridden_cxx_method_iterator
overridden_methods_begin(const CXXMethodDecl * Method) const1272 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1273   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1274     = OverriddenMethods.find(Method->getCanonicalDecl());
1275   if (Pos == OverriddenMethods.end())
1276     return nullptr;
1277 
1278   return Pos->second.begin();
1279 }
1280 
1281 ASTContext::overridden_cxx_method_iterator
overridden_methods_end(const CXXMethodDecl * Method) const1282 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1283   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1284     = OverriddenMethods.find(Method->getCanonicalDecl());
1285   if (Pos == OverriddenMethods.end())
1286     return nullptr;
1287 
1288   return Pos->second.end();
1289 }
1290 
1291 unsigned
overridden_methods_size(const CXXMethodDecl * Method) const1292 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1293   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1294     = OverriddenMethods.find(Method->getCanonicalDecl());
1295   if (Pos == OverriddenMethods.end())
1296     return 0;
1297 
1298   return Pos->second.size();
1299 }
1300 
addOverriddenMethod(const CXXMethodDecl * Method,const CXXMethodDecl * Overridden)1301 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1302                                      const CXXMethodDecl *Overridden) {
1303   assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1304   OverriddenMethods[Method].push_back(Overridden);
1305 }
1306 
getOverriddenMethods(const NamedDecl * D,SmallVectorImpl<const NamedDecl * > & Overridden) const1307 void ASTContext::getOverriddenMethods(
1308                       const NamedDecl *D,
1309                       SmallVectorImpl<const NamedDecl *> &Overridden) const {
1310   assert(D);
1311 
1312   if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1313     Overridden.append(overridden_methods_begin(CXXMethod),
1314                       overridden_methods_end(CXXMethod));
1315     return;
1316   }
1317 
1318   const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1319   if (!Method)
1320     return;
1321 
1322   SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1323   Method->getOverriddenMethods(OverDecls);
1324   Overridden.append(OverDecls.begin(), OverDecls.end());
1325 }
1326 
addedLocalImportDecl(ImportDecl * Import)1327 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1328   assert(!Import->NextLocalImport && "Import declaration already in the chain");
1329   assert(!Import->isFromASTFile() && "Non-local import declaration");
1330   if (!FirstLocalImport) {
1331     FirstLocalImport = Import;
1332     LastLocalImport = Import;
1333     return;
1334   }
1335 
1336   LastLocalImport->NextLocalImport = Import;
1337   LastLocalImport = Import;
1338 }
1339 
1340 //===----------------------------------------------------------------------===//
1341 //                         Type Sizing and Analysis
1342 //===----------------------------------------------------------------------===//
1343 
1344 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1345 /// scalar floating point type.
getFloatTypeSemantics(QualType T) const1346 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1347   const BuiltinType *BT = T->getAs<BuiltinType>();
1348   assert(BT && "Not a floating point type!");
1349   switch (BT->getKind()) {
1350   default: llvm_unreachable("Not a floating point type!");
1351   case BuiltinType::Half:       return Target->getHalfFormat();
1352   case BuiltinType::Float:      return Target->getFloatFormat();
1353   case BuiltinType::Double:     return Target->getDoubleFormat();
1354   case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1355   }
1356 }
1357 
getDeclAlign(const Decl * D,bool ForAlignof) const1358 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1359   unsigned Align = Target->getCharWidth();
1360 
1361   bool UseAlignAttrOnly = false;
1362   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1363     Align = AlignFromAttr;
1364 
1365     // __attribute__((aligned)) can increase or decrease alignment
1366     // *except* on a struct or struct member, where it only increases
1367     // alignment unless 'packed' is also specified.
1368     //
1369     // It is an error for alignas to decrease alignment, so we can
1370     // ignore that possibility;  Sema should diagnose it.
1371     if (isa<FieldDecl>(D)) {
1372       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1373         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1374     } else {
1375       UseAlignAttrOnly = true;
1376     }
1377   }
1378   else if (isa<FieldDecl>(D))
1379       UseAlignAttrOnly =
1380         D->hasAttr<PackedAttr>() ||
1381         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1382 
1383   // If we're using the align attribute only, just ignore everything
1384   // else about the declaration and its type.
1385   if (UseAlignAttrOnly) {
1386     // do nothing
1387 
1388   } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1389     QualType T = VD->getType();
1390     if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
1391       if (ForAlignof)
1392         T = RT->getPointeeType();
1393       else
1394         T = getPointerType(RT->getPointeeType());
1395     }
1396     QualType BaseT = getBaseElementType(T);
1397     if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
1398       // Adjust alignments of declarations with array type by the
1399       // large-array alignment on the target.
1400       if (const ArrayType *arrayType = getAsArrayType(T)) {
1401         unsigned MinWidth = Target->getLargeArrayMinWidth();
1402         if (!ForAlignof && MinWidth) {
1403           if (isa<VariableArrayType>(arrayType))
1404             Align = std::max(Align, Target->getLargeArrayAlign());
1405           else if (isa<ConstantArrayType>(arrayType) &&
1406                    MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1407             Align = std::max(Align, Target->getLargeArrayAlign());
1408         }
1409       }
1410       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1411       if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1412         if (VD->hasGlobalStorage() && !ForAlignof)
1413           Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1414       }
1415     }
1416 
1417     // Fields can be subject to extra alignment constraints, like if
1418     // the field is packed, the struct is packed, or the struct has a
1419     // a max-field-alignment constraint (#pragma pack).  So calculate
1420     // the actual alignment of the field within the struct, and then
1421     // (as we're expected to) constrain that by the alignment of the type.
1422     if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1423       const RecordDecl *Parent = Field->getParent();
1424       // We can only produce a sensible answer if the record is valid.
1425       if (!Parent->isInvalidDecl()) {
1426         const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1427 
1428         // Start with the record's overall alignment.
1429         unsigned FieldAlign = toBits(Layout.getAlignment());
1430 
1431         // Use the GCD of that and the offset within the record.
1432         uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1433         if (Offset > 0) {
1434           // Alignment is always a power of 2, so the GCD will be a power of 2,
1435           // which means we get to do this crazy thing instead of Euclid's.
1436           uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1437           if (LowBitOfOffset < FieldAlign)
1438             FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1439         }
1440 
1441         Align = std::min(Align, FieldAlign);
1442       }
1443     }
1444   }
1445 
1446   return toCharUnitsFromBits(Align);
1447 }
1448 
1449 // getTypeInfoDataSizeInChars - Return the size of a type, in
1450 // chars. If the type is a record, its data size is returned.  This is
1451 // the size of the memcpy that's performed when assigning this type
1452 // using a trivial copy/move assignment operator.
1453 std::pair<CharUnits, CharUnits>
getTypeInfoDataSizeInChars(QualType T) const1454 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1455   std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1456 
1457   // In C++, objects can sometimes be allocated into the tail padding
1458   // of a base-class subobject.  We decide whether that's possible
1459   // during class layout, so here we can just trust the layout results.
1460   if (getLangOpts().CPlusPlus) {
1461     if (const RecordType *RT = T->getAs<RecordType>()) {
1462       const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1463       sizeAndAlign.first = layout.getDataSize();
1464     }
1465   }
1466 
1467   return sizeAndAlign;
1468 }
1469 
1470 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1471 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1472 std::pair<CharUnits, CharUnits>
getConstantArrayInfoInChars(const ASTContext & Context,const ConstantArrayType * CAT)1473 static getConstantArrayInfoInChars(const ASTContext &Context,
1474                                    const ConstantArrayType *CAT) {
1475   std::pair<CharUnits, CharUnits> EltInfo =
1476       Context.getTypeInfoInChars(CAT->getElementType());
1477   uint64_t Size = CAT->getSize().getZExtValue();
1478   assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1479               (uint64_t)(-1)/Size) &&
1480          "Overflow in array type char size evaluation");
1481   uint64_t Width = EltInfo.first.getQuantity() * Size;
1482   unsigned Align = EltInfo.second.getQuantity();
1483   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1484       Context.getTargetInfo().getPointerWidth(0) == 64)
1485     Width = llvm::RoundUpToAlignment(Width, Align);
1486   return std::make_pair(CharUnits::fromQuantity(Width),
1487                         CharUnits::fromQuantity(Align));
1488 }
1489 
1490 std::pair<CharUnits, CharUnits>
getTypeInfoInChars(const Type * T) const1491 ASTContext::getTypeInfoInChars(const Type *T) const {
1492   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1493     return getConstantArrayInfoInChars(*this, CAT);
1494   TypeInfo Info = getTypeInfo(T);
1495   return std::make_pair(toCharUnitsFromBits(Info.Width),
1496                         toCharUnitsFromBits(Info.Align));
1497 }
1498 
1499 std::pair<CharUnits, CharUnits>
getTypeInfoInChars(QualType T) const1500 ASTContext::getTypeInfoInChars(QualType T) const {
1501   return getTypeInfoInChars(T.getTypePtr());
1502 }
1503 
isAlignmentRequired(const Type * T) const1504 bool ASTContext::isAlignmentRequired(const Type *T) const {
1505   return getTypeInfo(T).AlignIsRequired;
1506 }
1507 
isAlignmentRequired(QualType T) const1508 bool ASTContext::isAlignmentRequired(QualType T) const {
1509   return isAlignmentRequired(T.getTypePtr());
1510 }
1511 
getTypeInfo(const Type * T) const1512 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1513   TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1514   if (I != MemoizedTypeInfo.end())
1515     return I->second;
1516 
1517   // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1518   TypeInfo TI = getTypeInfoImpl(T);
1519   MemoizedTypeInfo[T] = TI;
1520   return TI;
1521 }
1522 
1523 /// getTypeInfoImpl - Return the size of the specified type, in bits.  This
1524 /// method does not work on incomplete types.
1525 ///
1526 /// FIXME: Pointers into different addr spaces could have different sizes and
1527 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1528 /// should take a QualType, &c.
getTypeInfoImpl(const Type * T) const1529 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1530   uint64_t Width = 0;
1531   unsigned Align = 8;
1532   bool AlignIsRequired = false;
1533   switch (T->getTypeClass()) {
1534 #define TYPE(Class, Base)
1535 #define ABSTRACT_TYPE(Class, Base)
1536 #define NON_CANONICAL_TYPE(Class, Base)
1537 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1538 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
1539   case Type::Class:                                                            \
1540   assert(!T->isDependentType() && "should not see dependent types here");      \
1541   return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1542 #include "clang/AST/TypeNodes.def"
1543     llvm_unreachable("Should not see dependent types");
1544 
1545   case Type::FunctionNoProto:
1546   case Type::FunctionProto:
1547     // GCC extension: alignof(function) = 32 bits
1548     Width = 0;
1549     Align = 32;
1550     break;
1551 
1552   case Type::IncompleteArray:
1553   case Type::VariableArray:
1554     Width = 0;
1555     Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1556     break;
1557 
1558   case Type::ConstantArray: {
1559     const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1560 
1561     TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1562     uint64_t Size = CAT->getSize().getZExtValue();
1563     assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1564            "Overflow in array type bit size evaluation");
1565     Width = EltInfo.Width * Size;
1566     Align = EltInfo.Align;
1567     if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1568         getTargetInfo().getPointerWidth(0) == 64)
1569       Width = llvm::RoundUpToAlignment(Width, Align);
1570     break;
1571   }
1572   case Type::ExtVector:
1573   case Type::Vector: {
1574     const VectorType *VT = cast<VectorType>(T);
1575     TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1576     Width = EltInfo.Width * VT->getNumElements();
1577     Align = Width;
1578     // If the alignment is not a power of 2, round up to the next power of 2.
1579     // This happens for non-power-of-2 length vectors.
1580     if (Align & (Align-1)) {
1581       Align = llvm::NextPowerOf2(Align);
1582       Width = llvm::RoundUpToAlignment(Width, Align);
1583     }
1584     // Adjust the alignment based on the target max.
1585     uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1586     if (TargetVectorAlign && TargetVectorAlign < Align)
1587       Align = TargetVectorAlign;
1588     break;
1589   }
1590 
1591   case Type::Builtin:
1592     switch (cast<BuiltinType>(T)->getKind()) {
1593     default: llvm_unreachable("Unknown builtin type!");
1594     case BuiltinType::Void:
1595       // GCC extension: alignof(void) = 8 bits.
1596       Width = 0;
1597       Align = 8;
1598       break;
1599 
1600     case BuiltinType::Bool:
1601       Width = Target->getBoolWidth();
1602       Align = Target->getBoolAlign();
1603       break;
1604     case BuiltinType::Char_S:
1605     case BuiltinType::Char_U:
1606     case BuiltinType::UChar:
1607     case BuiltinType::SChar:
1608       Width = Target->getCharWidth();
1609       Align = Target->getCharAlign();
1610       break;
1611     case BuiltinType::WChar_S:
1612     case BuiltinType::WChar_U:
1613       Width = Target->getWCharWidth();
1614       Align = Target->getWCharAlign();
1615       break;
1616     case BuiltinType::Char16:
1617       Width = Target->getChar16Width();
1618       Align = Target->getChar16Align();
1619       break;
1620     case BuiltinType::Char32:
1621       Width = Target->getChar32Width();
1622       Align = Target->getChar32Align();
1623       break;
1624     case BuiltinType::UShort:
1625     case BuiltinType::Short:
1626       Width = Target->getShortWidth();
1627       Align = Target->getShortAlign();
1628       break;
1629     case BuiltinType::UInt:
1630     case BuiltinType::Int:
1631       Width = Target->getIntWidth();
1632       Align = Target->getIntAlign();
1633       break;
1634     case BuiltinType::ULong:
1635     case BuiltinType::Long:
1636       Width = Target->getLongWidth();
1637       Align = Target->getLongAlign();
1638       break;
1639     case BuiltinType::ULongLong:
1640     case BuiltinType::LongLong:
1641       Width = Target->getLongLongWidth();
1642       Align = Target->getLongLongAlign();
1643       break;
1644     case BuiltinType::Int128:
1645     case BuiltinType::UInt128:
1646       Width = 128;
1647       Align = 128; // int128_t is 128-bit aligned on all targets.
1648       break;
1649     case BuiltinType::Half:
1650       Width = Target->getHalfWidth();
1651       Align = Target->getHalfAlign();
1652       break;
1653     case BuiltinType::Float:
1654       Width = Target->getFloatWidth();
1655       Align = Target->getFloatAlign();
1656       break;
1657     case BuiltinType::Double:
1658       Width = Target->getDoubleWidth();
1659       Align = Target->getDoubleAlign();
1660       break;
1661     case BuiltinType::LongDouble:
1662       Width = Target->getLongDoubleWidth();
1663       Align = Target->getLongDoubleAlign();
1664       break;
1665     case BuiltinType::NullPtr:
1666       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1667       Align = Target->getPointerAlign(0); //   == sizeof(void*)
1668       break;
1669     case BuiltinType::ObjCId:
1670     case BuiltinType::ObjCClass:
1671     case BuiltinType::ObjCSel:
1672       Width = Target->getPointerWidth(0);
1673       Align = Target->getPointerAlign(0);
1674       break;
1675     case BuiltinType::OCLSampler:
1676       // Samplers are modeled as integers.
1677       Width = Target->getIntWidth();
1678       Align = Target->getIntAlign();
1679       break;
1680     case BuiltinType::OCLEvent:
1681     case BuiltinType::OCLClkEvent:
1682     case BuiltinType::OCLQueue:
1683     case BuiltinType::OCLNDRange:
1684     case BuiltinType::OCLReserveID:
1685     case BuiltinType::OCLImage1d:
1686     case BuiltinType::OCLImage1dArray:
1687     case BuiltinType::OCLImage1dBuffer:
1688     case BuiltinType::OCLImage2d:
1689     case BuiltinType::OCLImage2dArray:
1690     case BuiltinType::OCLImage2dDepth:
1691     case BuiltinType::OCLImage2dArrayDepth:
1692     case BuiltinType::OCLImage2dMSAA:
1693     case BuiltinType::OCLImage2dArrayMSAA:
1694     case BuiltinType::OCLImage2dMSAADepth:
1695     case BuiltinType::OCLImage2dArrayMSAADepth:
1696     case BuiltinType::OCLImage3d:
1697       // Currently these types are pointers to opaque types.
1698       Width = Target->getPointerWidth(0);
1699       Align = Target->getPointerAlign(0);
1700       break;
1701     }
1702     break;
1703   case Type::ObjCObjectPointer:
1704     Width = Target->getPointerWidth(0);
1705     Align = Target->getPointerAlign(0);
1706     break;
1707   case Type::BlockPointer: {
1708     unsigned AS = getTargetAddressSpace(
1709         cast<BlockPointerType>(T)->getPointeeType());
1710     Width = Target->getPointerWidth(AS);
1711     Align = Target->getPointerAlign(AS);
1712     break;
1713   }
1714   case Type::LValueReference:
1715   case Type::RValueReference: {
1716     // alignof and sizeof should never enter this code path here, so we go
1717     // the pointer route.
1718     unsigned AS = getTargetAddressSpace(
1719         cast<ReferenceType>(T)->getPointeeType());
1720     Width = Target->getPointerWidth(AS);
1721     Align = Target->getPointerAlign(AS);
1722     break;
1723   }
1724   case Type::Pointer: {
1725     unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1726     Width = Target->getPointerWidth(AS);
1727     Align = Target->getPointerAlign(AS);
1728     break;
1729   }
1730   case Type::MemberPointer: {
1731     const MemberPointerType *MPT = cast<MemberPointerType>(T);
1732     std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1733     break;
1734   }
1735   case Type::Complex: {
1736     // Complex types have the same alignment as their elements, but twice the
1737     // size.
1738     TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1739     Width = EltInfo.Width * 2;
1740     Align = EltInfo.Align;
1741     break;
1742   }
1743   case Type::ObjCObject:
1744     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1745   case Type::Adjusted:
1746   case Type::Decayed:
1747     return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1748   case Type::ObjCInterface: {
1749     const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1750     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1751     Width = toBits(Layout.getSize());
1752     Align = toBits(Layout.getAlignment());
1753     break;
1754   }
1755   case Type::Record:
1756   case Type::Enum: {
1757     const TagType *TT = cast<TagType>(T);
1758 
1759     if (TT->getDecl()->isInvalidDecl()) {
1760       Width = 8;
1761       Align = 8;
1762       break;
1763     }
1764 
1765     if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1766       const EnumDecl *ED = ET->getDecl();
1767       TypeInfo Info =
1768           getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1769       if (unsigned AttrAlign = ED->getMaxAlignment()) {
1770         Info.Align = AttrAlign;
1771         Info.AlignIsRequired = true;
1772       }
1773       return Info;
1774     }
1775 
1776     const RecordType *RT = cast<RecordType>(TT);
1777     const RecordDecl *RD = RT->getDecl();
1778     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
1779     Width = toBits(Layout.getSize());
1780     Align = toBits(Layout.getAlignment());
1781     AlignIsRequired = RD->hasAttr<AlignedAttr>();
1782     break;
1783   }
1784 
1785   case Type::SubstTemplateTypeParm:
1786     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1787                        getReplacementType().getTypePtr());
1788 
1789   case Type::Auto: {
1790     const AutoType *A = cast<AutoType>(T);
1791     assert(!A->getDeducedType().isNull() &&
1792            "cannot request the size of an undeduced or dependent auto type");
1793     return getTypeInfo(A->getDeducedType().getTypePtr());
1794   }
1795 
1796   case Type::Paren:
1797     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1798 
1799   case Type::Typedef: {
1800     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1801     TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1802     // If the typedef has an aligned attribute on it, it overrides any computed
1803     // alignment we have.  This violates the GCC documentation (which says that
1804     // attribute(aligned) can only round up) but matches its implementation.
1805     if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
1806       Align = AttrAlign;
1807       AlignIsRequired = true;
1808     } else {
1809       Align = Info.Align;
1810       AlignIsRequired = Info.AlignIsRequired;
1811     }
1812     Width = Info.Width;
1813     break;
1814   }
1815 
1816   case Type::Elaborated:
1817     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1818 
1819   case Type::Attributed:
1820     return getTypeInfo(
1821                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1822 
1823   case Type::Atomic: {
1824     // Start with the base type information.
1825     TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1826     Width = Info.Width;
1827     Align = Info.Align;
1828 
1829     // If the size of the type doesn't exceed the platform's max
1830     // atomic promotion width, make the size and alignment more
1831     // favorable to atomic operations:
1832     if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1833       // Round the size up to a power of 2.
1834       if (!llvm::isPowerOf2_64(Width))
1835         Width = llvm::NextPowerOf2(Width);
1836 
1837       // Set the alignment equal to the size.
1838       Align = static_cast<unsigned>(Width);
1839     }
1840   }
1841 
1842   }
1843 
1844   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1845   return TypeInfo(Width, Align, AlignIsRequired);
1846 }
1847 
getOpenMPDefaultSimdAlign(QualType T) const1848 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1849   unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1850   // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1851   if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1852        getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1853       getTargetInfo().getABI() == "elfv1-qpx" &&
1854       T->isSpecificBuiltinType(BuiltinType::Double))
1855     SimdAlign = 256;
1856   return SimdAlign;
1857 }
1858 
1859 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
toCharUnitsFromBits(int64_t BitSize) const1860 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1861   return CharUnits::fromQuantity(BitSize / getCharWidth());
1862 }
1863 
1864 /// toBits - Convert a size in characters to a size in characters.
toBits(CharUnits CharSize) const1865 int64_t ASTContext::toBits(CharUnits CharSize) const {
1866   return CharSize.getQuantity() * getCharWidth();
1867 }
1868 
1869 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1870 /// This method does not work on incomplete types.
getTypeSizeInChars(QualType T) const1871 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1872   return getTypeInfoInChars(T).first;
1873 }
getTypeSizeInChars(const Type * T) const1874 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1875   return getTypeInfoInChars(T).first;
1876 }
1877 
1878 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1879 /// characters. This method does not work on incomplete types.
getTypeAlignInChars(QualType T) const1880 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1881   return toCharUnitsFromBits(getTypeAlign(T));
1882 }
getTypeAlignInChars(const Type * T) const1883 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1884   return toCharUnitsFromBits(getTypeAlign(T));
1885 }
1886 
1887 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1888 /// type for the current target in bits.  This can be different than the ABI
1889 /// alignment in cases where it is beneficial for performance to overalign
1890 /// a data type.
getPreferredTypeAlign(const Type * T) const1891 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1892   TypeInfo TI = getTypeInfo(T);
1893   unsigned ABIAlign = TI.Align;
1894 
1895   T = T->getBaseElementTypeUnsafe();
1896 
1897   // The preferred alignment of member pointers is that of a pointer.
1898   if (T->isMemberPointerType())
1899     return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1900 
1901   if (Target->getTriple().getArch() == llvm::Triple::xcore)
1902     return ABIAlign;  // Never overalign on XCore.
1903 
1904   // Double and long long should be naturally aligned if possible.
1905   if (const ComplexType *CT = T->getAs<ComplexType>())
1906     T = CT->getElementType().getTypePtr();
1907   if (const EnumType *ET = T->getAs<EnumType>())
1908     T = ET->getDecl()->getIntegerType().getTypePtr();
1909   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1910       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1911       T->isSpecificBuiltinType(BuiltinType::ULongLong))
1912     // Don't increase the alignment if an alignment attribute was specified on a
1913     // typedef declaration.
1914     if (!TI.AlignIsRequired)
1915       return std::max(ABIAlign, (unsigned)getTypeSize(T));
1916 
1917   return ABIAlign;
1918 }
1919 
1920 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1921 /// for __attribute__((aligned)) on this target, to be used if no alignment
1922 /// value is specified.
getTargetDefaultAlignForAttributeAligned() const1923 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
1924   return getTargetInfo().getDefaultAlignForAttributeAligned();
1925 }
1926 
1927 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
1928 /// to a global variable of the specified type.
getAlignOfGlobalVar(QualType T) const1929 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1930   return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1931 }
1932 
1933 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
1934 /// should be given to a global variable of the specified type.
getAlignOfGlobalVarInChars(QualType T) const1935 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1936   return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1937 }
1938 
getOffsetOfBaseWithVBPtr(const CXXRecordDecl * RD) const1939 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1940   CharUnits Offset = CharUnits::Zero();
1941   const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1942   while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1943     Offset += Layout->getBaseClassOffset(Base);
1944     Layout = &getASTRecordLayout(Base);
1945   }
1946   return Offset;
1947 }
1948 
1949 /// DeepCollectObjCIvars -
1950 /// This routine first collects all declared, but not synthesized, ivars in
1951 /// super class and then collects all ivars, including those synthesized for
1952 /// current class. This routine is used for implementation of current class
1953 /// when all ivars, declared and synthesized are known.
1954 ///
DeepCollectObjCIvars(const ObjCInterfaceDecl * OI,bool leafClass,SmallVectorImpl<const ObjCIvarDecl * > & Ivars) const1955 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1956                                       bool leafClass,
1957                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1958   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1959     DeepCollectObjCIvars(SuperClass, false, Ivars);
1960   if (!leafClass) {
1961     for (const auto *I : OI->ivars())
1962       Ivars.push_back(I);
1963   } else {
1964     ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1965     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1966          Iv= Iv->getNextIvar())
1967       Ivars.push_back(Iv);
1968   }
1969 }
1970 
1971 /// CollectInheritedProtocols - Collect all protocols in current class and
1972 /// those inherited by it.
CollectInheritedProtocols(const Decl * CDecl,llvm::SmallPtrSet<ObjCProtocolDecl *,8> & Protocols)1973 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1974                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1975   if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1976     // We can use protocol_iterator here instead of
1977     // all_referenced_protocol_iterator since we are walking all categories.
1978     for (auto *Proto : OI->all_referenced_protocols()) {
1979       CollectInheritedProtocols(Proto, Protocols);
1980     }
1981 
1982     // Categories of this Interface.
1983     for (const auto *Cat : OI->visible_categories())
1984       CollectInheritedProtocols(Cat, Protocols);
1985 
1986     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1987       while (SD) {
1988         CollectInheritedProtocols(SD, Protocols);
1989         SD = SD->getSuperClass();
1990       }
1991   } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1992     for (auto *Proto : OC->protocols()) {
1993       CollectInheritedProtocols(Proto, Protocols);
1994     }
1995   } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1996     // Insert the protocol.
1997     if (!Protocols.insert(
1998           const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1999       return;
2000 
2001     for (auto *Proto : OP->protocols())
2002       CollectInheritedProtocols(Proto, Protocols);
2003   }
2004 }
2005 
CountNonClassIvars(const ObjCInterfaceDecl * OI) const2006 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
2007   unsigned count = 0;
2008   // Count ivars declared in class extension.
2009   for (const auto *Ext : OI->known_extensions())
2010     count += Ext->ivar_size();
2011 
2012   // Count ivar defined in this class's implementation.  This
2013   // includes synthesized ivars.
2014   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
2015     count += ImplDecl->ivar_size();
2016 
2017   return count;
2018 }
2019 
isSentinelNullExpr(const Expr * E)2020 bool ASTContext::isSentinelNullExpr(const Expr *E) {
2021   if (!E)
2022     return false;
2023 
2024   // nullptr_t is always treated as null.
2025   if (E->getType()->isNullPtrType()) return true;
2026 
2027   if (E->getType()->isAnyPointerType() &&
2028       E->IgnoreParenCasts()->isNullPointerConstant(*this,
2029                                                 Expr::NPC_ValueDependentIsNull))
2030     return true;
2031 
2032   // Unfortunately, __null has type 'int'.
2033   if (isa<GNUNullExpr>(E)) return true;
2034 
2035   return false;
2036 }
2037 
2038 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
getObjCImplementation(ObjCInterfaceDecl * D)2039 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2040   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2041     I = ObjCImpls.find(D);
2042   if (I != ObjCImpls.end())
2043     return cast<ObjCImplementationDecl>(I->second);
2044   return nullptr;
2045 }
2046 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
getObjCImplementation(ObjCCategoryDecl * D)2047 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2048   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2049     I = ObjCImpls.find(D);
2050   if (I != ObjCImpls.end())
2051     return cast<ObjCCategoryImplDecl>(I->second);
2052   return nullptr;
2053 }
2054 
2055 /// \brief Set the implementation of ObjCInterfaceDecl.
setObjCImplementation(ObjCInterfaceDecl * IFaceD,ObjCImplementationDecl * ImplD)2056 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2057                            ObjCImplementationDecl *ImplD) {
2058   assert(IFaceD && ImplD && "Passed null params");
2059   ObjCImpls[IFaceD] = ImplD;
2060 }
2061 /// \brief Set the implementation of ObjCCategoryDecl.
setObjCImplementation(ObjCCategoryDecl * CatD,ObjCCategoryImplDecl * ImplD)2062 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2063                            ObjCCategoryImplDecl *ImplD) {
2064   assert(CatD && ImplD && "Passed null params");
2065   ObjCImpls[CatD] = ImplD;
2066 }
2067 
getObjContainingInterface(const NamedDecl * ND) const2068 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2069                                               const NamedDecl *ND) const {
2070   if (const ObjCInterfaceDecl *ID =
2071           dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2072     return ID;
2073   if (const ObjCCategoryDecl *CD =
2074           dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2075     return CD->getClassInterface();
2076   if (const ObjCImplDecl *IMD =
2077           dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2078     return IMD->getClassInterface();
2079 
2080   return nullptr;
2081 }
2082 
2083 /// \brief Get the copy initialization expression of VarDecl,or NULL if
2084 /// none exists.
getBlockVarCopyInits(const VarDecl * VD)2085 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
2086   assert(VD && "Passed null params");
2087   assert(VD->hasAttr<BlocksAttr>() &&
2088          "getBlockVarCopyInits - not __block var");
2089   llvm::DenseMap<const VarDecl*, Expr*>::iterator
2090     I = BlockVarCopyInits.find(VD);
2091   return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
2092 }
2093 
2094 /// \brief Set the copy inialization expression of a block var decl.
setBlockVarCopyInits(VarDecl * VD,Expr * Init)2095 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2096   assert(VD && Init && "Passed null params");
2097   assert(VD->hasAttr<BlocksAttr>() &&
2098          "setBlockVarCopyInits - not __block var");
2099   BlockVarCopyInits[VD] = Init;
2100 }
2101 
CreateTypeSourceInfo(QualType T,unsigned DataSize) const2102 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2103                                                  unsigned DataSize) const {
2104   if (!DataSize)
2105     DataSize = TypeLoc::getFullDataSizeForType(T);
2106   else
2107     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2108            "incorrect data size provided to CreateTypeSourceInfo!");
2109 
2110   TypeSourceInfo *TInfo =
2111     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2112   new (TInfo) TypeSourceInfo(T);
2113   return TInfo;
2114 }
2115 
getTrivialTypeSourceInfo(QualType T,SourceLocation L) const2116 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2117                                                      SourceLocation L) const {
2118   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2119   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2120   return DI;
2121 }
2122 
2123 const ASTRecordLayout &
getASTObjCInterfaceLayout(const ObjCInterfaceDecl * D) const2124 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2125   return getObjCLayout(D, nullptr);
2126 }
2127 
2128 const ASTRecordLayout &
getASTObjCImplementationLayout(const ObjCImplementationDecl * D) const2129 ASTContext::getASTObjCImplementationLayout(
2130                                         const ObjCImplementationDecl *D) const {
2131   return getObjCLayout(D->getClassInterface(), D);
2132 }
2133 
2134 //===----------------------------------------------------------------------===//
2135 //                   Type creation/memoization methods
2136 //===----------------------------------------------------------------------===//
2137 
2138 QualType
getExtQualType(const Type * baseType,Qualifiers quals) const2139 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2140   unsigned fastQuals = quals.getFastQualifiers();
2141   quals.removeFastQualifiers();
2142 
2143   // Check if we've already instantiated this type.
2144   llvm::FoldingSetNodeID ID;
2145   ExtQuals::Profile(ID, baseType, quals);
2146   void *insertPos = nullptr;
2147   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2148     assert(eq->getQualifiers() == quals);
2149     return QualType(eq, fastQuals);
2150   }
2151 
2152   // If the base type is not canonical, make the appropriate canonical type.
2153   QualType canon;
2154   if (!baseType->isCanonicalUnqualified()) {
2155     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2156     canonSplit.Quals.addConsistentQualifiers(quals);
2157     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2158 
2159     // Re-find the insert position.
2160     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2161   }
2162 
2163   ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2164   ExtQualNodes.InsertNode(eq, insertPos);
2165   return QualType(eq, fastQuals);
2166 }
2167 
2168 QualType
getAddrSpaceQualType(QualType T,unsigned AddressSpace) const2169 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2170   QualType CanT = getCanonicalType(T);
2171   if (CanT.getAddressSpace() == AddressSpace)
2172     return T;
2173 
2174   // If we are composing extended qualifiers together, merge together
2175   // into one ExtQuals node.
2176   QualifierCollector Quals;
2177   const Type *TypeNode = Quals.strip(T);
2178 
2179   // If this type already has an address space specified, it cannot get
2180   // another one.
2181   assert(!Quals.hasAddressSpace() &&
2182          "Type cannot be in multiple addr spaces!");
2183   Quals.addAddressSpace(AddressSpace);
2184 
2185   return getExtQualType(TypeNode, Quals);
2186 }
2187 
getObjCGCQualType(QualType T,Qualifiers::GC GCAttr) const2188 QualType ASTContext::getObjCGCQualType(QualType T,
2189                                        Qualifiers::GC GCAttr) const {
2190   QualType CanT = getCanonicalType(T);
2191   if (CanT.getObjCGCAttr() == GCAttr)
2192     return T;
2193 
2194   if (const PointerType *ptr = T->getAs<PointerType>()) {
2195     QualType Pointee = ptr->getPointeeType();
2196     if (Pointee->isAnyPointerType()) {
2197       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2198       return getPointerType(ResultType);
2199     }
2200   }
2201 
2202   // If we are composing extended qualifiers together, merge together
2203   // into one ExtQuals node.
2204   QualifierCollector Quals;
2205   const Type *TypeNode = Quals.strip(T);
2206 
2207   // If this type already has an ObjCGC specified, it cannot get
2208   // another one.
2209   assert(!Quals.hasObjCGCAttr() &&
2210          "Type cannot have multiple ObjCGCs!");
2211   Quals.addObjCGCAttr(GCAttr);
2212 
2213   return getExtQualType(TypeNode, Quals);
2214 }
2215 
adjustFunctionType(const FunctionType * T,FunctionType::ExtInfo Info)2216 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2217                                                    FunctionType::ExtInfo Info) {
2218   if (T->getExtInfo() == Info)
2219     return T;
2220 
2221   QualType Result;
2222   if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2223     Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2224   } else {
2225     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2226     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2227     EPI.ExtInfo = Info;
2228     Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2229   }
2230 
2231   return cast<FunctionType>(Result.getTypePtr());
2232 }
2233 
adjustDeducedFunctionResultType(FunctionDecl * FD,QualType ResultType)2234 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2235                                                  QualType ResultType) {
2236   FD = FD->getMostRecentDecl();
2237   while (true) {
2238     const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2239     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2240     FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2241     if (FunctionDecl *Next = FD->getPreviousDecl())
2242       FD = Next;
2243     else
2244       break;
2245   }
2246   if (ASTMutationListener *L = getASTMutationListener())
2247     L->DeducedReturnType(FD, ResultType);
2248 }
2249 
2250 /// Get a function type and produce the equivalent function type with the
2251 /// specified exception specification. Type sugar that can be present on a
2252 /// declaration of a function with an exception specification is permitted
2253 /// and preserved. Other type sugar (for instance, typedefs) is not.
getFunctionTypeWithExceptionSpec(ASTContext & Context,QualType Orig,const FunctionProtoType::ExceptionSpecInfo & ESI)2254 static QualType getFunctionTypeWithExceptionSpec(
2255     ASTContext &Context, QualType Orig,
2256     const FunctionProtoType::ExceptionSpecInfo &ESI) {
2257   // Might have some parens.
2258   if (auto *PT = dyn_cast<ParenType>(Orig))
2259     return Context.getParenType(
2260         getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2261 
2262   // Might have a calling-convention attribute.
2263   if (auto *AT = dyn_cast<AttributedType>(Orig))
2264     return Context.getAttributedType(
2265         AT->getAttrKind(),
2266         getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2267         getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2268                                          ESI));
2269 
2270   // Anything else must be a function type. Rebuild it with the new exception
2271   // specification.
2272   const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2273   return Context.getFunctionType(
2274       Proto->getReturnType(), Proto->getParamTypes(),
2275       Proto->getExtProtoInfo().withExceptionSpec(ESI));
2276 }
2277 
adjustExceptionSpec(FunctionDecl * FD,const FunctionProtoType::ExceptionSpecInfo & ESI,bool AsWritten)2278 void ASTContext::adjustExceptionSpec(
2279     FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2280     bool AsWritten) {
2281   // Update the type.
2282   QualType Updated =
2283       getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2284   FD->setType(Updated);
2285 
2286   if (!AsWritten)
2287     return;
2288 
2289   // Update the type in the type source information too.
2290   if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2291     // If the type and the type-as-written differ, we may need to update
2292     // the type-as-written too.
2293     if (TSInfo->getType() != FD->getType())
2294       Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2295 
2296     // FIXME: When we get proper type location information for exceptions,
2297     // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2298     // up the TypeSourceInfo;
2299     assert(TypeLoc::getFullDataSizeForType(Updated) ==
2300                TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2301            "TypeLoc size mismatch from updating exception specification");
2302     TSInfo->overrideType(Updated);
2303   }
2304 }
2305 
2306 /// getComplexType - Return the uniqued reference to the type for a complex
2307 /// number with the specified element type.
getComplexType(QualType T) const2308 QualType ASTContext::getComplexType(QualType T) const {
2309   // Unique pointers, to guarantee there is only one pointer of a particular
2310   // structure.
2311   llvm::FoldingSetNodeID ID;
2312   ComplexType::Profile(ID, T);
2313 
2314   void *InsertPos = nullptr;
2315   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2316     return QualType(CT, 0);
2317 
2318   // If the pointee type isn't canonical, this won't be a canonical type either,
2319   // so fill in the canonical type field.
2320   QualType Canonical;
2321   if (!T.isCanonical()) {
2322     Canonical = getComplexType(getCanonicalType(T));
2323 
2324     // Get the new insert position for the node we care about.
2325     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2326     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2327   }
2328   ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2329   Types.push_back(New);
2330   ComplexTypes.InsertNode(New, InsertPos);
2331   return QualType(New, 0);
2332 }
2333 
2334 /// getPointerType - Return the uniqued reference to the type for a pointer to
2335 /// the specified type.
getPointerType(QualType T) const2336 QualType ASTContext::getPointerType(QualType T) const {
2337   // Unique pointers, to guarantee there is only one pointer of a particular
2338   // structure.
2339   llvm::FoldingSetNodeID ID;
2340   PointerType::Profile(ID, T);
2341 
2342   void *InsertPos = nullptr;
2343   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2344     return QualType(PT, 0);
2345 
2346   // If the pointee type isn't canonical, this won't be a canonical type either,
2347   // so fill in the canonical type field.
2348   QualType Canonical;
2349   if (!T.isCanonical()) {
2350     Canonical = getPointerType(getCanonicalType(T));
2351 
2352     // Get the new insert position for the node we care about.
2353     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2354     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2355   }
2356   PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2357   Types.push_back(New);
2358   PointerTypes.InsertNode(New, InsertPos);
2359   return QualType(New, 0);
2360 }
2361 
getAdjustedType(QualType Orig,QualType New) const2362 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2363   llvm::FoldingSetNodeID ID;
2364   AdjustedType::Profile(ID, Orig, New);
2365   void *InsertPos = nullptr;
2366   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2367   if (AT)
2368     return QualType(AT, 0);
2369 
2370   QualType Canonical = getCanonicalType(New);
2371 
2372   // Get the new insert position for the node we care about.
2373   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2374   assert(!AT && "Shouldn't be in the map!");
2375 
2376   AT = new (*this, TypeAlignment)
2377       AdjustedType(Type::Adjusted, Orig, New, Canonical);
2378   Types.push_back(AT);
2379   AdjustedTypes.InsertNode(AT, InsertPos);
2380   return QualType(AT, 0);
2381 }
2382 
getDecayedType(QualType T) const2383 QualType ASTContext::getDecayedType(QualType T) const {
2384   assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2385 
2386   QualType Decayed;
2387 
2388   // C99 6.7.5.3p7:
2389   //   A declaration of a parameter as "array of type" shall be
2390   //   adjusted to "qualified pointer to type", where the type
2391   //   qualifiers (if any) are those specified within the [ and ] of
2392   //   the array type derivation.
2393   if (T->isArrayType())
2394     Decayed = getArrayDecayedType(T);
2395 
2396   // C99 6.7.5.3p8:
2397   //   A declaration of a parameter as "function returning type"
2398   //   shall be adjusted to "pointer to function returning type", as
2399   //   in 6.3.2.1.
2400   if (T->isFunctionType())
2401     Decayed = getPointerType(T);
2402 
2403   llvm::FoldingSetNodeID ID;
2404   AdjustedType::Profile(ID, T, Decayed);
2405   void *InsertPos = nullptr;
2406   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2407   if (AT)
2408     return QualType(AT, 0);
2409 
2410   QualType Canonical = getCanonicalType(Decayed);
2411 
2412   // Get the new insert position for the node we care about.
2413   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2414   assert(!AT && "Shouldn't be in the map!");
2415 
2416   AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2417   Types.push_back(AT);
2418   AdjustedTypes.InsertNode(AT, InsertPos);
2419   return QualType(AT, 0);
2420 }
2421 
2422 /// getBlockPointerType - Return the uniqued reference to the type for
2423 /// a pointer to the specified block.
getBlockPointerType(QualType T) const2424 QualType ASTContext::getBlockPointerType(QualType T) const {
2425   assert(T->isFunctionType() && "block of function types only");
2426   // Unique pointers, to guarantee there is only one block of a particular
2427   // structure.
2428   llvm::FoldingSetNodeID ID;
2429   BlockPointerType::Profile(ID, T);
2430 
2431   void *InsertPos = nullptr;
2432   if (BlockPointerType *PT =
2433         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2434     return QualType(PT, 0);
2435 
2436   // If the block pointee type isn't canonical, this won't be a canonical
2437   // type either so fill in the canonical type field.
2438   QualType Canonical;
2439   if (!T.isCanonical()) {
2440     Canonical = getBlockPointerType(getCanonicalType(T));
2441 
2442     // Get the new insert position for the node we care about.
2443     BlockPointerType *NewIP =
2444       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2445     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2446   }
2447   BlockPointerType *New
2448     = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2449   Types.push_back(New);
2450   BlockPointerTypes.InsertNode(New, InsertPos);
2451   return QualType(New, 0);
2452 }
2453 
2454 /// getLValueReferenceType - Return the uniqued reference to the type for an
2455 /// lvalue reference to the specified type.
2456 QualType
getLValueReferenceType(QualType T,bool SpelledAsLValue) const2457 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2458   assert(getCanonicalType(T) != OverloadTy &&
2459          "Unresolved overloaded function type");
2460 
2461   // Unique pointers, to guarantee there is only one pointer of a particular
2462   // structure.
2463   llvm::FoldingSetNodeID ID;
2464   ReferenceType::Profile(ID, T, SpelledAsLValue);
2465 
2466   void *InsertPos = nullptr;
2467   if (LValueReferenceType *RT =
2468         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2469     return QualType(RT, 0);
2470 
2471   const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2472 
2473   // If the referencee type isn't canonical, this won't be a canonical type
2474   // either, so fill in the canonical type field.
2475   QualType Canonical;
2476   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2477     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2478     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2479 
2480     // Get the new insert position for the node we care about.
2481     LValueReferenceType *NewIP =
2482       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2483     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2484   }
2485 
2486   LValueReferenceType *New
2487     = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2488                                                      SpelledAsLValue);
2489   Types.push_back(New);
2490   LValueReferenceTypes.InsertNode(New, InsertPos);
2491 
2492   return QualType(New, 0);
2493 }
2494 
2495 /// getRValueReferenceType - Return the uniqued reference to the type for an
2496 /// rvalue reference to the specified type.
getRValueReferenceType(QualType T) const2497 QualType ASTContext::getRValueReferenceType(QualType T) const {
2498   // Unique pointers, to guarantee there is only one pointer of a particular
2499   // structure.
2500   llvm::FoldingSetNodeID ID;
2501   ReferenceType::Profile(ID, T, false);
2502 
2503   void *InsertPos = nullptr;
2504   if (RValueReferenceType *RT =
2505         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2506     return QualType(RT, 0);
2507 
2508   const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2509 
2510   // If the referencee type isn't canonical, this won't be a canonical type
2511   // either, so fill in the canonical type field.
2512   QualType Canonical;
2513   if (InnerRef || !T.isCanonical()) {
2514     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2515     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2516 
2517     // Get the new insert position for the node we care about.
2518     RValueReferenceType *NewIP =
2519       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2520     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2521   }
2522 
2523   RValueReferenceType *New
2524     = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2525   Types.push_back(New);
2526   RValueReferenceTypes.InsertNode(New, InsertPos);
2527   return QualType(New, 0);
2528 }
2529 
2530 /// getMemberPointerType - Return the uniqued reference to the type for a
2531 /// member pointer to the specified type, in the specified class.
getMemberPointerType(QualType T,const Type * Cls) const2532 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2533   // Unique pointers, to guarantee there is only one pointer of a particular
2534   // structure.
2535   llvm::FoldingSetNodeID ID;
2536   MemberPointerType::Profile(ID, T, Cls);
2537 
2538   void *InsertPos = nullptr;
2539   if (MemberPointerType *PT =
2540       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2541     return QualType(PT, 0);
2542 
2543   // If the pointee or class type isn't canonical, this won't be a canonical
2544   // type either, so fill in the canonical type field.
2545   QualType Canonical;
2546   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2547     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2548 
2549     // Get the new insert position for the node we care about.
2550     MemberPointerType *NewIP =
2551       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2552     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2553   }
2554   MemberPointerType *New
2555     = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2556   Types.push_back(New);
2557   MemberPointerTypes.InsertNode(New, InsertPos);
2558   return QualType(New, 0);
2559 }
2560 
2561 /// getConstantArrayType - Return the unique reference to the type for an
2562 /// array of the specified element type.
getConstantArrayType(QualType EltTy,const llvm::APInt & ArySizeIn,ArrayType::ArraySizeModifier ASM,unsigned IndexTypeQuals) const2563 QualType ASTContext::getConstantArrayType(QualType EltTy,
2564                                           const llvm::APInt &ArySizeIn,
2565                                           ArrayType::ArraySizeModifier ASM,
2566                                           unsigned IndexTypeQuals) const {
2567   assert((EltTy->isDependentType() ||
2568           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2569          "Constant array of VLAs is illegal!");
2570 
2571   // Convert the array size into a canonical width matching the pointer size for
2572   // the target.
2573   llvm::APInt ArySize(ArySizeIn);
2574   ArySize =
2575     ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2576 
2577   llvm::FoldingSetNodeID ID;
2578   ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2579 
2580   void *InsertPos = nullptr;
2581   if (ConstantArrayType *ATP =
2582       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2583     return QualType(ATP, 0);
2584 
2585   // If the element type isn't canonical or has qualifiers, this won't
2586   // be a canonical type either, so fill in the canonical type field.
2587   QualType Canon;
2588   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2589     SplitQualType canonSplit = getCanonicalType(EltTy).split();
2590     Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2591                                  ASM, IndexTypeQuals);
2592     Canon = getQualifiedType(Canon, canonSplit.Quals);
2593 
2594     // Get the new insert position for the node we care about.
2595     ConstantArrayType *NewIP =
2596       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2597     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2598   }
2599 
2600   ConstantArrayType *New = new(*this,TypeAlignment)
2601     ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2602   ConstantArrayTypes.InsertNode(New, InsertPos);
2603   Types.push_back(New);
2604   return QualType(New, 0);
2605 }
2606 
2607 /// getVariableArrayDecayedType - Turns the given type, which may be
2608 /// variably-modified, into the corresponding type with all the known
2609 /// sizes replaced with [*].
getVariableArrayDecayedType(QualType type) const2610 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2611   // Vastly most common case.
2612   if (!type->isVariablyModifiedType()) return type;
2613 
2614   QualType result;
2615 
2616   SplitQualType split = type.getSplitDesugaredType();
2617   const Type *ty = split.Ty;
2618   switch (ty->getTypeClass()) {
2619 #define TYPE(Class, Base)
2620 #define ABSTRACT_TYPE(Class, Base)
2621 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2622 #include "clang/AST/TypeNodes.def"
2623     llvm_unreachable("didn't desugar past all non-canonical types?");
2624 
2625   // These types should never be variably-modified.
2626   case Type::Builtin:
2627   case Type::Complex:
2628   case Type::Vector:
2629   case Type::ExtVector:
2630   case Type::DependentSizedExtVector:
2631   case Type::ObjCObject:
2632   case Type::ObjCInterface:
2633   case Type::ObjCObjectPointer:
2634   case Type::Record:
2635   case Type::Enum:
2636   case Type::UnresolvedUsing:
2637   case Type::TypeOfExpr:
2638   case Type::TypeOf:
2639   case Type::Decltype:
2640   case Type::UnaryTransform:
2641   case Type::DependentName:
2642   case Type::InjectedClassName:
2643   case Type::TemplateSpecialization:
2644   case Type::DependentTemplateSpecialization:
2645   case Type::TemplateTypeParm:
2646   case Type::SubstTemplateTypeParmPack:
2647   case Type::Auto:
2648   case Type::PackExpansion:
2649     llvm_unreachable("type should never be variably-modified");
2650 
2651   // These types can be variably-modified but should never need to
2652   // further decay.
2653   case Type::FunctionNoProto:
2654   case Type::FunctionProto:
2655   case Type::BlockPointer:
2656   case Type::MemberPointer:
2657     return type;
2658 
2659   // These types can be variably-modified.  All these modifications
2660   // preserve structure except as noted by comments.
2661   // TODO: if we ever care about optimizing VLAs, there are no-op
2662   // optimizations available here.
2663   case Type::Pointer:
2664     result = getPointerType(getVariableArrayDecayedType(
2665                               cast<PointerType>(ty)->getPointeeType()));
2666     break;
2667 
2668   case Type::LValueReference: {
2669     const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2670     result = getLValueReferenceType(
2671                  getVariableArrayDecayedType(lv->getPointeeType()),
2672                                     lv->isSpelledAsLValue());
2673     break;
2674   }
2675 
2676   case Type::RValueReference: {
2677     const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2678     result = getRValueReferenceType(
2679                  getVariableArrayDecayedType(lv->getPointeeType()));
2680     break;
2681   }
2682 
2683   case Type::Atomic: {
2684     const AtomicType *at = cast<AtomicType>(ty);
2685     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2686     break;
2687   }
2688 
2689   case Type::ConstantArray: {
2690     const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2691     result = getConstantArrayType(
2692                  getVariableArrayDecayedType(cat->getElementType()),
2693                                   cat->getSize(),
2694                                   cat->getSizeModifier(),
2695                                   cat->getIndexTypeCVRQualifiers());
2696     break;
2697   }
2698 
2699   case Type::DependentSizedArray: {
2700     const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2701     result = getDependentSizedArrayType(
2702                  getVariableArrayDecayedType(dat->getElementType()),
2703                                         dat->getSizeExpr(),
2704                                         dat->getSizeModifier(),
2705                                         dat->getIndexTypeCVRQualifiers(),
2706                                         dat->getBracketsRange());
2707     break;
2708   }
2709 
2710   // Turn incomplete types into [*] types.
2711   case Type::IncompleteArray: {
2712     const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2713     result = getVariableArrayType(
2714                  getVariableArrayDecayedType(iat->getElementType()),
2715                                   /*size*/ nullptr,
2716                                   ArrayType::Normal,
2717                                   iat->getIndexTypeCVRQualifiers(),
2718                                   SourceRange());
2719     break;
2720   }
2721 
2722   // Turn VLA types into [*] types.
2723   case Type::VariableArray: {
2724     const VariableArrayType *vat = cast<VariableArrayType>(ty);
2725     result = getVariableArrayType(
2726                  getVariableArrayDecayedType(vat->getElementType()),
2727                                   /*size*/ nullptr,
2728                                   ArrayType::Star,
2729                                   vat->getIndexTypeCVRQualifiers(),
2730                                   vat->getBracketsRange());
2731     break;
2732   }
2733   }
2734 
2735   // Apply the top-level qualifiers from the original.
2736   return getQualifiedType(result, split.Quals);
2737 }
2738 
2739 /// getVariableArrayType - Returns a non-unique reference to the type for a
2740 /// variable array of the specified element type.
getVariableArrayType(QualType EltTy,Expr * NumElts,ArrayType::ArraySizeModifier ASM,unsigned IndexTypeQuals,SourceRange Brackets) const2741 QualType ASTContext::getVariableArrayType(QualType EltTy,
2742                                           Expr *NumElts,
2743                                           ArrayType::ArraySizeModifier ASM,
2744                                           unsigned IndexTypeQuals,
2745                                           SourceRange Brackets) const {
2746   // Since we don't unique expressions, it isn't possible to unique VLA's
2747   // that have an expression provided for their size.
2748   QualType Canon;
2749 
2750   // Be sure to pull qualifiers off the element type.
2751   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2752     SplitQualType canonSplit = getCanonicalType(EltTy).split();
2753     Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2754                                  IndexTypeQuals, Brackets);
2755     Canon = getQualifiedType(Canon, canonSplit.Quals);
2756   }
2757 
2758   VariableArrayType *New = new(*this, TypeAlignment)
2759     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2760 
2761   VariableArrayTypes.push_back(New);
2762   Types.push_back(New);
2763   return QualType(New, 0);
2764 }
2765 
2766 /// getDependentSizedArrayType - Returns a non-unique reference to
2767 /// the type for a dependently-sized array of the specified element
2768 /// type.
getDependentSizedArrayType(QualType elementType,Expr * numElements,ArrayType::ArraySizeModifier ASM,unsigned elementTypeQuals,SourceRange brackets) const2769 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2770                                                 Expr *numElements,
2771                                                 ArrayType::ArraySizeModifier ASM,
2772                                                 unsigned elementTypeQuals,
2773                                                 SourceRange brackets) const {
2774   assert((!numElements || numElements->isTypeDependent() ||
2775           numElements->isValueDependent()) &&
2776          "Size must be type- or value-dependent!");
2777 
2778   // Dependently-sized array types that do not have a specified number
2779   // of elements will have their sizes deduced from a dependent
2780   // initializer.  We do no canonicalization here at all, which is okay
2781   // because they can't be used in most locations.
2782   if (!numElements) {
2783     DependentSizedArrayType *newType
2784       = new (*this, TypeAlignment)
2785           DependentSizedArrayType(*this, elementType, QualType(),
2786                                   numElements, ASM, elementTypeQuals,
2787                                   brackets);
2788     Types.push_back(newType);
2789     return QualType(newType, 0);
2790   }
2791 
2792   // Otherwise, we actually build a new type every time, but we
2793   // also build a canonical type.
2794 
2795   SplitQualType canonElementType = getCanonicalType(elementType).split();
2796 
2797   void *insertPos = nullptr;
2798   llvm::FoldingSetNodeID ID;
2799   DependentSizedArrayType::Profile(ID, *this,
2800                                    QualType(canonElementType.Ty, 0),
2801                                    ASM, elementTypeQuals, numElements);
2802 
2803   // Look for an existing type with these properties.
2804   DependentSizedArrayType *canonTy =
2805     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2806 
2807   // If we don't have one, build one.
2808   if (!canonTy) {
2809     canonTy = new (*this, TypeAlignment)
2810       DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2811                               QualType(), numElements, ASM, elementTypeQuals,
2812                               brackets);
2813     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2814     Types.push_back(canonTy);
2815   }
2816 
2817   // Apply qualifiers from the element type to the array.
2818   QualType canon = getQualifiedType(QualType(canonTy,0),
2819                                     canonElementType.Quals);
2820 
2821   // If we didn't need extra canonicalization for the element type or the size
2822   // expression, then just use that as our result.
2823   if (QualType(canonElementType.Ty, 0) == elementType &&
2824       canonTy->getSizeExpr() == numElements)
2825     return canon;
2826 
2827   // Otherwise, we need to build a type which follows the spelling
2828   // of the element type.
2829   DependentSizedArrayType *sugaredType
2830     = new (*this, TypeAlignment)
2831         DependentSizedArrayType(*this, elementType, canon, numElements,
2832                                 ASM, elementTypeQuals, brackets);
2833   Types.push_back(sugaredType);
2834   return QualType(sugaredType, 0);
2835 }
2836 
getIncompleteArrayType(QualType elementType,ArrayType::ArraySizeModifier ASM,unsigned elementTypeQuals) const2837 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2838                                             ArrayType::ArraySizeModifier ASM,
2839                                             unsigned elementTypeQuals) const {
2840   llvm::FoldingSetNodeID ID;
2841   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2842 
2843   void *insertPos = nullptr;
2844   if (IncompleteArrayType *iat =
2845        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2846     return QualType(iat, 0);
2847 
2848   // If the element type isn't canonical, this won't be a canonical type
2849   // either, so fill in the canonical type field.  We also have to pull
2850   // qualifiers off the element type.
2851   QualType canon;
2852 
2853   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2854     SplitQualType canonSplit = getCanonicalType(elementType).split();
2855     canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2856                                    ASM, elementTypeQuals);
2857     canon = getQualifiedType(canon, canonSplit.Quals);
2858 
2859     // Get the new insert position for the node we care about.
2860     IncompleteArrayType *existing =
2861       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2862     assert(!existing && "Shouldn't be in the map!"); (void) existing;
2863   }
2864 
2865   IncompleteArrayType *newType = new (*this, TypeAlignment)
2866     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2867 
2868   IncompleteArrayTypes.InsertNode(newType, insertPos);
2869   Types.push_back(newType);
2870   return QualType(newType, 0);
2871 }
2872 
2873 /// getVectorType - Return the unique reference to a vector type of
2874 /// the specified element type and size. VectorType must be a built-in type.
getVectorType(QualType vecType,unsigned NumElts,VectorType::VectorKind VecKind) const2875 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2876                                    VectorType::VectorKind VecKind) const {
2877   assert(vecType->isBuiltinType());
2878 
2879   // Check if we've already instantiated a vector of this type.
2880   llvm::FoldingSetNodeID ID;
2881   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2882 
2883   void *InsertPos = nullptr;
2884   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2885     return QualType(VTP, 0);
2886 
2887   // If the element type isn't canonical, this won't be a canonical type either,
2888   // so fill in the canonical type field.
2889   QualType Canonical;
2890   if (!vecType.isCanonical()) {
2891     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2892 
2893     // Get the new insert position for the node we care about.
2894     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2895     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2896   }
2897   VectorType *New = new (*this, TypeAlignment)
2898     VectorType(vecType, NumElts, Canonical, VecKind);
2899   VectorTypes.InsertNode(New, InsertPos);
2900   Types.push_back(New);
2901   return QualType(New, 0);
2902 }
2903 
2904 /// getExtVectorType - Return the unique reference to an extended vector type of
2905 /// the specified element type and size. VectorType must be a built-in type.
2906 QualType
getExtVectorType(QualType vecType,unsigned NumElts) const2907 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2908   assert(vecType->isBuiltinType() || vecType->isDependentType());
2909 
2910   // Check if we've already instantiated a vector of this type.
2911   llvm::FoldingSetNodeID ID;
2912   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2913                       VectorType::GenericVector);
2914   void *InsertPos = nullptr;
2915   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2916     return QualType(VTP, 0);
2917 
2918   // If the element type isn't canonical, this won't be a canonical type either,
2919   // so fill in the canonical type field.
2920   QualType Canonical;
2921   if (!vecType.isCanonical()) {
2922     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2923 
2924     // Get the new insert position for the node we care about.
2925     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2926     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2927   }
2928   ExtVectorType *New = new (*this, TypeAlignment)
2929     ExtVectorType(vecType, NumElts, Canonical);
2930   VectorTypes.InsertNode(New, InsertPos);
2931   Types.push_back(New);
2932   return QualType(New, 0);
2933 }
2934 
2935 QualType
getDependentSizedExtVectorType(QualType vecType,Expr * SizeExpr,SourceLocation AttrLoc) const2936 ASTContext::getDependentSizedExtVectorType(QualType vecType,
2937                                            Expr *SizeExpr,
2938                                            SourceLocation AttrLoc) const {
2939   llvm::FoldingSetNodeID ID;
2940   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2941                                        SizeExpr);
2942 
2943   void *InsertPos = nullptr;
2944   DependentSizedExtVectorType *Canon
2945     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2946   DependentSizedExtVectorType *New;
2947   if (Canon) {
2948     // We already have a canonical version of this array type; use it as
2949     // the canonical type for a newly-built type.
2950     New = new (*this, TypeAlignment)
2951       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2952                                   SizeExpr, AttrLoc);
2953   } else {
2954     QualType CanonVecTy = getCanonicalType(vecType);
2955     if (CanonVecTy == vecType) {
2956       New = new (*this, TypeAlignment)
2957         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2958                                     AttrLoc);
2959 
2960       DependentSizedExtVectorType *CanonCheck
2961         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2962       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2963       (void)CanonCheck;
2964       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2965     } else {
2966       QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2967                                                       SourceLocation());
2968       New = new (*this, TypeAlignment)
2969         DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2970     }
2971   }
2972 
2973   Types.push_back(New);
2974   return QualType(New, 0);
2975 }
2976 
2977 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2978 ///
2979 QualType
getFunctionNoProtoType(QualType ResultTy,const FunctionType::ExtInfo & Info) const2980 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2981                                    const FunctionType::ExtInfo &Info) const {
2982   const CallingConv CallConv = Info.getCC();
2983 
2984   // Unique functions, to guarantee there is only one function of a particular
2985   // structure.
2986   llvm::FoldingSetNodeID ID;
2987   FunctionNoProtoType::Profile(ID, ResultTy, Info);
2988 
2989   void *InsertPos = nullptr;
2990   if (FunctionNoProtoType *FT =
2991         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2992     return QualType(FT, 0);
2993 
2994   QualType Canonical;
2995   if (!ResultTy.isCanonical()) {
2996     Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
2997 
2998     // Get the new insert position for the node we care about.
2999     FunctionNoProtoType *NewIP =
3000       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3001     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3002   }
3003 
3004   FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
3005   FunctionNoProtoType *New = new (*this, TypeAlignment)
3006     FunctionNoProtoType(ResultTy, Canonical, newInfo);
3007   Types.push_back(New);
3008   FunctionNoProtoTypes.InsertNode(New, InsertPos);
3009   return QualType(New, 0);
3010 }
3011 
3012 /// \brief Determine whether \p T is canonical as the result type of a function.
isCanonicalResultType(QualType T)3013 static bool isCanonicalResultType(QualType T) {
3014   return T.isCanonical() &&
3015          (T.getObjCLifetime() == Qualifiers::OCL_None ||
3016           T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3017 }
3018 
3019 CanQualType
getCanonicalFunctionResultType(QualType ResultType) const3020 ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3021   CanQualType CanResultType = getCanonicalType(ResultType);
3022 
3023   // Canonical result types do not have ARC lifetime qualifiers.
3024   if (CanResultType.getQualifiers().hasObjCLifetime()) {
3025     Qualifiers Qs = CanResultType.getQualifiers();
3026     Qs.removeObjCLifetime();
3027     return CanQualType::CreateUnsafe(
3028              getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3029   }
3030 
3031   return CanResultType;
3032 }
3033 
3034 QualType
getFunctionType(QualType ResultTy,ArrayRef<QualType> ArgArray,const FunctionProtoType::ExtProtoInfo & EPI) const3035 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
3036                             const FunctionProtoType::ExtProtoInfo &EPI) const {
3037   size_t NumArgs = ArgArray.size();
3038 
3039   // Unique functions, to guarantee there is only one function of a particular
3040   // structure.
3041   llvm::FoldingSetNodeID ID;
3042   FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3043                              *this);
3044 
3045   void *InsertPos = nullptr;
3046   if (FunctionProtoType *FTP =
3047         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
3048     return QualType(FTP, 0);
3049 
3050   // Determine whether the type being created is already canonical or not.
3051   bool isCanonical =
3052     EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
3053     !EPI.HasTrailingReturn;
3054   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
3055     if (!ArgArray[i].isCanonicalAsParam())
3056       isCanonical = false;
3057 
3058   // If this type isn't canonical, get the canonical version of it.
3059   // The exception spec is not part of the canonical type.
3060   QualType Canonical;
3061   if (!isCanonical) {
3062     SmallVector<QualType, 16> CanonicalArgs;
3063     CanonicalArgs.reserve(NumArgs);
3064     for (unsigned i = 0; i != NumArgs; ++i)
3065       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
3066 
3067     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
3068     CanonicalEPI.HasTrailingReturn = false;
3069     CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3070 
3071     // Adjust the canonical function result type.
3072     CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
3073     Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
3074 
3075     // Get the new insert position for the node we care about.
3076     FunctionProtoType *NewIP =
3077       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3078     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3079   }
3080 
3081   // FunctionProtoType objects are allocated with extra bytes after
3082   // them for three variable size arrays at the end:
3083   //  - parameter types
3084   //  - exception types
3085   //  - consumed-arguments flags
3086   // Instead of the exception types, there could be a noexcept
3087   // expression, or information used to resolve the exception
3088   // specification.
3089   size_t Size = sizeof(FunctionProtoType) +
3090                 NumArgs * sizeof(QualType);
3091   if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3092     Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3093   } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3094     Size += sizeof(Expr*);
3095   } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3096     Size += 2 * sizeof(FunctionDecl*);
3097   } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3098     Size += sizeof(FunctionDecl*);
3099   }
3100   if (EPI.ConsumedParameters)
3101     Size += NumArgs * sizeof(bool);
3102 
3103   FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
3104   FunctionProtoType::ExtProtoInfo newEPI = EPI;
3105   new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3106   Types.push_back(FTP);
3107   FunctionProtoTypes.InsertNode(FTP, InsertPos);
3108   return QualType(FTP, 0);
3109 }
3110 
3111 #ifndef NDEBUG
NeedsInjectedClassNameType(const RecordDecl * D)3112 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3113   if (!isa<CXXRecordDecl>(D)) return false;
3114   const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3115   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3116     return true;
3117   if (RD->getDescribedClassTemplate() &&
3118       !isa<ClassTemplateSpecializationDecl>(RD))
3119     return true;
3120   return false;
3121 }
3122 #endif
3123 
3124 /// getInjectedClassNameType - Return the unique reference to the
3125 /// injected class name type for the specified templated declaration.
getInjectedClassNameType(CXXRecordDecl * Decl,QualType TST) const3126 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
3127                                               QualType TST) const {
3128   assert(NeedsInjectedClassNameType(Decl));
3129   if (Decl->TypeForDecl) {
3130     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3131   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
3132     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3133     Decl->TypeForDecl = PrevDecl->TypeForDecl;
3134     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3135   } else {
3136     Type *newType =
3137       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
3138     Decl->TypeForDecl = newType;
3139     Types.push_back(newType);
3140   }
3141   return QualType(Decl->TypeForDecl, 0);
3142 }
3143 
3144 /// getTypeDeclType - Return the unique reference to the type for the
3145 /// specified type declaration.
getTypeDeclTypeSlow(const TypeDecl * Decl) const3146 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3147   assert(Decl && "Passed null for Decl param");
3148   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3149 
3150   if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3151     return getTypedefType(Typedef);
3152 
3153   assert(!isa<TemplateTypeParmDecl>(Decl) &&
3154          "Template type parameter types are always available.");
3155 
3156   if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
3157     assert(Record->isFirstDecl() && "struct/union has previous declaration");
3158     assert(!NeedsInjectedClassNameType(Record));
3159     return getRecordType(Record);
3160   } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
3161     assert(Enum->isFirstDecl() && "enum has previous declaration");
3162     return getEnumType(Enum);
3163   } else if (const UnresolvedUsingTypenameDecl *Using =
3164                dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3165     Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3166     Decl->TypeForDecl = newType;
3167     Types.push_back(newType);
3168   } else
3169     llvm_unreachable("TypeDecl without a type?");
3170 
3171   return QualType(Decl->TypeForDecl, 0);
3172 }
3173 
3174 /// getTypedefType - Return the unique reference to the type for the
3175 /// specified typedef name decl.
3176 QualType
getTypedefType(const TypedefNameDecl * Decl,QualType Canonical) const3177 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3178                            QualType Canonical) const {
3179   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3180 
3181   if (Canonical.isNull())
3182     Canonical = getCanonicalType(Decl->getUnderlyingType());
3183   TypedefType *newType = new(*this, TypeAlignment)
3184     TypedefType(Type::Typedef, Decl, Canonical);
3185   Decl->TypeForDecl = newType;
3186   Types.push_back(newType);
3187   return QualType(newType, 0);
3188 }
3189 
getRecordType(const RecordDecl * Decl) const3190 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
3191   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3192 
3193   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3194     if (PrevDecl->TypeForDecl)
3195       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3196 
3197   RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3198   Decl->TypeForDecl = newType;
3199   Types.push_back(newType);
3200   return QualType(newType, 0);
3201 }
3202 
getEnumType(const EnumDecl * Decl) const3203 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3204   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3205 
3206   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3207     if (PrevDecl->TypeForDecl)
3208       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3209 
3210   EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3211   Decl->TypeForDecl = newType;
3212   Types.push_back(newType);
3213   return QualType(newType, 0);
3214 }
3215 
getAttributedType(AttributedType::Kind attrKind,QualType modifiedType,QualType equivalentType)3216 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3217                                        QualType modifiedType,
3218                                        QualType equivalentType) {
3219   llvm::FoldingSetNodeID id;
3220   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3221 
3222   void *insertPos = nullptr;
3223   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3224   if (type) return QualType(type, 0);
3225 
3226   QualType canon = getCanonicalType(equivalentType);
3227   type = new (*this, TypeAlignment)
3228            AttributedType(canon, attrKind, modifiedType, equivalentType);
3229 
3230   Types.push_back(type);
3231   AttributedTypes.InsertNode(type, insertPos);
3232 
3233   return QualType(type, 0);
3234 }
3235 
3236 /// \brief Retrieve a substitution-result type.
3237 QualType
getSubstTemplateTypeParmType(const TemplateTypeParmType * Parm,QualType Replacement) const3238 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3239                                          QualType Replacement) const {
3240   assert(Replacement.isCanonical()
3241          && "replacement types must always be canonical");
3242 
3243   llvm::FoldingSetNodeID ID;
3244   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3245   void *InsertPos = nullptr;
3246   SubstTemplateTypeParmType *SubstParm
3247     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3248 
3249   if (!SubstParm) {
3250     SubstParm = new (*this, TypeAlignment)
3251       SubstTemplateTypeParmType(Parm, Replacement);
3252     Types.push_back(SubstParm);
3253     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3254   }
3255 
3256   return QualType(SubstParm, 0);
3257 }
3258 
3259 /// \brief Retrieve a
getSubstTemplateTypeParmPackType(const TemplateTypeParmType * Parm,const TemplateArgument & ArgPack)3260 QualType ASTContext::getSubstTemplateTypeParmPackType(
3261                                           const TemplateTypeParmType *Parm,
3262                                               const TemplateArgument &ArgPack) {
3263 #ifndef NDEBUG
3264   for (const auto &P : ArgPack.pack_elements()) {
3265     assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3266     assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
3267   }
3268 #endif
3269 
3270   llvm::FoldingSetNodeID ID;
3271   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3272   void *InsertPos = nullptr;
3273   if (SubstTemplateTypeParmPackType *SubstParm
3274         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3275     return QualType(SubstParm, 0);
3276 
3277   QualType Canon;
3278   if (!Parm->isCanonicalUnqualified()) {
3279     Canon = getCanonicalType(QualType(Parm, 0));
3280     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3281                                              ArgPack);
3282     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3283   }
3284 
3285   SubstTemplateTypeParmPackType *SubstParm
3286     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3287                                                                ArgPack);
3288   Types.push_back(SubstParm);
3289   SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3290   return QualType(SubstParm, 0);
3291 }
3292 
3293 /// \brief Retrieve the template type parameter type for a template
3294 /// parameter or parameter pack with the given depth, index, and (optionally)
3295 /// name.
getTemplateTypeParmType(unsigned Depth,unsigned Index,bool ParameterPack,TemplateTypeParmDecl * TTPDecl) const3296 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3297                                              bool ParameterPack,
3298                                              TemplateTypeParmDecl *TTPDecl) const {
3299   llvm::FoldingSetNodeID ID;
3300   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3301   void *InsertPos = nullptr;
3302   TemplateTypeParmType *TypeParm
3303     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3304 
3305   if (TypeParm)
3306     return QualType(TypeParm, 0);
3307 
3308   if (TTPDecl) {
3309     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3310     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3311 
3312     TemplateTypeParmType *TypeCheck
3313       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3314     assert(!TypeCheck && "Template type parameter canonical type broken");
3315     (void)TypeCheck;
3316   } else
3317     TypeParm = new (*this, TypeAlignment)
3318       TemplateTypeParmType(Depth, Index, ParameterPack);
3319 
3320   Types.push_back(TypeParm);
3321   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3322 
3323   return QualType(TypeParm, 0);
3324 }
3325 
3326 TypeSourceInfo *
getTemplateSpecializationTypeInfo(TemplateName Name,SourceLocation NameLoc,const TemplateArgumentListInfo & Args,QualType Underlying) const3327 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3328                                               SourceLocation NameLoc,
3329                                         const TemplateArgumentListInfo &Args,
3330                                               QualType Underlying) const {
3331   assert(!Name.getAsDependentTemplateName() &&
3332          "No dependent template names here!");
3333   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3334 
3335   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3336   TemplateSpecializationTypeLoc TL =
3337       DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3338   TL.setTemplateKeywordLoc(SourceLocation());
3339   TL.setTemplateNameLoc(NameLoc);
3340   TL.setLAngleLoc(Args.getLAngleLoc());
3341   TL.setRAngleLoc(Args.getRAngleLoc());
3342   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3343     TL.setArgLocInfo(i, Args[i].getLocInfo());
3344   return DI;
3345 }
3346 
3347 QualType
getTemplateSpecializationType(TemplateName Template,const TemplateArgumentListInfo & Args,QualType Underlying) const3348 ASTContext::getTemplateSpecializationType(TemplateName Template,
3349                                           const TemplateArgumentListInfo &Args,
3350                                           QualType Underlying) const {
3351   assert(!Template.getAsDependentTemplateName() &&
3352          "No dependent template names here!");
3353 
3354   unsigned NumArgs = Args.size();
3355 
3356   SmallVector<TemplateArgument, 4> ArgVec;
3357   ArgVec.reserve(NumArgs);
3358   for (unsigned i = 0; i != NumArgs; ++i)
3359     ArgVec.push_back(Args[i].getArgument());
3360 
3361   return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
3362                                        Underlying);
3363 }
3364 
3365 #ifndef NDEBUG
hasAnyPackExpansions(const TemplateArgument * Args,unsigned NumArgs)3366 static bool hasAnyPackExpansions(const TemplateArgument *Args,
3367                                  unsigned NumArgs) {
3368   for (unsigned I = 0; I != NumArgs; ++I)
3369     if (Args[I].isPackExpansion())
3370       return true;
3371 
3372   return true;
3373 }
3374 #endif
3375 
3376 QualType
getTemplateSpecializationType(TemplateName Template,const TemplateArgument * Args,unsigned NumArgs,QualType Underlying) const3377 ASTContext::getTemplateSpecializationType(TemplateName Template,
3378                                           const TemplateArgument *Args,
3379                                           unsigned NumArgs,
3380                                           QualType Underlying) const {
3381   assert(!Template.getAsDependentTemplateName() &&
3382          "No dependent template names here!");
3383   // Look through qualified template names.
3384   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3385     Template = TemplateName(QTN->getTemplateDecl());
3386 
3387   bool IsTypeAlias =
3388     Template.getAsTemplateDecl() &&
3389     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3390   QualType CanonType;
3391   if (!Underlying.isNull())
3392     CanonType = getCanonicalType(Underlying);
3393   else {
3394     // We can get here with an alias template when the specialization contains
3395     // a pack expansion that does not match up with a parameter pack.
3396     assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3397            "Caller must compute aliased type");
3398     IsTypeAlias = false;
3399     CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3400                                                        NumArgs);
3401   }
3402 
3403   // Allocate the (non-canonical) template specialization type, but don't
3404   // try to unique it: these types typically have location information that
3405   // we don't unique and don't want to lose.
3406   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3407                        sizeof(TemplateArgument) * NumArgs +
3408                        (IsTypeAlias? sizeof(QualType) : 0),
3409                        TypeAlignment);
3410   TemplateSpecializationType *Spec
3411     = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3412                                          IsTypeAlias ? Underlying : QualType());
3413 
3414   Types.push_back(Spec);
3415   return QualType(Spec, 0);
3416 }
3417 
3418 QualType
getCanonicalTemplateSpecializationType(TemplateName Template,const TemplateArgument * Args,unsigned NumArgs) const3419 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3420                                                    const TemplateArgument *Args,
3421                                                    unsigned NumArgs) const {
3422   assert(!Template.getAsDependentTemplateName() &&
3423          "No dependent template names here!");
3424 
3425   // Look through qualified template names.
3426   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3427     Template = TemplateName(QTN->getTemplateDecl());
3428 
3429   // Build the canonical template specialization type.
3430   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3431   SmallVector<TemplateArgument, 4> CanonArgs;
3432   CanonArgs.reserve(NumArgs);
3433   for (unsigned I = 0; I != NumArgs; ++I)
3434     CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3435 
3436   // Determine whether this canonical template specialization type already
3437   // exists.
3438   llvm::FoldingSetNodeID ID;
3439   TemplateSpecializationType::Profile(ID, CanonTemplate,
3440                                       CanonArgs.data(), NumArgs, *this);
3441 
3442   void *InsertPos = nullptr;
3443   TemplateSpecializationType *Spec
3444     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3445 
3446   if (!Spec) {
3447     // Allocate a new canonical template specialization type.
3448     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3449                           sizeof(TemplateArgument) * NumArgs),
3450                          TypeAlignment);
3451     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3452                                                 CanonArgs.data(), NumArgs,
3453                                                 QualType(), QualType());
3454     Types.push_back(Spec);
3455     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3456   }
3457 
3458   assert(Spec->isDependentType() &&
3459          "Non-dependent template-id type must have a canonical type");
3460   return QualType(Spec, 0);
3461 }
3462 
3463 QualType
getElaboratedType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,QualType NamedType) const3464 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3465                               NestedNameSpecifier *NNS,
3466                               QualType NamedType) const {
3467   llvm::FoldingSetNodeID ID;
3468   ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3469 
3470   void *InsertPos = nullptr;
3471   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3472   if (T)
3473     return QualType(T, 0);
3474 
3475   QualType Canon = NamedType;
3476   if (!Canon.isCanonical()) {
3477     Canon = getCanonicalType(NamedType);
3478     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3479     assert(!CheckT && "Elaborated canonical type broken");
3480     (void)CheckT;
3481   }
3482 
3483   T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
3484   Types.push_back(T);
3485   ElaboratedTypes.InsertNode(T, InsertPos);
3486   return QualType(T, 0);
3487 }
3488 
3489 QualType
getParenType(QualType InnerType) const3490 ASTContext::getParenType(QualType InnerType) const {
3491   llvm::FoldingSetNodeID ID;
3492   ParenType::Profile(ID, InnerType);
3493 
3494   void *InsertPos = nullptr;
3495   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3496   if (T)
3497     return QualType(T, 0);
3498 
3499   QualType Canon = InnerType;
3500   if (!Canon.isCanonical()) {
3501     Canon = getCanonicalType(InnerType);
3502     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3503     assert(!CheckT && "Paren canonical type broken");
3504     (void)CheckT;
3505   }
3506 
3507   T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
3508   Types.push_back(T);
3509   ParenTypes.InsertNode(T, InsertPos);
3510   return QualType(T, 0);
3511 }
3512 
getDependentNameType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,const IdentifierInfo * Name,QualType Canon) const3513 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3514                                           NestedNameSpecifier *NNS,
3515                                           const IdentifierInfo *Name,
3516                                           QualType Canon) const {
3517   if (Canon.isNull()) {
3518     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3519     ElaboratedTypeKeyword CanonKeyword = Keyword;
3520     if (Keyword == ETK_None)
3521       CanonKeyword = ETK_Typename;
3522 
3523     if (CanonNNS != NNS || CanonKeyword != Keyword)
3524       Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3525   }
3526 
3527   llvm::FoldingSetNodeID ID;
3528   DependentNameType::Profile(ID, Keyword, NNS, Name);
3529 
3530   void *InsertPos = nullptr;
3531   DependentNameType *T
3532     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3533   if (T)
3534     return QualType(T, 0);
3535 
3536   T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
3537   Types.push_back(T);
3538   DependentNameTypes.InsertNode(T, InsertPos);
3539   return QualType(T, 0);
3540 }
3541 
3542 QualType
getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,const IdentifierInfo * Name,const TemplateArgumentListInfo & Args) const3543 ASTContext::getDependentTemplateSpecializationType(
3544                                  ElaboratedTypeKeyword Keyword,
3545                                  NestedNameSpecifier *NNS,
3546                                  const IdentifierInfo *Name,
3547                                  const TemplateArgumentListInfo &Args) const {
3548   // TODO: avoid this copy
3549   SmallVector<TemplateArgument, 16> ArgCopy;
3550   for (unsigned I = 0, E = Args.size(); I != E; ++I)
3551     ArgCopy.push_back(Args[I].getArgument());
3552   return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3553                                                 ArgCopy.size(),
3554                                                 ArgCopy.data());
3555 }
3556 
3557 QualType
getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,const IdentifierInfo * Name,unsigned NumArgs,const TemplateArgument * Args) const3558 ASTContext::getDependentTemplateSpecializationType(
3559                                  ElaboratedTypeKeyword Keyword,
3560                                  NestedNameSpecifier *NNS,
3561                                  const IdentifierInfo *Name,
3562                                  unsigned NumArgs,
3563                                  const TemplateArgument *Args) const {
3564   assert((!NNS || NNS->isDependent()) &&
3565          "nested-name-specifier must be dependent");
3566 
3567   llvm::FoldingSetNodeID ID;
3568   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3569                                                Name, NumArgs, Args);
3570 
3571   void *InsertPos = nullptr;
3572   DependentTemplateSpecializationType *T
3573     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3574   if (T)
3575     return QualType(T, 0);
3576 
3577   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3578 
3579   ElaboratedTypeKeyword CanonKeyword = Keyword;
3580   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3581 
3582   bool AnyNonCanonArgs = false;
3583   SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3584   for (unsigned I = 0; I != NumArgs; ++I) {
3585     CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3586     if (!CanonArgs[I].structurallyEquals(Args[I]))
3587       AnyNonCanonArgs = true;
3588   }
3589 
3590   QualType Canon;
3591   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3592     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3593                                                    Name, NumArgs,
3594                                                    CanonArgs.data());
3595 
3596     // Find the insert position again.
3597     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3598   }
3599 
3600   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3601                         sizeof(TemplateArgument) * NumArgs),
3602                        TypeAlignment);
3603   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3604                                                     Name, NumArgs, Args, Canon);
3605   Types.push_back(T);
3606   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3607   return QualType(T, 0);
3608 }
3609 
getPackExpansionType(QualType Pattern,Optional<unsigned> NumExpansions)3610 QualType ASTContext::getPackExpansionType(QualType Pattern,
3611                                           Optional<unsigned> NumExpansions) {
3612   llvm::FoldingSetNodeID ID;
3613   PackExpansionType::Profile(ID, Pattern, NumExpansions);
3614 
3615   assert(Pattern->containsUnexpandedParameterPack() &&
3616          "Pack expansions must expand one or more parameter packs");
3617   void *InsertPos = nullptr;
3618   PackExpansionType *T
3619     = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3620   if (T)
3621     return QualType(T, 0);
3622 
3623   QualType Canon;
3624   if (!Pattern.isCanonical()) {
3625     Canon = getCanonicalType(Pattern);
3626     // The canonical type might not contain an unexpanded parameter pack, if it
3627     // contains an alias template specialization which ignores one of its
3628     // parameters.
3629     if (Canon->containsUnexpandedParameterPack()) {
3630       Canon = getPackExpansionType(Canon, NumExpansions);
3631 
3632       // Find the insert position again, in case we inserted an element into
3633       // PackExpansionTypes and invalidated our insert position.
3634       PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3635     }
3636   }
3637 
3638   T = new (*this, TypeAlignment)
3639       PackExpansionType(Pattern, Canon, NumExpansions);
3640   Types.push_back(T);
3641   PackExpansionTypes.InsertNode(T, InsertPos);
3642   return QualType(T, 0);
3643 }
3644 
3645 /// CmpProtocolNames - Comparison predicate for sorting protocols
3646 /// alphabetically.
CmpProtocolNames(ObjCProtocolDecl * const * LHS,ObjCProtocolDecl * const * RHS)3647 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3648                             ObjCProtocolDecl *const *RHS) {
3649   return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
3650 }
3651 
areSortedAndUniqued(ObjCProtocolDecl * const * Protocols,unsigned NumProtocols)3652 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
3653                                 unsigned NumProtocols) {
3654   if (NumProtocols == 0) return true;
3655 
3656   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3657     return false;
3658 
3659   for (unsigned i = 1; i != NumProtocols; ++i)
3660     if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
3661         Protocols[i]->getCanonicalDecl() != Protocols[i])
3662       return false;
3663   return true;
3664 }
3665 
3666 static void
SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl * > & Protocols)3667 SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
3668   // Sort protocols, keyed by name.
3669   llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
3670 
3671   // Canonicalize.
3672   for (ObjCProtocolDecl *&P : Protocols)
3673     P = P->getCanonicalDecl();
3674 
3675   // Remove duplicates.
3676   auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3677   Protocols.erase(ProtocolsEnd, Protocols.end());
3678 }
3679 
getObjCObjectType(QualType BaseType,ObjCProtocolDecl * const * Protocols,unsigned NumProtocols) const3680 QualType ASTContext::getObjCObjectType(QualType BaseType,
3681                                        ObjCProtocolDecl * const *Protocols,
3682                                        unsigned NumProtocols) const {
3683   return getObjCObjectType(BaseType, { },
3684                            llvm::makeArrayRef(Protocols, NumProtocols),
3685                            /*isKindOf=*/false);
3686 }
3687 
getObjCObjectType(QualType baseType,ArrayRef<QualType> typeArgs,ArrayRef<ObjCProtocolDecl * > protocols,bool isKindOf) const3688 QualType ASTContext::getObjCObjectType(
3689            QualType baseType,
3690            ArrayRef<QualType> typeArgs,
3691            ArrayRef<ObjCProtocolDecl *> protocols,
3692            bool isKindOf) const {
3693   // If the base type is an interface and there aren't any protocols or
3694   // type arguments to add, then the interface type will do just fine.
3695   if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3696       isa<ObjCInterfaceType>(baseType))
3697     return baseType;
3698 
3699   // Look in the folding set for an existing type.
3700   llvm::FoldingSetNodeID ID;
3701   ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
3702   void *InsertPos = nullptr;
3703   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3704     return QualType(QT, 0);
3705 
3706   // Determine the type arguments to be used for canonicalization,
3707   // which may be explicitly specified here or written on the base
3708   // type.
3709   ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3710   if (effectiveTypeArgs.empty()) {
3711     if (auto baseObject = baseType->getAs<ObjCObjectType>())
3712       effectiveTypeArgs = baseObject->getTypeArgs();
3713   }
3714 
3715   // Build the canonical type, which has the canonical base type and a
3716   // sorted-and-uniqued list of protocols and the type arguments
3717   // canonicalized.
3718   QualType canonical;
3719   bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3720                                           effectiveTypeArgs.end(),
3721                                           [&](QualType type) {
3722                                             return type.isCanonical();
3723                                           });
3724   bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3725                                              protocols.size());
3726   if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3727     // Determine the canonical type arguments.
3728     ArrayRef<QualType> canonTypeArgs;
3729     SmallVector<QualType, 4> canonTypeArgsVec;
3730     if (!typeArgsAreCanonical) {
3731       canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3732       for (auto typeArg : effectiveTypeArgs)
3733         canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3734       canonTypeArgs = canonTypeArgsVec;
3735     } else {
3736       canonTypeArgs = effectiveTypeArgs;
3737     }
3738 
3739     ArrayRef<ObjCProtocolDecl *> canonProtocols;
3740     SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3741     if (!protocolsSorted) {
3742       canonProtocolsVec.append(protocols.begin(), protocols.end());
3743       SortAndUniqueProtocols(canonProtocolsVec);
3744       canonProtocols = canonProtocolsVec;
3745     } else {
3746       canonProtocols = protocols;
3747     }
3748 
3749     canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
3750                                   canonProtocols, isKindOf);
3751 
3752     // Regenerate InsertPos.
3753     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3754   }
3755 
3756   unsigned size = sizeof(ObjCObjectTypeImpl);
3757   size += typeArgs.size() * sizeof(QualType);
3758   size += protocols.size() * sizeof(ObjCProtocolDecl *);
3759   void *mem = Allocate(size, TypeAlignment);
3760   ObjCObjectTypeImpl *T =
3761     new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3762                                  isKindOf);
3763 
3764   Types.push_back(T);
3765   ObjCObjectTypes.InsertNode(T, InsertPos);
3766   return QualType(T, 0);
3767 }
3768 
3769 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3770 /// protocol list adopt all protocols in QT's qualified-id protocol
3771 /// list.
ObjCObjectAdoptsQTypeProtocols(QualType QT,ObjCInterfaceDecl * IC)3772 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3773                                                 ObjCInterfaceDecl *IC) {
3774   if (!QT->isObjCQualifiedIdType())
3775     return false;
3776 
3777   if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3778     // If both the right and left sides have qualifiers.
3779     for (auto *Proto : OPT->quals()) {
3780       if (!IC->ClassImplementsProtocol(Proto, false))
3781         return false;
3782     }
3783     return true;
3784   }
3785   return false;
3786 }
3787 
3788 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3789 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
3790 /// of protocols.
QIdProtocolsAdoptObjCObjectProtocols(QualType QT,ObjCInterfaceDecl * IDecl)3791 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3792                                                 ObjCInterfaceDecl *IDecl) {
3793   if (!QT->isObjCQualifiedIdType())
3794     return false;
3795   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3796   if (!OPT)
3797     return false;
3798   if (!IDecl->hasDefinition())
3799     return false;
3800   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3801   CollectInheritedProtocols(IDecl, InheritedProtocols);
3802   if (InheritedProtocols.empty())
3803     return false;
3804   // Check that if every protocol in list of id<plist> conforms to a protcol
3805   // of IDecl's, then bridge casting is ok.
3806   bool Conforms = false;
3807   for (auto *Proto : OPT->quals()) {
3808     Conforms = false;
3809     for (auto *PI : InheritedProtocols) {
3810       if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3811         Conforms = true;
3812         break;
3813       }
3814     }
3815     if (!Conforms)
3816       break;
3817   }
3818   if (Conforms)
3819     return true;
3820 
3821   for (auto *PI : InheritedProtocols) {
3822     // If both the right and left sides have qualifiers.
3823     bool Adopts = false;
3824     for (auto *Proto : OPT->quals()) {
3825       // return 'true' if 'PI' is in the inheritance hierarchy of Proto
3826       if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
3827         break;
3828     }
3829     if (!Adopts)
3830       return false;
3831   }
3832   return true;
3833 }
3834 
3835 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3836 /// the given object type.
getObjCObjectPointerType(QualType ObjectT) const3837 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
3838   llvm::FoldingSetNodeID ID;
3839   ObjCObjectPointerType::Profile(ID, ObjectT);
3840 
3841   void *InsertPos = nullptr;
3842   if (ObjCObjectPointerType *QT =
3843               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3844     return QualType(QT, 0);
3845 
3846   // Find the canonical object type.
3847   QualType Canonical;
3848   if (!ObjectT.isCanonical()) {
3849     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3850 
3851     // Regenerate InsertPos.
3852     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3853   }
3854 
3855   // No match.
3856   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3857   ObjCObjectPointerType *QType =
3858     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
3859 
3860   Types.push_back(QType);
3861   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
3862   return QualType(QType, 0);
3863 }
3864 
3865 /// getObjCInterfaceType - Return the unique reference to the type for the
3866 /// specified ObjC interface decl. The list of protocols is optional.
getObjCInterfaceType(const ObjCInterfaceDecl * Decl,ObjCInterfaceDecl * PrevDecl) const3867 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3868                                           ObjCInterfaceDecl *PrevDecl) const {
3869   if (Decl->TypeForDecl)
3870     return QualType(Decl->TypeForDecl, 0);
3871 
3872   if (PrevDecl) {
3873     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3874     Decl->TypeForDecl = PrevDecl->TypeForDecl;
3875     return QualType(PrevDecl->TypeForDecl, 0);
3876   }
3877 
3878   // Prefer the definition, if there is one.
3879   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3880     Decl = Def;
3881 
3882   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3883   ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3884   Decl->TypeForDecl = T;
3885   Types.push_back(T);
3886   return QualType(T, 0);
3887 }
3888 
3889 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3890 /// TypeOfExprType AST's (since expression's are never shared). For example,
3891 /// multiple declarations that refer to "typeof(x)" all contain different
3892 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
3893 /// on canonical type's (which are always unique).
getTypeOfExprType(Expr * tofExpr) const3894 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
3895   TypeOfExprType *toe;
3896   if (tofExpr->isTypeDependent()) {
3897     llvm::FoldingSetNodeID ID;
3898     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3899 
3900     void *InsertPos = nullptr;
3901     DependentTypeOfExprType *Canon
3902       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3903     if (Canon) {
3904       // We already have a "canonical" version of an identical, dependent
3905       // typeof(expr) type. Use that as our canonical type.
3906       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3907                                           QualType((TypeOfExprType*)Canon, 0));
3908     } else {
3909       // Build a new, canonical typeof(expr) type.
3910       Canon
3911         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3912       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3913       toe = Canon;
3914     }
3915   } else {
3916     QualType Canonical = getCanonicalType(tofExpr->getType());
3917     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3918   }
3919   Types.push_back(toe);
3920   return QualType(toe, 0);
3921 }
3922 
3923 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
3924 /// TypeOfType nodes. The only motivation to unique these nodes would be
3925 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3926 /// an issue. This doesn't affect the type checker, since it operates
3927 /// on canonical types (which are always unique).
getTypeOfType(QualType tofType) const3928 QualType ASTContext::getTypeOfType(QualType tofType) const {
3929   QualType Canonical = getCanonicalType(tofType);
3930   TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3931   Types.push_back(tot);
3932   return QualType(tot, 0);
3933 }
3934 
3935 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3936 /// nodes. This would never be helpful, since each such type has its own
3937 /// expression, and would not give a significant memory saving, since there
3938 /// is an Expr tree under each such type.
getDecltypeType(Expr * e,QualType UnderlyingType) const3939 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3940   DecltypeType *dt;
3941 
3942   // C++11 [temp.type]p2:
3943   //   If an expression e involves a template parameter, decltype(e) denotes a
3944   //   unique dependent type. Two such decltype-specifiers refer to the same
3945   //   type only if their expressions are equivalent (14.5.6.1).
3946   if (e->isInstantiationDependent()) {
3947     llvm::FoldingSetNodeID ID;
3948     DependentDecltypeType::Profile(ID, *this, e);
3949 
3950     void *InsertPos = nullptr;
3951     DependentDecltypeType *Canon
3952       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3953     if (!Canon) {
3954       // Build a new, canonical typeof(expr) type.
3955       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3956       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3957     }
3958     dt = new (*this, TypeAlignment)
3959         DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
3960   } else {
3961     dt = new (*this, TypeAlignment)
3962         DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
3963   }
3964   Types.push_back(dt);
3965   return QualType(dt, 0);
3966 }
3967 
3968 /// getUnaryTransformationType - We don't unique these, since the memory
3969 /// savings are minimal and these are rare.
getUnaryTransformType(QualType BaseType,QualType UnderlyingType,UnaryTransformType::UTTKind Kind) const3970 QualType ASTContext::getUnaryTransformType(QualType BaseType,
3971                                            QualType UnderlyingType,
3972                                            UnaryTransformType::UTTKind Kind)
3973     const {
3974   UnaryTransformType *Ty =
3975     new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3976                                                    Kind,
3977                                  UnderlyingType->isDependentType() ?
3978                                  QualType() : getCanonicalType(UnderlyingType));
3979   Types.push_back(Ty);
3980   return QualType(Ty, 0);
3981 }
3982 
3983 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
3984 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3985 /// canonical deduced-but-dependent 'auto' type.
getAutoType(QualType DeducedType,AutoTypeKeyword Keyword,bool IsDependent) const3986 QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
3987                                  bool IsDependent) const {
3988   if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
3989     return getAutoDeductType();
3990 
3991   // Look in the folding set for an existing type.
3992   void *InsertPos = nullptr;
3993   llvm::FoldingSetNodeID ID;
3994   AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
3995   if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3996     return QualType(AT, 0);
3997 
3998   AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
3999                                                      Keyword,
4000                                                      IsDependent);
4001   Types.push_back(AT);
4002   if (InsertPos)
4003     AutoTypes.InsertNode(AT, InsertPos);
4004   return QualType(AT, 0);
4005 }
4006 
4007 /// getAtomicType - Return the uniqued reference to the atomic type for
4008 /// the given value type.
getAtomicType(QualType T) const4009 QualType ASTContext::getAtomicType(QualType T) const {
4010   // Unique pointers, to guarantee there is only one pointer of a particular
4011   // structure.
4012   llvm::FoldingSetNodeID ID;
4013   AtomicType::Profile(ID, T);
4014 
4015   void *InsertPos = nullptr;
4016   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4017     return QualType(AT, 0);
4018 
4019   // If the atomic value type isn't canonical, this won't be a canonical type
4020   // either, so fill in the canonical type field.
4021   QualType Canonical;
4022   if (!T.isCanonical()) {
4023     Canonical = getAtomicType(getCanonicalType(T));
4024 
4025     // Get the new insert position for the node we care about.
4026     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
4027     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
4028   }
4029   AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4030   Types.push_back(New);
4031   AtomicTypes.InsertNode(New, InsertPos);
4032   return QualType(New, 0);
4033 }
4034 
4035 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
getAutoDeductType() const4036 QualType ASTContext::getAutoDeductType() const {
4037   if (AutoDeductTy.isNull())
4038     AutoDeductTy = QualType(
4039       new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
4040                                           /*dependent*/false),
4041       0);
4042   return AutoDeductTy;
4043 }
4044 
4045 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
getAutoRRefDeductType() const4046 QualType ASTContext::getAutoRRefDeductType() const {
4047   if (AutoRRefDeductTy.isNull())
4048     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4049   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4050   return AutoRRefDeductTy;
4051 }
4052 
4053 /// getTagDeclType - Return the unique reference to the type for the
4054 /// specified TagDecl (struct/union/class/enum) decl.
getTagDeclType(const TagDecl * Decl) const4055 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
4056   assert (Decl);
4057   // FIXME: What is the design on getTagDeclType when it requires casting
4058   // away const?  mutable?
4059   return getTypeDeclType(const_cast<TagDecl*>(Decl));
4060 }
4061 
4062 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4063 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4064 /// needs to agree with the definition in <stddef.h>.
getSizeType() const4065 CanQualType ASTContext::getSizeType() const {
4066   return getFromTargetType(Target->getSizeType());
4067 }
4068 
4069 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
getIntMaxType() const4070 CanQualType ASTContext::getIntMaxType() const {
4071   return getFromTargetType(Target->getIntMaxType());
4072 }
4073 
4074 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
getUIntMaxType() const4075 CanQualType ASTContext::getUIntMaxType() const {
4076   return getFromTargetType(Target->getUIntMaxType());
4077 }
4078 
4079 /// getSignedWCharType - Return the type of "signed wchar_t".
4080 /// Used when in C++, as a GCC extension.
getSignedWCharType() const4081 QualType ASTContext::getSignedWCharType() const {
4082   // FIXME: derive from "Target" ?
4083   return WCharTy;
4084 }
4085 
4086 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4087 /// Used when in C++, as a GCC extension.
getUnsignedWCharType() const4088 QualType ASTContext::getUnsignedWCharType() const {
4089   // FIXME: derive from "Target" ?
4090   return UnsignedIntTy;
4091 }
4092 
getIntPtrType() const4093 QualType ASTContext::getIntPtrType() const {
4094   return getFromTargetType(Target->getIntPtrType());
4095 }
4096 
getUIntPtrType() const4097 QualType ASTContext::getUIntPtrType() const {
4098   return getCorrespondingUnsignedType(getIntPtrType());
4099 }
4100 
4101 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
4102 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
getPointerDiffType() const4103 QualType ASTContext::getPointerDiffType() const {
4104   return getFromTargetType(Target->getPtrDiffType(0));
4105 }
4106 
4107 /// \brief Return the unique type for "pid_t" defined in
4108 /// <sys/types.h>. We need this to compute the correct type for vfork().
getProcessIDType() const4109 QualType ASTContext::getProcessIDType() const {
4110   return getFromTargetType(Target->getProcessIDType());
4111 }
4112 
4113 //===----------------------------------------------------------------------===//
4114 //                              Type Operators
4115 //===----------------------------------------------------------------------===//
4116 
getCanonicalParamType(QualType T) const4117 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
4118   // Push qualifiers into arrays, and then discard any remaining
4119   // qualifiers.
4120   T = getCanonicalType(T);
4121   T = getVariableArrayDecayedType(T);
4122   const Type *Ty = T.getTypePtr();
4123   QualType Result;
4124   if (isa<ArrayType>(Ty)) {
4125     Result = getArrayDecayedType(QualType(Ty,0));
4126   } else if (isa<FunctionType>(Ty)) {
4127     Result = getPointerType(QualType(Ty, 0));
4128   } else {
4129     Result = QualType(Ty, 0);
4130   }
4131 
4132   return CanQualType::CreateUnsafe(Result);
4133 }
4134 
getUnqualifiedArrayType(QualType type,Qualifiers & quals)4135 QualType ASTContext::getUnqualifiedArrayType(QualType type,
4136                                              Qualifiers &quals) {
4137   SplitQualType splitType = type.getSplitUnqualifiedType();
4138 
4139   // FIXME: getSplitUnqualifiedType() actually walks all the way to
4140   // the unqualified desugared type and then drops it on the floor.
4141   // We then have to strip that sugar back off with
4142   // getUnqualifiedDesugaredType(), which is silly.
4143   const ArrayType *AT =
4144     dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
4145 
4146   // If we don't have an array, just use the results in splitType.
4147   if (!AT) {
4148     quals = splitType.Quals;
4149     return QualType(splitType.Ty, 0);
4150   }
4151 
4152   // Otherwise, recurse on the array's element type.
4153   QualType elementType = AT->getElementType();
4154   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4155 
4156   // If that didn't change the element type, AT has no qualifiers, so we
4157   // can just use the results in splitType.
4158   if (elementType == unqualElementType) {
4159     assert(quals.empty()); // from the recursive call
4160     quals = splitType.Quals;
4161     return QualType(splitType.Ty, 0);
4162   }
4163 
4164   // Otherwise, add in the qualifiers from the outermost type, then
4165   // build the type back up.
4166   quals.addConsistentQualifiers(splitType.Quals);
4167 
4168   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4169     return getConstantArrayType(unqualElementType, CAT->getSize(),
4170                                 CAT->getSizeModifier(), 0);
4171   }
4172 
4173   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
4174     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
4175   }
4176 
4177   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
4178     return getVariableArrayType(unqualElementType,
4179                                 VAT->getSizeExpr(),
4180                                 VAT->getSizeModifier(),
4181                                 VAT->getIndexTypeCVRQualifiers(),
4182                                 VAT->getBracketsRange());
4183   }
4184 
4185   const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
4186   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
4187                                     DSAT->getSizeModifier(), 0,
4188                                     SourceRange());
4189 }
4190 
4191 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
4192 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4193 /// they point to and return true. If T1 and T2 aren't pointer types
4194 /// or pointer-to-member types, or if they are not similar at this
4195 /// level, returns false and leaves T1 and T2 unchanged. Top-level
4196 /// qualifiers on T1 and T2 are ignored. This function will typically
4197 /// be called in a loop that successively "unwraps" pointer and
4198 /// pointer-to-member types to compare them at each level.
UnwrapSimilarPointerTypes(QualType & T1,QualType & T2)4199 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4200   const PointerType *T1PtrType = T1->getAs<PointerType>(),
4201                     *T2PtrType = T2->getAs<PointerType>();
4202   if (T1PtrType && T2PtrType) {
4203     T1 = T1PtrType->getPointeeType();
4204     T2 = T2PtrType->getPointeeType();
4205     return true;
4206   }
4207 
4208   const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4209                           *T2MPType = T2->getAs<MemberPointerType>();
4210   if (T1MPType && T2MPType &&
4211       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4212                              QualType(T2MPType->getClass(), 0))) {
4213     T1 = T1MPType->getPointeeType();
4214     T2 = T2MPType->getPointeeType();
4215     return true;
4216   }
4217 
4218   if (getLangOpts().ObjC1) {
4219     const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4220                                 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4221     if (T1OPType && T2OPType) {
4222       T1 = T1OPType->getPointeeType();
4223       T2 = T2OPType->getPointeeType();
4224       return true;
4225     }
4226   }
4227 
4228   // FIXME: Block pointers, too?
4229 
4230   return false;
4231 }
4232 
4233 DeclarationNameInfo
getNameForTemplate(TemplateName Name,SourceLocation NameLoc) const4234 ASTContext::getNameForTemplate(TemplateName Name,
4235                                SourceLocation NameLoc) const {
4236   switch (Name.getKind()) {
4237   case TemplateName::QualifiedTemplate:
4238   case TemplateName::Template:
4239     // DNInfo work in progress: CHECKME: what about DNLoc?
4240     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4241                                NameLoc);
4242 
4243   case TemplateName::OverloadedTemplate: {
4244     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4245     // DNInfo work in progress: CHECKME: what about DNLoc?
4246     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4247   }
4248 
4249   case TemplateName::DependentTemplate: {
4250     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4251     DeclarationName DName;
4252     if (DTN->isIdentifier()) {
4253       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4254       return DeclarationNameInfo(DName, NameLoc);
4255     } else {
4256       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4257       // DNInfo work in progress: FIXME: source locations?
4258       DeclarationNameLoc DNLoc;
4259       DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4260       DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4261       return DeclarationNameInfo(DName, NameLoc, DNLoc);
4262     }
4263   }
4264 
4265   case TemplateName::SubstTemplateTemplateParm: {
4266     SubstTemplateTemplateParmStorage *subst
4267       = Name.getAsSubstTemplateTemplateParm();
4268     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4269                                NameLoc);
4270   }
4271 
4272   case TemplateName::SubstTemplateTemplateParmPack: {
4273     SubstTemplateTemplateParmPackStorage *subst
4274       = Name.getAsSubstTemplateTemplateParmPack();
4275     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4276                                NameLoc);
4277   }
4278   }
4279 
4280   llvm_unreachable("bad template name kind!");
4281 }
4282 
getCanonicalTemplateName(TemplateName Name) const4283 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4284   switch (Name.getKind()) {
4285   case TemplateName::QualifiedTemplate:
4286   case TemplateName::Template: {
4287     TemplateDecl *Template = Name.getAsTemplateDecl();
4288     if (TemplateTemplateParmDecl *TTP
4289           = dyn_cast<TemplateTemplateParmDecl>(Template))
4290       Template = getCanonicalTemplateTemplateParmDecl(TTP);
4291 
4292     // The canonical template name is the canonical template declaration.
4293     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4294   }
4295 
4296   case TemplateName::OverloadedTemplate:
4297     llvm_unreachable("cannot canonicalize overloaded template");
4298 
4299   case TemplateName::DependentTemplate: {
4300     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4301     assert(DTN && "Non-dependent template names must refer to template decls.");
4302     return DTN->CanonicalTemplateName;
4303   }
4304 
4305   case TemplateName::SubstTemplateTemplateParm: {
4306     SubstTemplateTemplateParmStorage *subst
4307       = Name.getAsSubstTemplateTemplateParm();
4308     return getCanonicalTemplateName(subst->getReplacement());
4309   }
4310 
4311   case TemplateName::SubstTemplateTemplateParmPack: {
4312     SubstTemplateTemplateParmPackStorage *subst
4313                                   = Name.getAsSubstTemplateTemplateParmPack();
4314     TemplateTemplateParmDecl *canonParameter
4315       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4316     TemplateArgument canonArgPack
4317       = getCanonicalTemplateArgument(subst->getArgumentPack());
4318     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4319   }
4320   }
4321 
4322   llvm_unreachable("bad template name!");
4323 }
4324 
hasSameTemplateName(TemplateName X,TemplateName Y)4325 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4326   X = getCanonicalTemplateName(X);
4327   Y = getCanonicalTemplateName(Y);
4328   return X.getAsVoidPointer() == Y.getAsVoidPointer();
4329 }
4330 
4331 TemplateArgument
getCanonicalTemplateArgument(const TemplateArgument & Arg) const4332 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4333   switch (Arg.getKind()) {
4334     case TemplateArgument::Null:
4335       return Arg;
4336 
4337     case TemplateArgument::Expression:
4338       return Arg;
4339 
4340     case TemplateArgument::Declaration: {
4341       ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4342       return TemplateArgument(D, Arg.getParamTypeForDecl());
4343     }
4344 
4345     case TemplateArgument::NullPtr:
4346       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4347                               /*isNullPtr*/true);
4348 
4349     case TemplateArgument::Template:
4350       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4351 
4352     case TemplateArgument::TemplateExpansion:
4353       return TemplateArgument(getCanonicalTemplateName(
4354                                          Arg.getAsTemplateOrTemplatePattern()),
4355                               Arg.getNumTemplateExpansions());
4356 
4357     case TemplateArgument::Integral:
4358       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4359 
4360     case TemplateArgument::Type:
4361       return TemplateArgument(getCanonicalType(Arg.getAsType()));
4362 
4363     case TemplateArgument::Pack: {
4364       if (Arg.pack_size() == 0)
4365         return Arg;
4366 
4367       TemplateArgument *CanonArgs
4368         = new (*this) TemplateArgument[Arg.pack_size()];
4369       unsigned Idx = 0;
4370       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4371                                         AEnd = Arg.pack_end();
4372            A != AEnd; (void)++A, ++Idx)
4373         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4374 
4375       return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
4376     }
4377   }
4378 
4379   // Silence GCC warning
4380   llvm_unreachable("Unhandled template argument kind");
4381 }
4382 
4383 NestedNameSpecifier *
getCanonicalNestedNameSpecifier(NestedNameSpecifier * NNS) const4384 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4385   if (!NNS)
4386     return nullptr;
4387 
4388   switch (NNS->getKind()) {
4389   case NestedNameSpecifier::Identifier:
4390     // Canonicalize the prefix but keep the identifier the same.
4391     return NestedNameSpecifier::Create(*this,
4392                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4393                                        NNS->getAsIdentifier());
4394 
4395   case NestedNameSpecifier::Namespace:
4396     // A namespace is canonical; build a nested-name-specifier with
4397     // this namespace and no prefix.
4398     return NestedNameSpecifier::Create(*this, nullptr,
4399                                  NNS->getAsNamespace()->getOriginalNamespace());
4400 
4401   case NestedNameSpecifier::NamespaceAlias:
4402     // A namespace is canonical; build a nested-name-specifier with
4403     // this namespace and no prefix.
4404     return NestedNameSpecifier::Create(*this, nullptr,
4405                                     NNS->getAsNamespaceAlias()->getNamespace()
4406                                                       ->getOriginalNamespace());
4407 
4408   case NestedNameSpecifier::TypeSpec:
4409   case NestedNameSpecifier::TypeSpecWithTemplate: {
4410     QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4411 
4412     // If we have some kind of dependent-named type (e.g., "typename T::type"),
4413     // break it apart into its prefix and identifier, then reconsititute those
4414     // as the canonical nested-name-specifier. This is required to canonicalize
4415     // a dependent nested-name-specifier involving typedefs of dependent-name
4416     // types, e.g.,
4417     //   typedef typename T::type T1;
4418     //   typedef typename T1::type T2;
4419     if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4420       return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4421                            const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4422 
4423     // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4424     // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4425     // first place?
4426     return NestedNameSpecifier::Create(*this, nullptr, false,
4427                                        const_cast<Type *>(T.getTypePtr()));
4428   }
4429 
4430   case NestedNameSpecifier::Global:
4431   case NestedNameSpecifier::Super:
4432     // The global specifier and __super specifer are canonical and unique.
4433     return NNS;
4434   }
4435 
4436   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4437 }
4438 
getAsArrayType(QualType T) const4439 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4440   // Handle the non-qualified case efficiently.
4441   if (!T.hasLocalQualifiers()) {
4442     // Handle the common positive case fast.
4443     if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4444       return AT;
4445   }
4446 
4447   // Handle the common negative case fast.
4448   if (!isa<ArrayType>(T.getCanonicalType()))
4449     return nullptr;
4450 
4451   // Apply any qualifiers from the array type to the element type.  This
4452   // implements C99 6.7.3p8: "If the specification of an array type includes
4453   // any type qualifiers, the element type is so qualified, not the array type."
4454 
4455   // If we get here, we either have type qualifiers on the type, or we have
4456   // sugar such as a typedef in the way.  If we have type qualifiers on the type
4457   // we must propagate them down into the element type.
4458 
4459   SplitQualType split = T.getSplitDesugaredType();
4460   Qualifiers qs = split.Quals;
4461 
4462   // If we have a simple case, just return now.
4463   const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4464   if (!ATy || qs.empty())
4465     return ATy;
4466 
4467   // Otherwise, we have an array and we have qualifiers on it.  Push the
4468   // qualifiers into the array element type and return a new array type.
4469   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4470 
4471   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4472     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4473                                                 CAT->getSizeModifier(),
4474                                            CAT->getIndexTypeCVRQualifiers()));
4475   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4476     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4477                                                   IAT->getSizeModifier(),
4478                                            IAT->getIndexTypeCVRQualifiers()));
4479 
4480   if (const DependentSizedArrayType *DSAT
4481         = dyn_cast<DependentSizedArrayType>(ATy))
4482     return cast<ArrayType>(
4483                      getDependentSizedArrayType(NewEltTy,
4484                                                 DSAT->getSizeExpr(),
4485                                                 DSAT->getSizeModifier(),
4486                                               DSAT->getIndexTypeCVRQualifiers(),
4487                                                 DSAT->getBracketsRange()));
4488 
4489   const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4490   return cast<ArrayType>(getVariableArrayType(NewEltTy,
4491                                               VAT->getSizeExpr(),
4492                                               VAT->getSizeModifier(),
4493                                               VAT->getIndexTypeCVRQualifiers(),
4494                                               VAT->getBracketsRange()));
4495 }
4496 
getAdjustedParameterType(QualType T) const4497 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4498   if (T->isArrayType() || T->isFunctionType())
4499     return getDecayedType(T);
4500   return T;
4501 }
4502 
getSignatureParameterType(QualType T) const4503 QualType ASTContext::getSignatureParameterType(QualType T) const {
4504   T = getVariableArrayDecayedType(T);
4505   T = getAdjustedParameterType(T);
4506   return T.getUnqualifiedType();
4507 }
4508 
getExceptionObjectType(QualType T) const4509 QualType ASTContext::getExceptionObjectType(QualType T) const {
4510   // C++ [except.throw]p3:
4511   //   A throw-expression initializes a temporary object, called the exception
4512   //   object, the type of which is determined by removing any top-level
4513   //   cv-qualifiers from the static type of the operand of throw and adjusting
4514   //   the type from "array of T" or "function returning T" to "pointer to T"
4515   //   or "pointer to function returning T", [...]
4516   T = getVariableArrayDecayedType(T);
4517   if (T->isArrayType() || T->isFunctionType())
4518     T = getDecayedType(T);
4519   return T.getUnqualifiedType();
4520 }
4521 
4522 /// getArrayDecayedType - Return the properly qualified result of decaying the
4523 /// specified array type to a pointer.  This operation is non-trivial when
4524 /// handling typedefs etc.  The canonical type of "T" must be an array type,
4525 /// this returns a pointer to a properly qualified element of the array.
4526 ///
4527 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
getArrayDecayedType(QualType Ty) const4528 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4529   // Get the element type with 'getAsArrayType' so that we don't lose any
4530   // typedefs in the element type of the array.  This also handles propagation
4531   // of type qualifiers from the array type into the element type if present
4532   // (C99 6.7.3p8).
4533   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4534   assert(PrettyArrayType && "Not an array type!");
4535 
4536   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4537 
4538   // int x[restrict 4] ->  int *restrict
4539   return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
4540 }
4541 
getBaseElementType(const ArrayType * array) const4542 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4543   return getBaseElementType(array->getElementType());
4544 }
4545 
getBaseElementType(QualType type) const4546 QualType ASTContext::getBaseElementType(QualType type) const {
4547   Qualifiers qs;
4548   while (true) {
4549     SplitQualType split = type.getSplitDesugaredType();
4550     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4551     if (!array) break;
4552 
4553     type = array->getElementType();
4554     qs.addConsistentQualifiers(split.Quals);
4555   }
4556 
4557   return getQualifiedType(type, qs);
4558 }
4559 
4560 /// getConstantArrayElementCount - Returns number of constant array elements.
4561 uint64_t
getConstantArrayElementCount(const ConstantArrayType * CA) const4562 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
4563   uint64_t ElementCount = 1;
4564   do {
4565     ElementCount *= CA->getSize().getZExtValue();
4566     CA = dyn_cast_or_null<ConstantArrayType>(
4567       CA->getElementType()->getAsArrayTypeUnsafe());
4568   } while (CA);
4569   return ElementCount;
4570 }
4571 
4572 /// getFloatingRank - Return a relative rank for floating point types.
4573 /// This routine will assert if passed a built-in type that isn't a float.
getFloatingRank(QualType T)4574 static FloatingRank getFloatingRank(QualType T) {
4575   if (const ComplexType *CT = T->getAs<ComplexType>())
4576     return getFloatingRank(CT->getElementType());
4577 
4578   assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4579   switch (T->getAs<BuiltinType>()->getKind()) {
4580   default: llvm_unreachable("getFloatingRank(): not a floating type");
4581   case BuiltinType::Half:       return HalfRank;
4582   case BuiltinType::Float:      return FloatRank;
4583   case BuiltinType::Double:     return DoubleRank;
4584   case BuiltinType::LongDouble: return LongDoubleRank;
4585   }
4586 }
4587 
4588 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4589 /// point or a complex type (based on typeDomain/typeSize).
4590 /// 'typeDomain' is a real floating point or complex type.
4591 /// 'typeSize' is a real floating point or complex type.
getFloatingTypeOfSizeWithinDomain(QualType Size,QualType Domain) const4592 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4593                                                        QualType Domain) const {
4594   FloatingRank EltRank = getFloatingRank(Size);
4595   if (Domain->isComplexType()) {
4596     switch (EltRank) {
4597     case HalfRank: llvm_unreachable("Complex half is not supported");
4598     case FloatRank:      return FloatComplexTy;
4599     case DoubleRank:     return DoubleComplexTy;
4600     case LongDoubleRank: return LongDoubleComplexTy;
4601     }
4602   }
4603 
4604   assert(Domain->isRealFloatingType() && "Unknown domain!");
4605   switch (EltRank) {
4606   case HalfRank:       return HalfTy;
4607   case FloatRank:      return FloatTy;
4608   case DoubleRank:     return DoubleTy;
4609   case LongDoubleRank: return LongDoubleTy;
4610   }
4611   llvm_unreachable("getFloatingRank(): illegal value for rank");
4612 }
4613 
4614 /// getFloatingTypeOrder - Compare the rank of the two specified floating
4615 /// point types, ignoring the domain of the type (i.e. 'double' ==
4616 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
4617 /// LHS < RHS, return -1.
getFloatingTypeOrder(QualType LHS,QualType RHS) const4618 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
4619   FloatingRank LHSR = getFloatingRank(LHS);
4620   FloatingRank RHSR = getFloatingRank(RHS);
4621 
4622   if (LHSR == RHSR)
4623     return 0;
4624   if (LHSR > RHSR)
4625     return 1;
4626   return -1;
4627 }
4628 
4629 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4630 /// routine will assert if passed a built-in type that isn't an integer or enum,
4631 /// or if it is not canonicalized.
getIntegerRank(const Type * T) const4632 unsigned ASTContext::getIntegerRank(const Type *T) const {
4633   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
4634 
4635   switch (cast<BuiltinType>(T)->getKind()) {
4636   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
4637   case BuiltinType::Bool:
4638     return 1 + (getIntWidth(BoolTy) << 3);
4639   case BuiltinType::Char_S:
4640   case BuiltinType::Char_U:
4641   case BuiltinType::SChar:
4642   case BuiltinType::UChar:
4643     return 2 + (getIntWidth(CharTy) << 3);
4644   case BuiltinType::Short:
4645   case BuiltinType::UShort:
4646     return 3 + (getIntWidth(ShortTy) << 3);
4647   case BuiltinType::Int:
4648   case BuiltinType::UInt:
4649     return 4 + (getIntWidth(IntTy) << 3);
4650   case BuiltinType::Long:
4651   case BuiltinType::ULong:
4652     return 5 + (getIntWidth(LongTy) << 3);
4653   case BuiltinType::LongLong:
4654   case BuiltinType::ULongLong:
4655     return 6 + (getIntWidth(LongLongTy) << 3);
4656   case BuiltinType::Int128:
4657   case BuiltinType::UInt128:
4658     return 7 + (getIntWidth(Int128Ty) << 3);
4659   }
4660 }
4661 
4662 /// \brief Whether this is a promotable bitfield reference according
4663 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4664 ///
4665 /// \returns the type this bit-field will promote to, or NULL if no
4666 /// promotion occurs.
isPromotableBitField(Expr * E) const4667 QualType ASTContext::isPromotableBitField(Expr *E) const {
4668   if (E->isTypeDependent() || E->isValueDependent())
4669     return QualType();
4670 
4671   // FIXME: We should not do this unless E->refersToBitField() is true. This
4672   // matters in C where getSourceBitField() will find bit-fields for various
4673   // cases where the source expression is not a bit-field designator.
4674 
4675   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
4676   if (!Field)
4677     return QualType();
4678 
4679   QualType FT = Field->getType();
4680 
4681   uint64_t BitWidth = Field->getBitWidthValue(*this);
4682   uint64_t IntSize = getTypeSize(IntTy);
4683   // C++ [conv.prom]p5:
4684   //   A prvalue for an integral bit-field can be converted to a prvalue of type
4685   //   int if int can represent all the values of the bit-field; otherwise, it
4686   //   can be converted to unsigned int if unsigned int can represent all the
4687   //   values of the bit-field. If the bit-field is larger yet, no integral
4688   //   promotion applies to it.
4689   // C11 6.3.1.1/2:
4690   //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4691   //   If an int can represent all values of the original type (as restricted by
4692   //   the width, for a bit-field), the value is converted to an int; otherwise,
4693   //   it is converted to an unsigned int.
4694   //
4695   // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4696   //        We perform that promotion here to match GCC and C++.
4697   if (BitWidth < IntSize)
4698     return IntTy;
4699 
4700   if (BitWidth == IntSize)
4701     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4702 
4703   // Types bigger than int are not subject to promotions, and therefore act
4704   // like the base type. GCC has some weird bugs in this area that we
4705   // deliberately do not follow (GCC follows a pre-standard resolution to
4706   // C's DR315 which treats bit-width as being part of the type, and this leaks
4707   // into their semantics in some cases).
4708   return QualType();
4709 }
4710 
4711 /// getPromotedIntegerType - Returns the type that Promotable will
4712 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4713 /// integer type.
getPromotedIntegerType(QualType Promotable) const4714 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
4715   assert(!Promotable.isNull());
4716   assert(Promotable->isPromotableIntegerType());
4717   if (const EnumType *ET = Promotable->getAs<EnumType>())
4718     return ET->getDecl()->getPromotionType();
4719 
4720   if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4721     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4722     // (3.9.1) can be converted to a prvalue of the first of the following
4723     // types that can represent all the values of its underlying type:
4724     // int, unsigned int, long int, unsigned long int, long long int, or
4725     // unsigned long long int [...]
4726     // FIXME: Is there some better way to compute this?
4727     if (BT->getKind() == BuiltinType::WChar_S ||
4728         BT->getKind() == BuiltinType::WChar_U ||
4729         BT->getKind() == BuiltinType::Char16 ||
4730         BT->getKind() == BuiltinType::Char32) {
4731       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4732       uint64_t FromSize = getTypeSize(BT);
4733       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4734                                   LongLongTy, UnsignedLongLongTy };
4735       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4736         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4737         if (FromSize < ToSize ||
4738             (FromSize == ToSize &&
4739              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4740           return PromoteTypes[Idx];
4741       }
4742       llvm_unreachable("char type should fit into long long");
4743     }
4744   }
4745 
4746   // At this point, we should have a signed or unsigned integer type.
4747   if (Promotable->isSignedIntegerType())
4748     return IntTy;
4749   uint64_t PromotableSize = getIntWidth(Promotable);
4750   uint64_t IntSize = getIntWidth(IntTy);
4751   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4752   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4753 }
4754 
4755 /// \brief Recurses in pointer/array types until it finds an objc retainable
4756 /// type and returns its ownership.
getInnerObjCOwnership(QualType T) const4757 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4758   while (!T.isNull()) {
4759     if (T.getObjCLifetime() != Qualifiers::OCL_None)
4760       return T.getObjCLifetime();
4761     if (T->isArrayType())
4762       T = getBaseElementType(T);
4763     else if (const PointerType *PT = T->getAs<PointerType>())
4764       T = PT->getPointeeType();
4765     else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4766       T = RT->getPointeeType();
4767     else
4768       break;
4769   }
4770 
4771   return Qualifiers::OCL_None;
4772 }
4773 
getIntegerTypeForEnum(const EnumType * ET)4774 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4775   // Incomplete enum types are not treated as integer types.
4776   // FIXME: In C++, enum types are never integer types.
4777   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4778     return ET->getDecl()->getIntegerType().getTypePtr();
4779   return nullptr;
4780 }
4781 
4782 /// getIntegerTypeOrder - Returns the highest ranked integer type:
4783 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
4784 /// LHS < RHS, return -1.
getIntegerTypeOrder(QualType LHS,QualType RHS) const4785 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
4786   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4787   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
4788 
4789   // Unwrap enums to their underlying type.
4790   if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4791     LHSC = getIntegerTypeForEnum(ET);
4792   if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4793     RHSC = getIntegerTypeForEnum(ET);
4794 
4795   if (LHSC == RHSC) return 0;
4796 
4797   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4798   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
4799 
4800   unsigned LHSRank = getIntegerRank(LHSC);
4801   unsigned RHSRank = getIntegerRank(RHSC);
4802 
4803   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
4804     if (LHSRank == RHSRank) return 0;
4805     return LHSRank > RHSRank ? 1 : -1;
4806   }
4807 
4808   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4809   if (LHSUnsigned) {
4810     // If the unsigned [LHS] type is larger, return it.
4811     if (LHSRank >= RHSRank)
4812       return 1;
4813 
4814     // If the signed type can represent all values of the unsigned type, it
4815     // wins.  Because we are dealing with 2's complement and types that are
4816     // powers of two larger than each other, this is always safe.
4817     return -1;
4818   }
4819 
4820   // If the unsigned [RHS] type is larger, return it.
4821   if (RHSRank >= LHSRank)
4822     return -1;
4823 
4824   // If the signed type can represent all values of the unsigned type, it
4825   // wins.  Because we are dealing with 2's complement and types that are
4826   // powers of two larger than each other, this is always safe.
4827   return 1;
4828 }
4829 
4830 // getCFConstantStringType - Return the type used for constant CFStrings.
getCFConstantStringType() const4831 QualType ASTContext::getCFConstantStringType() const {
4832   if (!CFConstantStringTypeDecl) {
4833     CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
4834     CFConstantStringTypeDecl->startDefinition();
4835 
4836     QualType FieldTypes[4];
4837 
4838     // const int *isa;
4839     FieldTypes[0] = getPointerType(IntTy.withConst());
4840     // int flags;
4841     FieldTypes[1] = IntTy;
4842     // const char *str;
4843     FieldTypes[2] = getPointerType(CharTy.withConst());
4844     // long length;
4845     FieldTypes[3] = LongTy;
4846 
4847     // Create fields
4848     for (unsigned i = 0; i < 4; ++i) {
4849       FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
4850                                            SourceLocation(),
4851                                            SourceLocation(), nullptr,
4852                                            FieldTypes[i], /*TInfo=*/nullptr,
4853                                            /*BitWidth=*/nullptr,
4854                                            /*Mutable=*/false,
4855                                            ICIS_NoInit);
4856       Field->setAccess(AS_public);
4857       CFConstantStringTypeDecl->addDecl(Field);
4858     }
4859 
4860     CFConstantStringTypeDecl->completeDefinition();
4861   }
4862 
4863   return getTagDeclType(CFConstantStringTypeDecl);
4864 }
4865 
getObjCSuperType() const4866 QualType ASTContext::getObjCSuperType() const {
4867   if (ObjCSuperType.isNull()) {
4868     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
4869     TUDecl->addDecl(ObjCSuperTypeDecl);
4870     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4871   }
4872   return ObjCSuperType;
4873 }
4874 
setCFConstantStringType(QualType T)4875 void ASTContext::setCFConstantStringType(QualType T) {
4876   const RecordType *Rec = T->getAs<RecordType>();
4877   assert(Rec && "Invalid CFConstantStringType");
4878   CFConstantStringTypeDecl = Rec->getDecl();
4879 }
4880 
getBlockDescriptorType() const4881 QualType ASTContext::getBlockDescriptorType() const {
4882   if (BlockDescriptorType)
4883     return getTagDeclType(BlockDescriptorType);
4884 
4885   RecordDecl *RD;
4886   // FIXME: Needs the FlagAppleBlock bit.
4887   RD = buildImplicitRecord("__block_descriptor");
4888   RD->startDefinition();
4889 
4890   QualType FieldTypes[] = {
4891     UnsignedLongTy,
4892     UnsignedLongTy,
4893   };
4894 
4895   static const char *const FieldNames[] = {
4896     "reserved",
4897     "Size"
4898   };
4899 
4900   for (size_t i = 0; i < 2; ++i) {
4901     FieldDecl *Field = FieldDecl::Create(
4902         *this, RD, SourceLocation(), SourceLocation(),
4903         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4904         /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
4905     Field->setAccess(AS_public);
4906     RD->addDecl(Field);
4907   }
4908 
4909   RD->completeDefinition();
4910 
4911   BlockDescriptorType = RD;
4912 
4913   return getTagDeclType(BlockDescriptorType);
4914 }
4915 
getBlockDescriptorExtendedType() const4916 QualType ASTContext::getBlockDescriptorExtendedType() const {
4917   if (BlockDescriptorExtendedType)
4918     return getTagDeclType(BlockDescriptorExtendedType);
4919 
4920   RecordDecl *RD;
4921   // FIXME: Needs the FlagAppleBlock bit.
4922   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4923   RD->startDefinition();
4924 
4925   QualType FieldTypes[] = {
4926     UnsignedLongTy,
4927     UnsignedLongTy,
4928     getPointerType(VoidPtrTy),
4929     getPointerType(VoidPtrTy)
4930   };
4931 
4932   static const char *const FieldNames[] = {
4933     "reserved",
4934     "Size",
4935     "CopyFuncPtr",
4936     "DestroyFuncPtr"
4937   };
4938 
4939   for (size_t i = 0; i < 4; ++i) {
4940     FieldDecl *Field = FieldDecl::Create(
4941         *this, RD, SourceLocation(), SourceLocation(),
4942         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4943         /*BitWidth=*/nullptr,
4944         /*Mutable=*/false, ICIS_NoInit);
4945     Field->setAccess(AS_public);
4946     RD->addDecl(Field);
4947   }
4948 
4949   RD->completeDefinition();
4950 
4951   BlockDescriptorExtendedType = RD;
4952   return getTagDeclType(BlockDescriptorExtendedType);
4953 }
4954 
4955 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4956 /// requires copy/dispose. Note that this must match the logic
4957 /// in buildByrefHelpers.
BlockRequiresCopying(QualType Ty,const VarDecl * D)4958 bool ASTContext::BlockRequiresCopying(QualType Ty,
4959                                       const VarDecl *D) {
4960   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4961     const Expr *copyExpr = getBlockVarCopyInits(D);
4962     if (!copyExpr && record->hasTrivialDestructor()) return false;
4963 
4964     return true;
4965   }
4966 
4967   if (!Ty->isObjCRetainableType()) return false;
4968 
4969   Qualifiers qs = Ty.getQualifiers();
4970 
4971   // If we have lifetime, that dominates.
4972   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4973     switch (lifetime) {
4974       case Qualifiers::OCL_None: llvm_unreachable("impossible");
4975 
4976       // These are just bits as far as the runtime is concerned.
4977       case Qualifiers::OCL_ExplicitNone:
4978       case Qualifiers::OCL_Autoreleasing:
4979         return false;
4980 
4981       // Tell the runtime that this is ARC __weak, called by the
4982       // byref routines.
4983       case Qualifiers::OCL_Weak:
4984       // ARC __strong __block variables need to be retained.
4985       case Qualifiers::OCL_Strong:
4986         return true;
4987     }
4988     llvm_unreachable("fell out of lifetime switch!");
4989   }
4990   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4991           Ty->isObjCObjectPointerType());
4992 }
4993 
getByrefLifetime(QualType Ty,Qualifiers::ObjCLifetime & LifeTime,bool & HasByrefExtendedLayout) const4994 bool ASTContext::getByrefLifetime(QualType Ty,
4995                               Qualifiers::ObjCLifetime &LifeTime,
4996                               bool &HasByrefExtendedLayout) const {
4997 
4998   if (!getLangOpts().ObjC1 ||
4999       getLangOpts().getGC() != LangOptions::NonGC)
5000     return false;
5001 
5002   HasByrefExtendedLayout = false;
5003   if (Ty->isRecordType()) {
5004     HasByrefExtendedLayout = true;
5005     LifeTime = Qualifiers::OCL_None;
5006   } else if ((LifeTime = Ty.getObjCLifetime())) {
5007     // Honor the ARC qualifiers.
5008   } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5009     // The MRR rule.
5010     LifeTime = Qualifiers::OCL_ExplicitNone;
5011   } else {
5012     LifeTime = Qualifiers::OCL_None;
5013   }
5014   return true;
5015 }
5016 
getObjCInstanceTypeDecl()5017 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5018   if (!ObjCInstanceTypeDecl)
5019     ObjCInstanceTypeDecl =
5020         buildImplicitTypedef(getObjCIdType(), "instancetype");
5021   return ObjCInstanceTypeDecl;
5022 }
5023 
5024 // This returns true if a type has been typedefed to BOOL:
5025 // typedef <type> BOOL;
isTypeTypedefedAsBOOL(QualType T)5026 static bool isTypeTypedefedAsBOOL(QualType T) {
5027   if (const TypedefType *TT = dyn_cast<TypedefType>(T))
5028     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5029       return II->isStr("BOOL");
5030 
5031   return false;
5032 }
5033 
5034 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
5035 /// purpose.
getObjCEncodingTypeSize(QualType type) const5036 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
5037   if (!type->isIncompleteArrayType() && type->isIncompleteType())
5038     return CharUnits::Zero();
5039 
5040   CharUnits sz = getTypeSizeInChars(type);
5041 
5042   // Make all integer and enum types at least as large as an int
5043   if (sz.isPositive() && type->isIntegralOrEnumerationType())
5044     sz = std::max(sz, getTypeSizeInChars(IntTy));
5045   // Treat arrays as pointers, since that's how they're passed in.
5046   else if (type->isArrayType())
5047     sz = getTypeSizeInChars(VoidPtrTy);
5048   return sz;
5049 }
5050 
isMSStaticDataMemberInlineDefinition(const VarDecl * VD) const5051 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
5052   return getTargetInfo().getCXXABI().isMicrosoft() &&
5053          VD->isStaticDataMember() &&
5054          VD->getType()->isIntegralOrEnumerationType() &&
5055          !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
5056 }
5057 
5058 static inline
charUnitsToString(const CharUnits & CU)5059 std::string charUnitsToString(const CharUnits &CU) {
5060   return llvm::itostr(CU.getQuantity());
5061 }
5062 
5063 /// getObjCEncodingForBlock - Return the encoded type for this block
5064 /// declaration.
getObjCEncodingForBlock(const BlockExpr * Expr) const5065 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5066   std::string S;
5067 
5068   const BlockDecl *Decl = Expr->getBlockDecl();
5069   QualType BlockTy =
5070       Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5071   // Encode result type.
5072   if (getLangOpts().EncodeExtendedBlockSig)
5073     getObjCEncodingForMethodParameter(
5074         Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5075         true /*Extended*/);
5076   else
5077     getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
5078   // Compute size of all parameters.
5079   // Start with computing size of a pointer in number of bytes.
5080   // FIXME: There might(should) be a better way of doing this computation!
5081   SourceLocation Loc;
5082   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5083   CharUnits ParmOffset = PtrSize;
5084   for (auto PI : Decl->params()) {
5085     QualType PType = PI->getType();
5086     CharUnits sz = getObjCEncodingTypeSize(PType);
5087     if (sz.isZero())
5088       continue;
5089     assert (sz.isPositive() && "BlockExpr - Incomplete param type");
5090     ParmOffset += sz;
5091   }
5092   // Size of the argument frame
5093   S += charUnitsToString(ParmOffset);
5094   // Block pointer and offset.
5095   S += "@?0";
5096 
5097   // Argument types.
5098   ParmOffset = PtrSize;
5099   for (auto PVDecl : Decl->params()) {
5100     QualType PType = PVDecl->getOriginalType();
5101     if (const ArrayType *AT =
5102           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5103       // Use array's original type only if it has known number of
5104       // elements.
5105       if (!isa<ConstantArrayType>(AT))
5106         PType = PVDecl->getType();
5107     } else if (PType->isFunctionType())
5108       PType = PVDecl->getType();
5109     if (getLangOpts().EncodeExtendedBlockSig)
5110       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5111                                       S, true /*Extended*/);
5112     else
5113       getObjCEncodingForType(PType, S);
5114     S += charUnitsToString(ParmOffset);
5115     ParmOffset += getObjCEncodingTypeSize(PType);
5116   }
5117 
5118   return S;
5119 }
5120 
getObjCEncodingForFunctionDecl(const FunctionDecl * Decl,std::string & S)5121 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
5122                                                 std::string& S) {
5123   // Encode result type.
5124   getObjCEncodingForType(Decl->getReturnType(), S);
5125   CharUnits ParmOffset;
5126   // Compute size of all parameters.
5127   for (auto PI : Decl->params()) {
5128     QualType PType = PI->getType();
5129     CharUnits sz = getObjCEncodingTypeSize(PType);
5130     if (sz.isZero())
5131       continue;
5132 
5133     assert (sz.isPositive() &&
5134         "getObjCEncodingForFunctionDecl - Incomplete param type");
5135     ParmOffset += sz;
5136   }
5137   S += charUnitsToString(ParmOffset);
5138   ParmOffset = CharUnits::Zero();
5139 
5140   // Argument types.
5141   for (auto PVDecl : Decl->params()) {
5142     QualType PType = PVDecl->getOriginalType();
5143     if (const ArrayType *AT =
5144           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5145       // Use array's original type only if it has known number of
5146       // elements.
5147       if (!isa<ConstantArrayType>(AT))
5148         PType = PVDecl->getType();
5149     } else if (PType->isFunctionType())
5150       PType = PVDecl->getType();
5151     getObjCEncodingForType(PType, S);
5152     S += charUnitsToString(ParmOffset);
5153     ParmOffset += getObjCEncodingTypeSize(PType);
5154   }
5155 
5156   return false;
5157 }
5158 
5159 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
5160 /// method parameter or return type. If Extended, include class names and
5161 /// block object types.
getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,QualType T,std::string & S,bool Extended) const5162 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5163                                                    QualType T, std::string& S,
5164                                                    bool Extended) const {
5165   // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5166   getObjCEncodingForTypeQualifier(QT, S);
5167   // Encode parameter type.
5168   getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5169                              true     /*OutermostType*/,
5170                              false    /*EncodingProperty*/,
5171                              false    /*StructField*/,
5172                              Extended /*EncodeBlockParameters*/,
5173                              Extended /*EncodeClassNames*/);
5174 }
5175 
5176 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
5177 /// declaration.
getObjCEncodingForMethodDecl(const ObjCMethodDecl * Decl,std::string & S,bool Extended) const5178 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5179                                               std::string& S,
5180                                               bool Extended) const {
5181   // FIXME: This is not very efficient.
5182   // Encode return type.
5183   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5184                                     Decl->getReturnType(), S, Extended);
5185   // Compute size of all parameters.
5186   // Start with computing size of a pointer in number of bytes.
5187   // FIXME: There might(should) be a better way of doing this computation!
5188   SourceLocation Loc;
5189   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5190   // The first two arguments (self and _cmd) are pointers; account for
5191   // their size.
5192   CharUnits ParmOffset = 2 * PtrSize;
5193   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5194        E = Decl->sel_param_end(); PI != E; ++PI) {
5195     QualType PType = (*PI)->getType();
5196     CharUnits sz = getObjCEncodingTypeSize(PType);
5197     if (sz.isZero())
5198       continue;
5199 
5200     assert (sz.isPositive() &&
5201         "getObjCEncodingForMethodDecl - Incomplete param type");
5202     ParmOffset += sz;
5203   }
5204   S += charUnitsToString(ParmOffset);
5205   S += "@0:";
5206   S += charUnitsToString(PtrSize);
5207 
5208   // Argument types.
5209   ParmOffset = 2 * PtrSize;
5210   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5211        E = Decl->sel_param_end(); PI != E; ++PI) {
5212     const ParmVarDecl *PVDecl = *PI;
5213     QualType PType = PVDecl->getOriginalType();
5214     if (const ArrayType *AT =
5215           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5216       // Use array's original type only if it has known number of
5217       // elements.
5218       if (!isa<ConstantArrayType>(AT))
5219         PType = PVDecl->getType();
5220     } else if (PType->isFunctionType())
5221       PType = PVDecl->getType();
5222     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5223                                       PType, S, Extended);
5224     S += charUnitsToString(ParmOffset);
5225     ParmOffset += getObjCEncodingTypeSize(PType);
5226   }
5227 
5228   return false;
5229 }
5230 
5231 ObjCPropertyImplDecl *
getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl * PD,const Decl * Container) const5232 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5233                                       const ObjCPropertyDecl *PD,
5234                                       const Decl *Container) const {
5235   if (!Container)
5236     return nullptr;
5237   if (const ObjCCategoryImplDecl *CID =
5238       dyn_cast<ObjCCategoryImplDecl>(Container)) {
5239     for (auto *PID : CID->property_impls())
5240       if (PID->getPropertyDecl() == PD)
5241         return PID;
5242   } else {
5243     const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5244     for (auto *PID : OID->property_impls())
5245       if (PID->getPropertyDecl() == PD)
5246         return PID;
5247   }
5248   return nullptr;
5249 }
5250 
5251 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
5252 /// property declaration. If non-NULL, Container must be either an
5253 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5254 /// NULL when getting encodings for protocol properties.
5255 /// Property attributes are stored as a comma-delimited C string. The simple
5256 /// attributes readonly and bycopy are encoded as single characters. The
5257 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
5258 /// encoded as single characters, followed by an identifier. Property types
5259 /// are also encoded as a parametrized attribute. The characters used to encode
5260 /// these attributes are defined by the following enumeration:
5261 /// @code
5262 /// enum PropertyAttributes {
5263 /// kPropertyReadOnly = 'R',   // property is read-only.
5264 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
5265 /// kPropertyByref = '&',  // property is a reference to the value last assigned
5266 /// kPropertyDynamic = 'D',    // property is dynamic
5267 /// kPropertyGetter = 'G',     // followed by getter selector name
5268 /// kPropertySetter = 'S',     // followed by setter selector name
5269 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
5270 /// kPropertyType = 'T'              // followed by old-style type encoding.
5271 /// kPropertyWeak = 'W'              // 'weak' property
5272 /// kPropertyStrong = 'P'            // property GC'able
5273 /// kPropertyNonAtomic = 'N'         // property non-atomic
5274 /// };
5275 /// @endcode
getObjCEncodingForPropertyDecl(const ObjCPropertyDecl * PD,const Decl * Container,std::string & S) const5276 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5277                                                 const Decl *Container,
5278                                                 std::string& S) const {
5279   // Collect information from the property implementation decl(s).
5280   bool Dynamic = false;
5281   ObjCPropertyImplDecl *SynthesizePID = nullptr;
5282 
5283   if (ObjCPropertyImplDecl *PropertyImpDecl =
5284       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5285     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5286       Dynamic = true;
5287     else
5288       SynthesizePID = PropertyImpDecl;
5289   }
5290 
5291   // FIXME: This is not very efficient.
5292   S = "T";
5293 
5294   // Encode result type.
5295   // GCC has some special rules regarding encoding of properties which
5296   // closely resembles encoding of ivars.
5297   getObjCEncodingForPropertyType(PD->getType(), S);
5298 
5299   if (PD->isReadOnly()) {
5300     S += ",R";
5301     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5302       S += ",C";
5303     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5304       S += ",&";
5305     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5306       S += ",W";
5307   } else {
5308     switch (PD->getSetterKind()) {
5309     case ObjCPropertyDecl::Assign: break;
5310     case ObjCPropertyDecl::Copy:   S += ",C"; break;
5311     case ObjCPropertyDecl::Retain: S += ",&"; break;
5312     case ObjCPropertyDecl::Weak:   S += ",W"; break;
5313     }
5314   }
5315 
5316   // It really isn't clear at all what this means, since properties
5317   // are "dynamic by default".
5318   if (Dynamic)
5319     S += ",D";
5320 
5321   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5322     S += ",N";
5323 
5324   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5325     S += ",G";
5326     S += PD->getGetterName().getAsString();
5327   }
5328 
5329   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5330     S += ",S";
5331     S += PD->getSetterName().getAsString();
5332   }
5333 
5334   if (SynthesizePID) {
5335     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5336     S += ",V";
5337     S += OID->getNameAsString();
5338   }
5339 
5340   // FIXME: OBJCGC: weak & strong
5341 }
5342 
5343 /// getLegacyIntegralTypeEncoding -
5344 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5345 /// 'l' or 'L' , but not always.  For typedefs, we need to use
5346 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5347 ///
getLegacyIntegralTypeEncoding(QualType & PointeeTy) const5348 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5349   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5350     if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5351       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5352         PointeeTy = UnsignedIntTy;
5353       else
5354         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5355           PointeeTy = IntTy;
5356     }
5357   }
5358 }
5359 
getObjCEncodingForType(QualType T,std::string & S,const FieldDecl * Field,QualType * NotEncodedT) const5360 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5361                                         const FieldDecl *Field,
5362                                         QualType *NotEncodedT) const {
5363   // We follow the behavior of gcc, expanding structures which are
5364   // directly pointed to, and expanding embedded structures. Note that
5365   // these rules are sufficient to prevent recursive encoding of the
5366   // same type.
5367   getObjCEncodingForTypeImpl(T, S, true, true, Field,
5368                              true /* outermost type */, false, false,
5369                              false, false, false, NotEncodedT);
5370 }
5371 
getObjCEncodingForPropertyType(QualType T,std::string & S) const5372 void ASTContext::getObjCEncodingForPropertyType(QualType T,
5373                                                 std::string& S) const {
5374   // Encode result type.
5375   // GCC has some special rules regarding encoding of properties which
5376   // closely resembles encoding of ivars.
5377   getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5378                              true /* outermost type */,
5379                              true /* encoding property */);
5380 }
5381 
getObjCEncodingForPrimitiveKind(const ASTContext * C,BuiltinType::Kind kind)5382 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5383                                             BuiltinType::Kind kind) {
5384     switch (kind) {
5385     case BuiltinType::Void:       return 'v';
5386     case BuiltinType::Bool:       return 'B';
5387     case BuiltinType::Char_U:
5388     case BuiltinType::UChar:      return 'C';
5389     case BuiltinType::Char16:
5390     case BuiltinType::UShort:     return 'S';
5391     case BuiltinType::Char32:
5392     case BuiltinType::UInt:       return 'I';
5393     case BuiltinType::ULong:
5394         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5395     case BuiltinType::UInt128:    return 'T';
5396     case BuiltinType::ULongLong:  return 'Q';
5397     case BuiltinType::Char_S:
5398     case BuiltinType::SChar:      return 'c';
5399     case BuiltinType::Short:      return 's';
5400     case BuiltinType::WChar_S:
5401     case BuiltinType::WChar_U:
5402     case BuiltinType::Int:        return 'i';
5403     case BuiltinType::Long:
5404       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5405     case BuiltinType::LongLong:   return 'q';
5406     case BuiltinType::Int128:     return 't';
5407     case BuiltinType::Float:      return 'f';
5408     case BuiltinType::Double:     return 'd';
5409     case BuiltinType::LongDouble: return 'D';
5410     case BuiltinType::NullPtr:    return '*'; // like char*
5411 
5412     case BuiltinType::Half:
5413       // FIXME: potentially need @encodes for these!
5414       return ' ';
5415 
5416     case BuiltinType::ObjCId:
5417     case BuiltinType::ObjCClass:
5418     case BuiltinType::ObjCSel:
5419       llvm_unreachable("@encoding ObjC primitive type");
5420 
5421     // OpenCL and placeholder types don't need @encodings.
5422     case BuiltinType::OCLImage1d:
5423     case BuiltinType::OCLImage1dArray:
5424     case BuiltinType::OCLImage1dBuffer:
5425     case BuiltinType::OCLImage2d:
5426     case BuiltinType::OCLImage2dArray:
5427     case BuiltinType::OCLImage2dDepth:
5428     case BuiltinType::OCLImage2dArrayDepth:
5429     case BuiltinType::OCLImage2dMSAA:
5430     case BuiltinType::OCLImage2dArrayMSAA:
5431     case BuiltinType::OCLImage2dMSAADepth:
5432     case BuiltinType::OCLImage2dArrayMSAADepth:
5433     case BuiltinType::OCLImage3d:
5434     case BuiltinType::OCLEvent:
5435     case BuiltinType::OCLClkEvent:
5436     case BuiltinType::OCLQueue:
5437     case BuiltinType::OCLNDRange:
5438     case BuiltinType::OCLReserveID:
5439     case BuiltinType::OCLSampler:
5440     case BuiltinType::Dependent:
5441 #define BUILTIN_TYPE(KIND, ID)
5442 #define PLACEHOLDER_TYPE(KIND, ID) \
5443     case BuiltinType::KIND:
5444 #include "clang/AST/BuiltinTypes.def"
5445       llvm_unreachable("invalid builtin type for @encode");
5446     }
5447     llvm_unreachable("invalid BuiltinType::Kind value");
5448 }
5449 
ObjCEncodingForEnumType(const ASTContext * C,const EnumType * ET)5450 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5451   EnumDecl *Enum = ET->getDecl();
5452 
5453   // The encoding of an non-fixed enum type is always 'i', regardless of size.
5454   if (!Enum->isFixed())
5455     return 'i';
5456 
5457   // The encoding of a fixed enum type matches its fixed underlying type.
5458   const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5459   return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5460 }
5461 
EncodeBitField(const ASTContext * Ctx,std::string & S,QualType T,const FieldDecl * FD)5462 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5463                            QualType T, const FieldDecl *FD) {
5464   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5465   S += 'b';
5466   // The NeXT runtime encodes bit fields as b followed by the number of bits.
5467   // The GNU runtime requires more information; bitfields are encoded as b,
5468   // then the offset (in bits) of the first element, then the type of the
5469   // bitfield, then the size in bits.  For example, in this structure:
5470   //
5471   // struct
5472   // {
5473   //    int integer;
5474   //    int flags:2;
5475   // };
5476   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5477   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
5478   // information is not especially sensible, but we're stuck with it for
5479   // compatibility with GCC, although providing it breaks anything that
5480   // actually uses runtime introspection and wants to work on both runtimes...
5481   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5482     const RecordDecl *RD = FD->getParent();
5483     const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5484     S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5485     if (const EnumType *ET = T->getAs<EnumType>())
5486       S += ObjCEncodingForEnumType(Ctx, ET);
5487     else {
5488       const BuiltinType *BT = T->castAs<BuiltinType>();
5489       S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5490     }
5491   }
5492   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5493 }
5494 
5495 // FIXME: Use SmallString for accumulating string.
getObjCEncodingForTypeImpl(QualType T,std::string & S,bool ExpandPointedToStructures,bool ExpandStructures,const FieldDecl * FD,bool OutermostType,bool EncodingProperty,bool StructField,bool EncodeBlockParameters,bool EncodeClassNames,bool EncodePointerToObjCTypedef,QualType * NotEncodedT) const5496 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5497                                             bool ExpandPointedToStructures,
5498                                             bool ExpandStructures,
5499                                             const FieldDecl *FD,
5500                                             bool OutermostType,
5501                                             bool EncodingProperty,
5502                                             bool StructField,
5503                                             bool EncodeBlockParameters,
5504                                             bool EncodeClassNames,
5505                                             bool EncodePointerToObjCTypedef,
5506                                             QualType *NotEncodedT) const {
5507   CanQualType CT = getCanonicalType(T);
5508   switch (CT->getTypeClass()) {
5509   case Type::Builtin:
5510   case Type::Enum:
5511     if (FD && FD->isBitField())
5512       return EncodeBitField(this, S, T, FD);
5513     if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5514       S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5515     else
5516       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5517     return;
5518 
5519   case Type::Complex: {
5520     const ComplexType *CT = T->castAs<ComplexType>();
5521     S += 'j';
5522     getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
5523     return;
5524   }
5525 
5526   case Type::Atomic: {
5527     const AtomicType *AT = T->castAs<AtomicType>();
5528     S += 'A';
5529     getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
5530     return;
5531   }
5532 
5533   // encoding for pointer or reference types.
5534   case Type::Pointer:
5535   case Type::LValueReference:
5536   case Type::RValueReference: {
5537     QualType PointeeTy;
5538     if (isa<PointerType>(CT)) {
5539       const PointerType *PT = T->castAs<PointerType>();
5540       if (PT->isObjCSelType()) {
5541         S += ':';
5542         return;
5543       }
5544       PointeeTy = PT->getPointeeType();
5545     } else {
5546       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5547     }
5548 
5549     bool isReadOnly = false;
5550     // For historical/compatibility reasons, the read-only qualifier of the
5551     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
5552     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5553     // Also, do not emit the 'r' for anything but the outermost type!
5554     if (isa<TypedefType>(T.getTypePtr())) {
5555       if (OutermostType && T.isConstQualified()) {
5556         isReadOnly = true;
5557         S += 'r';
5558       }
5559     } else if (OutermostType) {
5560       QualType P = PointeeTy;
5561       while (P->getAs<PointerType>())
5562         P = P->getAs<PointerType>()->getPointeeType();
5563       if (P.isConstQualified()) {
5564         isReadOnly = true;
5565         S += 'r';
5566       }
5567     }
5568     if (isReadOnly) {
5569       // Another legacy compatibility encoding. Some ObjC qualifier and type
5570       // combinations need to be rearranged.
5571       // Rewrite "in const" from "nr" to "rn"
5572       if (StringRef(S).endswith("nr"))
5573         S.replace(S.end()-2, S.end(), "rn");
5574     }
5575 
5576     if (PointeeTy->isCharType()) {
5577       // char pointer types should be encoded as '*' unless it is a
5578       // type that has been typedef'd to 'BOOL'.
5579       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5580         S += '*';
5581         return;
5582       }
5583     } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5584       // GCC binary compat: Need to convert "struct objc_class *" to "#".
5585       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5586         S += '#';
5587         return;
5588       }
5589       // GCC binary compat: Need to convert "struct objc_object *" to "@".
5590       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5591         S += '@';
5592         return;
5593       }
5594       // fall through...
5595     }
5596     S += '^';
5597     getLegacyIntegralTypeEncoding(PointeeTy);
5598 
5599     getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5600                                nullptr, false, false, false, false, false, false,
5601                                NotEncodedT);
5602     return;
5603   }
5604 
5605   case Type::ConstantArray:
5606   case Type::IncompleteArray:
5607   case Type::VariableArray: {
5608     const ArrayType *AT = cast<ArrayType>(CT);
5609 
5610     if (isa<IncompleteArrayType>(AT) && !StructField) {
5611       // Incomplete arrays are encoded as a pointer to the array element.
5612       S += '^';
5613 
5614       getObjCEncodingForTypeImpl(AT->getElementType(), S,
5615                                  false, ExpandStructures, FD);
5616     } else {
5617       S += '[';
5618 
5619       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5620         S += llvm::utostr(CAT->getSize().getZExtValue());
5621       else {
5622         //Variable length arrays are encoded as a regular array with 0 elements.
5623         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5624                "Unknown array type!");
5625         S += '0';
5626       }
5627 
5628       getObjCEncodingForTypeImpl(AT->getElementType(), S,
5629                                  false, ExpandStructures, FD,
5630                                  false, false, false, false, false, false,
5631                                  NotEncodedT);
5632       S += ']';
5633     }
5634     return;
5635   }
5636 
5637   case Type::FunctionNoProto:
5638   case Type::FunctionProto:
5639     S += '?';
5640     return;
5641 
5642   case Type::Record: {
5643     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5644     S += RDecl->isUnion() ? '(' : '{';
5645     // Anonymous structures print as '?'
5646     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5647       S += II->getName();
5648       if (ClassTemplateSpecializationDecl *Spec
5649           = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5650         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5651         llvm::raw_string_ostream OS(S);
5652         TemplateSpecializationType::PrintTemplateArgumentList(OS,
5653                                             TemplateArgs.data(),
5654                                             TemplateArgs.size(),
5655                                             (*this).getPrintingPolicy());
5656       }
5657     } else {
5658       S += '?';
5659     }
5660     if (ExpandStructures) {
5661       S += '=';
5662       if (!RDecl->isUnion()) {
5663         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
5664       } else {
5665         for (const auto *Field : RDecl->fields()) {
5666           if (FD) {
5667             S += '"';
5668             S += Field->getNameAsString();
5669             S += '"';
5670           }
5671 
5672           // Special case bit-fields.
5673           if (Field->isBitField()) {
5674             getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5675                                        Field);
5676           } else {
5677             QualType qt = Field->getType();
5678             getLegacyIntegralTypeEncoding(qt);
5679             getObjCEncodingForTypeImpl(qt, S, false, true,
5680                                        FD, /*OutermostType*/false,
5681                                        /*EncodingProperty*/false,
5682                                        /*StructField*/true,
5683                                        false, false, false, NotEncodedT);
5684           }
5685         }
5686       }
5687     }
5688     S += RDecl->isUnion() ? ')' : '}';
5689     return;
5690   }
5691 
5692   case Type::BlockPointer: {
5693     const BlockPointerType *BT = T->castAs<BlockPointerType>();
5694     S += "@?"; // Unlike a pointer-to-function, which is "^?".
5695     if (EncodeBlockParameters) {
5696       const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5697 
5698       S += '<';
5699       // Block return type
5700       getObjCEncodingForTypeImpl(
5701           FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5702           FD, false /* OutermostType */, EncodingProperty,
5703           false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5704                                  NotEncodedT);
5705       // Block self
5706       S += "@?";
5707       // Block parameters
5708       if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5709         for (const auto &I : FPT->param_types())
5710           getObjCEncodingForTypeImpl(
5711               I, S, ExpandPointedToStructures, ExpandStructures, FD,
5712               false /* OutermostType */, EncodingProperty,
5713               false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5714                                      false, NotEncodedT);
5715       }
5716       S += '>';
5717     }
5718     return;
5719   }
5720 
5721   case Type::ObjCObject: {
5722     // hack to match legacy encoding of *id and *Class
5723     QualType Ty = getObjCObjectPointerType(CT);
5724     if (Ty->isObjCIdType()) {
5725       S += "{objc_object=}";
5726       return;
5727     }
5728     else if (Ty->isObjCClassType()) {
5729       S += "{objc_class=}";
5730       return;
5731     }
5732   }
5733 
5734   case Type::ObjCInterface: {
5735     // Ignore protocol qualifiers when mangling at this level.
5736     // @encode(class_name)
5737     ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
5738     S += '{';
5739     S += OI->getObjCRuntimeNameAsString();
5740     S += '=';
5741     SmallVector<const ObjCIvarDecl*, 32> Ivars;
5742     DeepCollectObjCIvars(OI, true, Ivars);
5743     for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5744       const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5745       if (Field->isBitField())
5746         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5747       else
5748         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5749                                    false, false, false, false, false,
5750                                    EncodePointerToObjCTypedef,
5751                                    NotEncodedT);
5752     }
5753     S += '}';
5754     return;
5755   }
5756 
5757   case Type::ObjCObjectPointer: {
5758     const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5759     if (OPT->isObjCIdType()) {
5760       S += '@';
5761       return;
5762     }
5763 
5764     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5765       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5766       // Since this is a binary compatibility issue, need to consult with runtime
5767       // folks. Fortunately, this is a *very* obsure construct.
5768       S += '#';
5769       return;
5770     }
5771 
5772     if (OPT->isObjCQualifiedIdType()) {
5773       getObjCEncodingForTypeImpl(getObjCIdType(), S,
5774                                  ExpandPointedToStructures,
5775                                  ExpandStructures, FD);
5776       if (FD || EncodingProperty || EncodeClassNames) {
5777         // Note that we do extended encoding of protocol qualifer list
5778         // Only when doing ivar or property encoding.
5779         S += '"';
5780         for (const auto *I : OPT->quals()) {
5781           S += '<';
5782           S += I->getObjCRuntimeNameAsString();
5783           S += '>';
5784         }
5785         S += '"';
5786       }
5787       return;
5788     }
5789 
5790     QualType PointeeTy = OPT->getPointeeType();
5791     if (!EncodingProperty &&
5792         isa<TypedefType>(PointeeTy.getTypePtr()) &&
5793         !EncodePointerToObjCTypedef) {
5794       // Another historical/compatibility reason.
5795       // We encode the underlying type which comes out as
5796       // {...};
5797       S += '^';
5798       if (FD && OPT->getInterfaceDecl()) {
5799         // Prevent recursive encoding of fields in some rare cases.
5800         ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5801         SmallVector<const ObjCIvarDecl*, 32> Ivars;
5802         DeepCollectObjCIvars(OI, true, Ivars);
5803         for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5804           if (cast<FieldDecl>(Ivars[i]) == FD) {
5805             S += '{';
5806             S += OI->getObjCRuntimeNameAsString();
5807             S += '}';
5808             return;
5809           }
5810         }
5811       }
5812       getObjCEncodingForTypeImpl(PointeeTy, S,
5813                                  false, ExpandPointedToStructures,
5814                                  nullptr,
5815                                  false, false, false, false, false,
5816                                  /*EncodePointerToObjCTypedef*/true);
5817       return;
5818     }
5819 
5820     S += '@';
5821     if (OPT->getInterfaceDecl() &&
5822         (FD || EncodingProperty || EncodeClassNames)) {
5823       S += '"';
5824       S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
5825       for (const auto *I : OPT->quals()) {
5826         S += '<';
5827         S += I->getObjCRuntimeNameAsString();
5828         S += '>';
5829       }
5830       S += '"';
5831     }
5832     return;
5833   }
5834 
5835   // gcc just blithely ignores member pointers.
5836   // FIXME: we shoul do better than that.  'M' is available.
5837   case Type::MemberPointer:
5838   // This matches gcc's encoding, even though technically it is insufficient.
5839   //FIXME. We should do a better job than gcc.
5840   case Type::Vector:
5841   case Type::ExtVector:
5842   // Until we have a coherent encoding of these three types, issue warning.
5843     { if (NotEncodedT)
5844         *NotEncodedT = T;
5845       return;
5846     }
5847 
5848   // We could see an undeduced auto type here during error recovery.
5849   // Just ignore it.
5850   case Type::Auto:
5851     return;
5852 
5853 #define ABSTRACT_TYPE(KIND, BASE)
5854 #define TYPE(KIND, BASE)
5855 #define DEPENDENT_TYPE(KIND, BASE) \
5856   case Type::KIND:
5857 #define NON_CANONICAL_TYPE(KIND, BASE) \
5858   case Type::KIND:
5859 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5860   case Type::KIND:
5861 #include "clang/AST/TypeNodes.def"
5862     llvm_unreachable("@encode for dependent type!");
5863   }
5864   llvm_unreachable("bad type kind!");
5865 }
5866 
getObjCEncodingForStructureImpl(RecordDecl * RDecl,std::string & S,const FieldDecl * FD,bool includeVBases,QualType * NotEncodedT) const5867 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5868                                                  std::string &S,
5869                                                  const FieldDecl *FD,
5870                                                  bool includeVBases,
5871                                                  QualType *NotEncodedT) const {
5872   assert(RDecl && "Expected non-null RecordDecl");
5873   assert(!RDecl->isUnion() && "Should not be called for unions");
5874   if (!RDecl->getDefinition())
5875     return;
5876 
5877   CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5878   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5879   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5880 
5881   if (CXXRec) {
5882     for (const auto &BI : CXXRec->bases()) {
5883       if (!BI.isVirtual()) {
5884         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5885         if (base->isEmpty())
5886           continue;
5887         uint64_t offs = toBits(layout.getBaseClassOffset(base));
5888         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5889                                   std::make_pair(offs, base));
5890       }
5891     }
5892   }
5893 
5894   unsigned i = 0;
5895   for (auto *Field : RDecl->fields()) {
5896     uint64_t offs = layout.getFieldOffset(i);
5897     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5898                               std::make_pair(offs, Field));
5899     ++i;
5900   }
5901 
5902   if (CXXRec && includeVBases) {
5903     for (const auto &BI : CXXRec->vbases()) {
5904       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5905       if (base->isEmpty())
5906         continue;
5907       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
5908       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5909           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5910         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5911                                   std::make_pair(offs, base));
5912     }
5913   }
5914 
5915   CharUnits size;
5916   if (CXXRec) {
5917     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5918   } else {
5919     size = layout.getSize();
5920   }
5921 
5922 #ifndef NDEBUG
5923   uint64_t CurOffs = 0;
5924 #endif
5925   std::multimap<uint64_t, NamedDecl *>::iterator
5926     CurLayObj = FieldOrBaseOffsets.begin();
5927 
5928   if (CXXRec && CXXRec->isDynamicClass() &&
5929       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
5930     if (FD) {
5931       S += "\"_vptr$";
5932       std::string recname = CXXRec->getNameAsString();
5933       if (recname.empty()) recname = "?";
5934       S += recname;
5935       S += '"';
5936     }
5937     S += "^^?";
5938 #ifndef NDEBUG
5939     CurOffs += getTypeSize(VoidPtrTy);
5940 #endif
5941   }
5942 
5943   if (!RDecl->hasFlexibleArrayMember()) {
5944     // Mark the end of the structure.
5945     uint64_t offs = toBits(size);
5946     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5947                               std::make_pair(offs, nullptr));
5948   }
5949 
5950   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5951 #ifndef NDEBUG
5952     assert(CurOffs <= CurLayObj->first);
5953     if (CurOffs < CurLayObj->first) {
5954       uint64_t padding = CurLayObj->first - CurOffs;
5955       // FIXME: There doesn't seem to be a way to indicate in the encoding that
5956       // packing/alignment of members is different that normal, in which case
5957       // the encoding will be out-of-sync with the real layout.
5958       // If the runtime switches to just consider the size of types without
5959       // taking into account alignment, we could make padding explicit in the
5960       // encoding (e.g. using arrays of chars). The encoding strings would be
5961       // longer then though.
5962       CurOffs += padding;
5963     }
5964 #endif
5965 
5966     NamedDecl *dcl = CurLayObj->second;
5967     if (!dcl)
5968       break; // reached end of structure.
5969 
5970     if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5971       // We expand the bases without their virtual bases since those are going
5972       // in the initial structure. Note that this differs from gcc which
5973       // expands virtual bases each time one is encountered in the hierarchy,
5974       // making the encoding type bigger than it really is.
5975       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5976                                       NotEncodedT);
5977       assert(!base->isEmpty());
5978 #ifndef NDEBUG
5979       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
5980 #endif
5981     } else {
5982       FieldDecl *field = cast<FieldDecl>(dcl);
5983       if (FD) {
5984         S += '"';
5985         S += field->getNameAsString();
5986         S += '"';
5987       }
5988 
5989       if (field->isBitField()) {
5990         EncodeBitField(this, S, field->getType(), field);
5991 #ifndef NDEBUG
5992         CurOffs += field->getBitWidthValue(*this);
5993 #endif
5994       } else {
5995         QualType qt = field->getType();
5996         getLegacyIntegralTypeEncoding(qt);
5997         getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5998                                    /*OutermostType*/false,
5999                                    /*EncodingProperty*/false,
6000                                    /*StructField*/true,
6001                                    false, false, false, NotEncodedT);
6002 #ifndef NDEBUG
6003         CurOffs += getTypeSize(field->getType());
6004 #endif
6005       }
6006     }
6007   }
6008 }
6009 
getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,std::string & S) const6010 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
6011                                                  std::string& S) const {
6012   if (QT & Decl::OBJC_TQ_In)
6013     S += 'n';
6014   if (QT & Decl::OBJC_TQ_Inout)
6015     S += 'N';
6016   if (QT & Decl::OBJC_TQ_Out)
6017     S += 'o';
6018   if (QT & Decl::OBJC_TQ_Bycopy)
6019     S += 'O';
6020   if (QT & Decl::OBJC_TQ_Byref)
6021     S += 'R';
6022   if (QT & Decl::OBJC_TQ_Oneway)
6023     S += 'V';
6024 }
6025 
getObjCIdDecl() const6026 TypedefDecl *ASTContext::getObjCIdDecl() const {
6027   if (!ObjCIdDecl) {
6028     QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
6029     T = getObjCObjectPointerType(T);
6030     ObjCIdDecl = buildImplicitTypedef(T, "id");
6031   }
6032   return ObjCIdDecl;
6033 }
6034 
getObjCSelDecl() const6035 TypedefDecl *ASTContext::getObjCSelDecl() const {
6036   if (!ObjCSelDecl) {
6037     QualType T = getPointerType(ObjCBuiltinSelTy);
6038     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
6039   }
6040   return ObjCSelDecl;
6041 }
6042 
getObjCClassDecl() const6043 TypedefDecl *ASTContext::getObjCClassDecl() const {
6044   if (!ObjCClassDecl) {
6045     QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
6046     T = getObjCObjectPointerType(T);
6047     ObjCClassDecl = buildImplicitTypedef(T, "Class");
6048   }
6049   return ObjCClassDecl;
6050 }
6051 
getObjCProtocolDecl() const6052 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6053   if (!ObjCProtocolClassDecl) {
6054     ObjCProtocolClassDecl
6055       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6056                                   SourceLocation(),
6057                                   &Idents.get("Protocol"),
6058                                   /*typeParamList=*/nullptr,
6059                                   /*PrevDecl=*/nullptr,
6060                                   SourceLocation(), true);
6061   }
6062 
6063   return ObjCProtocolClassDecl;
6064 }
6065 
6066 //===----------------------------------------------------------------------===//
6067 // __builtin_va_list Construction Functions
6068 //===----------------------------------------------------------------------===//
6069 
CreateCharPtrNamedVaListDecl(const ASTContext * Context,StringRef Name)6070 static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6071                                                  StringRef Name) {
6072   // typedef char* __builtin[_ms]_va_list;
6073   QualType T = Context->getPointerType(Context->CharTy);
6074   return Context->buildImplicitTypedef(T, Name);
6075 }
6076 
CreateMSVaListDecl(const ASTContext * Context)6077 static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6078   return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6079 }
6080 
CreateCharPtrBuiltinVaListDecl(const ASTContext * Context)6081 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6082   return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
6083 }
6084 
CreateVoidPtrBuiltinVaListDecl(const ASTContext * Context)6085 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6086   // typedef void* __builtin_va_list;
6087   QualType T = Context->getPointerType(Context->VoidTy);
6088   return Context->buildImplicitTypedef(T, "__builtin_va_list");
6089 }
6090 
6091 static TypedefDecl *
CreateAArch64ABIBuiltinVaListDecl(const ASTContext * Context)6092 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
6093   // struct __va_list
6094   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
6095   if (Context->getLangOpts().CPlusPlus) {
6096     // namespace std { struct __va_list {
6097     NamespaceDecl *NS;
6098     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6099                                Context->getTranslationUnitDecl(),
6100                                /*Inline*/ false, SourceLocation(),
6101                                SourceLocation(), &Context->Idents.get("std"),
6102                                /*PrevDecl*/ nullptr);
6103     NS->setImplicit();
6104     VaListTagDecl->setDeclContext(NS);
6105   }
6106 
6107   VaListTagDecl->startDefinition();
6108 
6109   const size_t NumFields = 5;
6110   QualType FieldTypes[NumFields];
6111   const char *FieldNames[NumFields];
6112 
6113   // void *__stack;
6114   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6115   FieldNames[0] = "__stack";
6116 
6117   // void *__gr_top;
6118   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6119   FieldNames[1] = "__gr_top";
6120 
6121   // void *__vr_top;
6122   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6123   FieldNames[2] = "__vr_top";
6124 
6125   // int __gr_offs;
6126   FieldTypes[3] = Context->IntTy;
6127   FieldNames[3] = "__gr_offs";
6128 
6129   // int __vr_offs;
6130   FieldTypes[4] = Context->IntTy;
6131   FieldNames[4] = "__vr_offs";
6132 
6133   // Create fields
6134   for (unsigned i = 0; i < NumFields; ++i) {
6135     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6136                                          VaListTagDecl,
6137                                          SourceLocation(),
6138                                          SourceLocation(),
6139                                          &Context->Idents.get(FieldNames[i]),
6140                                          FieldTypes[i], /*TInfo=*/nullptr,
6141                                          /*BitWidth=*/nullptr,
6142                                          /*Mutable=*/false,
6143                                          ICIS_NoInit);
6144     Field->setAccess(AS_public);
6145     VaListTagDecl->addDecl(Field);
6146   }
6147   VaListTagDecl->completeDefinition();
6148   Context->VaListTagDecl = VaListTagDecl;
6149   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6150 
6151   // } __builtin_va_list;
6152   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
6153 }
6154 
CreatePowerABIBuiltinVaListDecl(const ASTContext * Context)6155 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6156   // typedef struct __va_list_tag {
6157   RecordDecl *VaListTagDecl;
6158 
6159   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6160   VaListTagDecl->startDefinition();
6161 
6162   const size_t NumFields = 5;
6163   QualType FieldTypes[NumFields];
6164   const char *FieldNames[NumFields];
6165 
6166   //   unsigned char gpr;
6167   FieldTypes[0] = Context->UnsignedCharTy;
6168   FieldNames[0] = "gpr";
6169 
6170   //   unsigned char fpr;
6171   FieldTypes[1] = Context->UnsignedCharTy;
6172   FieldNames[1] = "fpr";
6173 
6174   //   unsigned short reserved;
6175   FieldTypes[2] = Context->UnsignedShortTy;
6176   FieldNames[2] = "reserved";
6177 
6178   //   void* overflow_arg_area;
6179   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6180   FieldNames[3] = "overflow_arg_area";
6181 
6182   //   void* reg_save_area;
6183   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6184   FieldNames[4] = "reg_save_area";
6185 
6186   // Create fields
6187   for (unsigned i = 0; i < NumFields; ++i) {
6188     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6189                                          SourceLocation(),
6190                                          SourceLocation(),
6191                                          &Context->Idents.get(FieldNames[i]),
6192                                          FieldTypes[i], /*TInfo=*/nullptr,
6193                                          /*BitWidth=*/nullptr,
6194                                          /*Mutable=*/false,
6195                                          ICIS_NoInit);
6196     Field->setAccess(AS_public);
6197     VaListTagDecl->addDecl(Field);
6198   }
6199   VaListTagDecl->completeDefinition();
6200   Context->VaListTagDecl = VaListTagDecl;
6201   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6202 
6203   // } __va_list_tag;
6204   TypedefDecl *VaListTagTypedefDecl =
6205       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6206 
6207   QualType VaListTagTypedefType =
6208     Context->getTypedefType(VaListTagTypedefDecl);
6209 
6210   // typedef __va_list_tag __builtin_va_list[1];
6211   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6212   QualType VaListTagArrayType
6213     = Context->getConstantArrayType(VaListTagTypedefType,
6214                                     Size, ArrayType::Normal, 0);
6215   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6216 }
6217 
6218 static TypedefDecl *
CreateX86_64ABIBuiltinVaListDecl(const ASTContext * Context)6219 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6220   // struct __va_list_tag {
6221   RecordDecl *VaListTagDecl;
6222   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6223   VaListTagDecl->startDefinition();
6224 
6225   const size_t NumFields = 4;
6226   QualType FieldTypes[NumFields];
6227   const char *FieldNames[NumFields];
6228 
6229   //   unsigned gp_offset;
6230   FieldTypes[0] = Context->UnsignedIntTy;
6231   FieldNames[0] = "gp_offset";
6232 
6233   //   unsigned fp_offset;
6234   FieldTypes[1] = Context->UnsignedIntTy;
6235   FieldNames[1] = "fp_offset";
6236 
6237   //   void* overflow_arg_area;
6238   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6239   FieldNames[2] = "overflow_arg_area";
6240 
6241   //   void* reg_save_area;
6242   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6243   FieldNames[3] = "reg_save_area";
6244 
6245   // Create fields
6246   for (unsigned i = 0; i < NumFields; ++i) {
6247     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6248                                          VaListTagDecl,
6249                                          SourceLocation(),
6250                                          SourceLocation(),
6251                                          &Context->Idents.get(FieldNames[i]),
6252                                          FieldTypes[i], /*TInfo=*/nullptr,
6253                                          /*BitWidth=*/nullptr,
6254                                          /*Mutable=*/false,
6255                                          ICIS_NoInit);
6256     Field->setAccess(AS_public);
6257     VaListTagDecl->addDecl(Field);
6258   }
6259   VaListTagDecl->completeDefinition();
6260   Context->VaListTagDecl = VaListTagDecl;
6261   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6262 
6263   // };
6264 
6265   // typedef struct __va_list_tag __builtin_va_list[1];
6266   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6267   QualType VaListTagArrayType =
6268       Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6269   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6270 }
6271 
CreatePNaClABIBuiltinVaListDecl(const ASTContext * Context)6272 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6273   // typedef int __builtin_va_list[4];
6274   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6275   QualType IntArrayType
6276     = Context->getConstantArrayType(Context->IntTy,
6277 				    Size, ArrayType::Normal, 0);
6278   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6279 }
6280 
6281 static TypedefDecl *
CreateAAPCSABIBuiltinVaListDecl(const ASTContext * Context)6282 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6283   // struct __va_list
6284   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6285   if (Context->getLangOpts().CPlusPlus) {
6286     // namespace std { struct __va_list {
6287     NamespaceDecl *NS;
6288     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6289                                Context->getTranslationUnitDecl(),
6290                                /*Inline*/false, SourceLocation(),
6291                                SourceLocation(), &Context->Idents.get("std"),
6292                                /*PrevDecl*/ nullptr);
6293     NS->setImplicit();
6294     VaListDecl->setDeclContext(NS);
6295   }
6296 
6297   VaListDecl->startDefinition();
6298 
6299   // void * __ap;
6300   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6301                                        VaListDecl,
6302                                        SourceLocation(),
6303                                        SourceLocation(),
6304                                        &Context->Idents.get("__ap"),
6305                                        Context->getPointerType(Context->VoidTy),
6306                                        /*TInfo=*/nullptr,
6307                                        /*BitWidth=*/nullptr,
6308                                        /*Mutable=*/false,
6309                                        ICIS_NoInit);
6310   Field->setAccess(AS_public);
6311   VaListDecl->addDecl(Field);
6312 
6313   // };
6314   VaListDecl->completeDefinition();
6315 
6316   // typedef struct __va_list __builtin_va_list;
6317   QualType T = Context->getRecordType(VaListDecl);
6318   return Context->buildImplicitTypedef(T, "__builtin_va_list");
6319 }
6320 
6321 static TypedefDecl *
CreateSystemZBuiltinVaListDecl(const ASTContext * Context)6322 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6323   // struct __va_list_tag {
6324   RecordDecl *VaListTagDecl;
6325   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6326   VaListTagDecl->startDefinition();
6327 
6328   const size_t NumFields = 4;
6329   QualType FieldTypes[NumFields];
6330   const char *FieldNames[NumFields];
6331 
6332   //   long __gpr;
6333   FieldTypes[0] = Context->LongTy;
6334   FieldNames[0] = "__gpr";
6335 
6336   //   long __fpr;
6337   FieldTypes[1] = Context->LongTy;
6338   FieldNames[1] = "__fpr";
6339 
6340   //   void *__overflow_arg_area;
6341   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6342   FieldNames[2] = "__overflow_arg_area";
6343 
6344   //   void *__reg_save_area;
6345   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6346   FieldNames[3] = "__reg_save_area";
6347 
6348   // Create fields
6349   for (unsigned i = 0; i < NumFields; ++i) {
6350     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6351                                          VaListTagDecl,
6352                                          SourceLocation(),
6353                                          SourceLocation(),
6354                                          &Context->Idents.get(FieldNames[i]),
6355                                          FieldTypes[i], /*TInfo=*/nullptr,
6356                                          /*BitWidth=*/nullptr,
6357                                          /*Mutable=*/false,
6358                                          ICIS_NoInit);
6359     Field->setAccess(AS_public);
6360     VaListTagDecl->addDecl(Field);
6361   }
6362   VaListTagDecl->completeDefinition();
6363   Context->VaListTagDecl = VaListTagDecl;
6364   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6365 
6366   // };
6367 
6368   // typedef __va_list_tag __builtin_va_list[1];
6369   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6370   QualType VaListTagArrayType =
6371       Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
6372 
6373   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6374 }
6375 
CreateVaListDecl(const ASTContext * Context,TargetInfo::BuiltinVaListKind Kind)6376 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6377                                      TargetInfo::BuiltinVaListKind Kind) {
6378   switch (Kind) {
6379   case TargetInfo::CharPtrBuiltinVaList:
6380     return CreateCharPtrBuiltinVaListDecl(Context);
6381   case TargetInfo::VoidPtrBuiltinVaList:
6382     return CreateVoidPtrBuiltinVaListDecl(Context);
6383   case TargetInfo::AArch64ABIBuiltinVaList:
6384     return CreateAArch64ABIBuiltinVaListDecl(Context);
6385   case TargetInfo::PowerABIBuiltinVaList:
6386     return CreatePowerABIBuiltinVaListDecl(Context);
6387   case TargetInfo::X86_64ABIBuiltinVaList:
6388     return CreateX86_64ABIBuiltinVaListDecl(Context);
6389   case TargetInfo::PNaClABIBuiltinVaList:
6390     return CreatePNaClABIBuiltinVaListDecl(Context);
6391   case TargetInfo::AAPCSABIBuiltinVaList:
6392     return CreateAAPCSABIBuiltinVaListDecl(Context);
6393   case TargetInfo::SystemZBuiltinVaList:
6394     return CreateSystemZBuiltinVaListDecl(Context);
6395   }
6396 
6397   llvm_unreachable("Unhandled __builtin_va_list type kind");
6398 }
6399 
getBuiltinVaListDecl() const6400 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6401   if (!BuiltinVaListDecl) {
6402     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6403     assert(BuiltinVaListDecl->isImplicit());
6404   }
6405 
6406   return BuiltinVaListDecl;
6407 }
6408 
getVaListTagDecl() const6409 Decl *ASTContext::getVaListTagDecl() const {
6410   // Force the creation of VaListTagDecl by building the __builtin_va_list
6411   // declaration.
6412   if (!VaListTagDecl)
6413     (void)getBuiltinVaListDecl();
6414 
6415   return VaListTagDecl;
6416 }
6417 
getBuiltinMSVaListDecl() const6418 TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6419   if (!BuiltinMSVaListDecl)
6420     BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6421 
6422   return BuiltinMSVaListDecl;
6423 }
6424 
setObjCConstantStringInterface(ObjCInterfaceDecl * Decl)6425 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6426   assert(ObjCConstantStringType.isNull() &&
6427          "'NSConstantString' type already set!");
6428 
6429   ObjCConstantStringType = getObjCInterfaceType(Decl);
6430 }
6431 
6432 /// \brief Retrieve the template name that corresponds to a non-empty
6433 /// lookup.
6434 TemplateName
getOverloadedTemplateName(UnresolvedSetIterator Begin,UnresolvedSetIterator End) const6435 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6436                                       UnresolvedSetIterator End) const {
6437   unsigned size = End - Begin;
6438   assert(size > 1 && "set is not overloaded!");
6439 
6440   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6441                           size * sizeof(FunctionTemplateDecl*));
6442   OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6443 
6444   NamedDecl **Storage = OT->getStorage();
6445   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6446     NamedDecl *D = *I;
6447     assert(isa<FunctionTemplateDecl>(D) ||
6448            (isa<UsingShadowDecl>(D) &&
6449             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6450     *Storage++ = D;
6451   }
6452 
6453   return TemplateName(OT);
6454 }
6455 
6456 /// \brief Retrieve the template name that represents a qualified
6457 /// template name such as \c std::vector.
6458 TemplateName
getQualifiedTemplateName(NestedNameSpecifier * NNS,bool TemplateKeyword,TemplateDecl * Template) const6459 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6460                                      bool TemplateKeyword,
6461                                      TemplateDecl *Template) const {
6462   assert(NNS && "Missing nested-name-specifier in qualified template name");
6463 
6464   // FIXME: Canonicalization?
6465   llvm::FoldingSetNodeID ID;
6466   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6467 
6468   void *InsertPos = nullptr;
6469   QualifiedTemplateName *QTN =
6470     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6471   if (!QTN) {
6472     QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6473         QualifiedTemplateName(NNS, TemplateKeyword, Template);
6474     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6475   }
6476 
6477   return TemplateName(QTN);
6478 }
6479 
6480 /// \brief Retrieve the template name that represents a dependent
6481 /// template name such as \c MetaFun::template apply.
6482 TemplateName
getDependentTemplateName(NestedNameSpecifier * NNS,const IdentifierInfo * Name) const6483 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6484                                      const IdentifierInfo *Name) const {
6485   assert((!NNS || NNS->isDependent()) &&
6486          "Nested name specifier must be dependent");
6487 
6488   llvm::FoldingSetNodeID ID;
6489   DependentTemplateName::Profile(ID, NNS, Name);
6490 
6491   void *InsertPos = nullptr;
6492   DependentTemplateName *QTN =
6493     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6494 
6495   if (QTN)
6496     return TemplateName(QTN);
6497 
6498   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6499   if (CanonNNS == NNS) {
6500     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6501         DependentTemplateName(NNS, Name);
6502   } else {
6503     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6504     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6505         DependentTemplateName(NNS, Name, Canon);
6506     DependentTemplateName *CheckQTN =
6507       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6508     assert(!CheckQTN && "Dependent type name canonicalization broken");
6509     (void)CheckQTN;
6510   }
6511 
6512   DependentTemplateNames.InsertNode(QTN, InsertPos);
6513   return TemplateName(QTN);
6514 }
6515 
6516 /// \brief Retrieve the template name that represents a dependent
6517 /// template name such as \c MetaFun::template operator+.
6518 TemplateName
getDependentTemplateName(NestedNameSpecifier * NNS,OverloadedOperatorKind Operator) const6519 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6520                                      OverloadedOperatorKind Operator) const {
6521   assert((!NNS || NNS->isDependent()) &&
6522          "Nested name specifier must be dependent");
6523 
6524   llvm::FoldingSetNodeID ID;
6525   DependentTemplateName::Profile(ID, NNS, Operator);
6526 
6527   void *InsertPos = nullptr;
6528   DependentTemplateName *QTN
6529     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6530 
6531   if (QTN)
6532     return TemplateName(QTN);
6533 
6534   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6535   if (CanonNNS == NNS) {
6536     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6537         DependentTemplateName(NNS, Operator);
6538   } else {
6539     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6540     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6541         DependentTemplateName(NNS, Operator, Canon);
6542 
6543     DependentTemplateName *CheckQTN
6544       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6545     assert(!CheckQTN && "Dependent template name canonicalization broken");
6546     (void)CheckQTN;
6547   }
6548 
6549   DependentTemplateNames.InsertNode(QTN, InsertPos);
6550   return TemplateName(QTN);
6551 }
6552 
6553 TemplateName
getSubstTemplateTemplateParm(TemplateTemplateParmDecl * param,TemplateName replacement) const6554 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6555                                          TemplateName replacement) const {
6556   llvm::FoldingSetNodeID ID;
6557   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6558 
6559   void *insertPos = nullptr;
6560   SubstTemplateTemplateParmStorage *subst
6561     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6562 
6563   if (!subst) {
6564     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6565     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6566   }
6567 
6568   return TemplateName(subst);
6569 }
6570 
6571 TemplateName
getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl * Param,const TemplateArgument & ArgPack) const6572 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6573                                        const TemplateArgument &ArgPack) const {
6574   ASTContext &Self = const_cast<ASTContext &>(*this);
6575   llvm::FoldingSetNodeID ID;
6576   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6577 
6578   void *InsertPos = nullptr;
6579   SubstTemplateTemplateParmPackStorage *Subst
6580     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6581 
6582   if (!Subst) {
6583     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6584                                                            ArgPack.pack_size(),
6585                                                          ArgPack.pack_begin());
6586     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6587   }
6588 
6589   return TemplateName(Subst);
6590 }
6591 
6592 /// getFromTargetType - Given one of the integer types provided by
6593 /// TargetInfo, produce the corresponding type. The unsigned @p Type
6594 /// is actually a value of type @c TargetInfo::IntType.
getFromTargetType(unsigned Type) const6595 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6596   switch (Type) {
6597   case TargetInfo::NoInt: return CanQualType();
6598   case TargetInfo::SignedChar: return SignedCharTy;
6599   case TargetInfo::UnsignedChar: return UnsignedCharTy;
6600   case TargetInfo::SignedShort: return ShortTy;
6601   case TargetInfo::UnsignedShort: return UnsignedShortTy;
6602   case TargetInfo::SignedInt: return IntTy;
6603   case TargetInfo::UnsignedInt: return UnsignedIntTy;
6604   case TargetInfo::SignedLong: return LongTy;
6605   case TargetInfo::UnsignedLong: return UnsignedLongTy;
6606   case TargetInfo::SignedLongLong: return LongLongTy;
6607   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6608   }
6609 
6610   llvm_unreachable("Unhandled TargetInfo::IntType value");
6611 }
6612 
6613 //===----------------------------------------------------------------------===//
6614 //                        Type Predicates.
6615 //===----------------------------------------------------------------------===//
6616 
6617 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6618 /// garbage collection attribute.
6619 ///
getObjCGCAttrKind(QualType Ty) const6620 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6621   if (getLangOpts().getGC() == LangOptions::NonGC)
6622     return Qualifiers::GCNone;
6623 
6624   assert(getLangOpts().ObjC1);
6625   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6626 
6627   // Default behaviour under objective-C's gc is for ObjC pointers
6628   // (or pointers to them) be treated as though they were declared
6629   // as __strong.
6630   if (GCAttrs == Qualifiers::GCNone) {
6631     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6632       return Qualifiers::Strong;
6633     else if (Ty->isPointerType())
6634       return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6635   } else {
6636     // It's not valid to set GC attributes on anything that isn't a
6637     // pointer.
6638 #ifndef NDEBUG
6639     QualType CT = Ty->getCanonicalTypeInternal();
6640     while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6641       CT = AT->getElementType();
6642     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6643 #endif
6644   }
6645   return GCAttrs;
6646 }
6647 
6648 //===----------------------------------------------------------------------===//
6649 //                        Type Compatibility Testing
6650 //===----------------------------------------------------------------------===//
6651 
6652 /// areCompatVectorTypes - Return true if the two specified vector types are
6653 /// compatible.
areCompatVectorTypes(const VectorType * LHS,const VectorType * RHS)6654 static bool areCompatVectorTypes(const VectorType *LHS,
6655                                  const VectorType *RHS) {
6656   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6657   return LHS->getElementType() == RHS->getElementType() &&
6658          LHS->getNumElements() == RHS->getNumElements();
6659 }
6660 
areCompatibleVectorTypes(QualType FirstVec,QualType SecondVec)6661 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6662                                           QualType SecondVec) {
6663   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6664   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6665 
6666   if (hasSameUnqualifiedType(FirstVec, SecondVec))
6667     return true;
6668 
6669   // Treat Neon vector types and most AltiVec vector types as if they are the
6670   // equivalent GCC vector types.
6671   const VectorType *First = FirstVec->getAs<VectorType>();
6672   const VectorType *Second = SecondVec->getAs<VectorType>();
6673   if (First->getNumElements() == Second->getNumElements() &&
6674       hasSameType(First->getElementType(), Second->getElementType()) &&
6675       First->getVectorKind() != VectorType::AltiVecPixel &&
6676       First->getVectorKind() != VectorType::AltiVecBool &&
6677       Second->getVectorKind() != VectorType::AltiVecPixel &&
6678       Second->getVectorKind() != VectorType::AltiVecBool)
6679     return true;
6680 
6681   return false;
6682 }
6683 
6684 //===----------------------------------------------------------------------===//
6685 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6686 //===----------------------------------------------------------------------===//
6687 
6688 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6689 /// inheritance hierarchy of 'rProto'.
6690 bool
ProtocolCompatibleWithProtocol(ObjCProtocolDecl * lProto,ObjCProtocolDecl * rProto) const6691 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6692                                            ObjCProtocolDecl *rProto) const {
6693   if (declaresSameEntity(lProto, rProto))
6694     return true;
6695   for (auto *PI : rProto->protocols())
6696     if (ProtocolCompatibleWithProtocol(lProto, PI))
6697       return true;
6698   return false;
6699 }
6700 
6701 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
6702 /// Class<pr1, ...>.
ObjCQualifiedClassTypesAreCompatible(QualType lhs,QualType rhs)6703 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6704                                                       QualType rhs) {
6705   const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6706   const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6707   assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6708 
6709   for (auto *lhsProto : lhsQID->quals()) {
6710     bool match = false;
6711     for (auto *rhsProto : rhsOPT->quals()) {
6712       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6713         match = true;
6714         break;
6715       }
6716     }
6717     if (!match)
6718       return false;
6719   }
6720   return true;
6721 }
6722 
6723 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6724 /// ObjCQualifiedIDType.
ObjCQualifiedIdTypesAreCompatible(QualType lhs,QualType rhs,bool compare)6725 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6726                                                    bool compare) {
6727   // Allow id<P..> and an 'id' or void* type in all cases.
6728   if (lhs->isVoidPointerType() ||
6729       lhs->isObjCIdType() || lhs->isObjCClassType())
6730     return true;
6731   else if (rhs->isVoidPointerType() ||
6732            rhs->isObjCIdType() || rhs->isObjCClassType())
6733     return true;
6734 
6735   if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6736     const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6737 
6738     if (!rhsOPT) return false;
6739 
6740     if (rhsOPT->qual_empty()) {
6741       // If the RHS is a unqualified interface pointer "NSString*",
6742       // make sure we check the class hierarchy.
6743       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6744         for (auto *I : lhsQID->quals()) {
6745           // when comparing an id<P> on lhs with a static type on rhs,
6746           // see if static class implements all of id's protocols, directly or
6747           // through its super class and categories.
6748           if (!rhsID->ClassImplementsProtocol(I, true))
6749             return false;
6750         }
6751       }
6752       // If there are no qualifiers and no interface, we have an 'id'.
6753       return true;
6754     }
6755     // Both the right and left sides have qualifiers.
6756     for (auto *lhsProto : lhsQID->quals()) {
6757       bool match = false;
6758 
6759       // when comparing an id<P> on lhs with a static type on rhs,
6760       // see if static class implements all of id's protocols, directly or
6761       // through its super class and categories.
6762       for (auto *rhsProto : rhsOPT->quals()) {
6763         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6764             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6765           match = true;
6766           break;
6767         }
6768       }
6769       // If the RHS is a qualified interface pointer "NSString<P>*",
6770       // make sure we check the class hierarchy.
6771       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6772         for (auto *I : lhsQID->quals()) {
6773           // when comparing an id<P> on lhs with a static type on rhs,
6774           // see if static class implements all of id's protocols, directly or
6775           // through its super class and categories.
6776           if (rhsID->ClassImplementsProtocol(I, true)) {
6777             match = true;
6778             break;
6779           }
6780         }
6781       }
6782       if (!match)
6783         return false;
6784     }
6785 
6786     return true;
6787   }
6788 
6789   const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6790   assert(rhsQID && "One of the LHS/RHS should be id<x>");
6791 
6792   if (const ObjCObjectPointerType *lhsOPT =
6793         lhs->getAsObjCInterfacePointerType()) {
6794     // If both the right and left sides have qualifiers.
6795     for (auto *lhsProto : lhsOPT->quals()) {
6796       bool match = false;
6797 
6798       // when comparing an id<P> on rhs with a static type on lhs,
6799       // see if static class implements all of id's protocols, directly or
6800       // through its super class and categories.
6801       // First, lhs protocols in the qualifier list must be found, direct
6802       // or indirect in rhs's qualifier list or it is a mismatch.
6803       for (auto *rhsProto : rhsQID->quals()) {
6804         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6805             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6806           match = true;
6807           break;
6808         }
6809       }
6810       if (!match)
6811         return false;
6812     }
6813 
6814     // Static class's protocols, or its super class or category protocols
6815     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6816     if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6817       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6818       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6819       // This is rather dubious but matches gcc's behavior. If lhs has
6820       // no type qualifier and its class has no static protocol(s)
6821       // assume that it is mismatch.
6822       if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6823         return false;
6824       for (auto *lhsProto : LHSInheritedProtocols) {
6825         bool match = false;
6826         for (auto *rhsProto : rhsQID->quals()) {
6827           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6828               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6829             match = true;
6830             break;
6831           }
6832         }
6833         if (!match)
6834           return false;
6835       }
6836     }
6837     return true;
6838   }
6839   return false;
6840 }
6841 
6842 /// canAssignObjCInterfaces - Return true if the two interface types are
6843 /// compatible for assignment from RHS to LHS.  This handles validation of any
6844 /// protocol qualifiers on the LHS or RHS.
6845 ///
canAssignObjCInterfaces(const ObjCObjectPointerType * LHSOPT,const ObjCObjectPointerType * RHSOPT)6846 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6847                                          const ObjCObjectPointerType *RHSOPT) {
6848   const ObjCObjectType* LHS = LHSOPT->getObjectType();
6849   const ObjCObjectType* RHS = RHSOPT->getObjectType();
6850 
6851   // If either type represents the built-in 'id' or 'Class' types, return true.
6852   if (LHS->isObjCUnqualifiedIdOrClass() ||
6853       RHS->isObjCUnqualifiedIdOrClass())
6854     return true;
6855 
6856   // Function object that propagates a successful result or handles
6857   // __kindof types.
6858   auto finish = [&](bool succeeded) -> bool {
6859     if (succeeded)
6860       return true;
6861 
6862     if (!RHS->isKindOfType())
6863       return false;
6864 
6865     // Strip off __kindof and protocol qualifiers, then check whether
6866     // we can assign the other way.
6867     return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6868                                    LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6869   };
6870 
6871   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6872     return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6873                                                     QualType(RHSOPT,0),
6874                                                     false));
6875   }
6876 
6877   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6878     return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6879                                                        QualType(RHSOPT,0)));
6880   }
6881 
6882   // If we have 2 user-defined types, fall into that path.
6883   if (LHS->getInterface() && RHS->getInterface()) {
6884     return finish(canAssignObjCInterfaces(LHS, RHS));
6885   }
6886 
6887   return false;
6888 }
6889 
6890 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6891 /// for providing type-safety for objective-c pointers used to pass/return
6892 /// arguments in block literals. When passed as arguments, passing 'A*' where
6893 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6894 /// not OK. For the return type, the opposite is not OK.
canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType * LHSOPT,const ObjCObjectPointerType * RHSOPT,bool BlockReturnType)6895 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6896                                          const ObjCObjectPointerType *LHSOPT,
6897                                          const ObjCObjectPointerType *RHSOPT,
6898                                          bool BlockReturnType) {
6899 
6900   // Function object that propagates a successful result or handles
6901   // __kindof types.
6902   auto finish = [&](bool succeeded) -> bool {
6903     if (succeeded)
6904       return true;
6905 
6906     const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6907     if (!Expected->isKindOfType())
6908       return false;
6909 
6910     // Strip off __kindof and protocol qualifiers, then check whether
6911     // we can assign the other way.
6912     return canAssignObjCInterfacesInBlockPointer(
6913              RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6914              LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6915              BlockReturnType);
6916   };
6917 
6918   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
6919     return true;
6920 
6921   if (LHSOPT->isObjCBuiltinType()) {
6922     return finish(RHSOPT->isObjCBuiltinType() ||
6923                   RHSOPT->isObjCQualifiedIdType());
6924   }
6925 
6926   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
6927     return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6928                                                     QualType(RHSOPT,0),
6929                                                     false));
6930 
6931   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6932   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6933   if (LHS && RHS)  { // We have 2 user-defined types.
6934     if (LHS != RHS) {
6935       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
6936         return finish(BlockReturnType);
6937       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
6938         return finish(!BlockReturnType);
6939     }
6940     else
6941       return true;
6942   }
6943   return false;
6944 }
6945 
6946 /// Comparison routine for Objective-C protocols to be used with
6947 /// llvm::array_pod_sort.
compareObjCProtocolsByName(ObjCProtocolDecl * const * lhs,ObjCProtocolDecl * const * rhs)6948 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6949                                       ObjCProtocolDecl * const *rhs) {
6950   return (*lhs)->getName().compare((*rhs)->getName());
6951 
6952 }
6953 
6954 /// getIntersectionOfProtocols - This routine finds the intersection of set
6955 /// of protocols inherited from two distinct objective-c pointer objects with
6956 /// the given common base.
6957 /// It is used to build composite qualifier list of the composite type of
6958 /// the conditional expression involving two objective-c pointer objects.
6959 static
getIntersectionOfProtocols(ASTContext & Context,const ObjCInterfaceDecl * CommonBase,const ObjCObjectPointerType * LHSOPT,const ObjCObjectPointerType * RHSOPT,SmallVectorImpl<ObjCProtocolDecl * > & IntersectionSet)6960 void getIntersectionOfProtocols(ASTContext &Context,
6961                                 const ObjCInterfaceDecl *CommonBase,
6962                                 const ObjCObjectPointerType *LHSOPT,
6963                                 const ObjCObjectPointerType *RHSOPT,
6964       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
6965 
6966   const ObjCObjectType* LHS = LHSOPT->getObjectType();
6967   const ObjCObjectType* RHS = RHSOPT->getObjectType();
6968   assert(LHS->getInterface() && "LHS must have an interface base");
6969   assert(RHS->getInterface() && "RHS must have an interface base");
6970 
6971   // Add all of the protocols for the LHS.
6972   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6973 
6974   // Start with the protocol qualifiers.
6975   for (auto proto : LHS->quals()) {
6976     Context.CollectInheritedProtocols(proto, LHSProtocolSet);
6977   }
6978 
6979   // Also add the protocols associated with the LHS interface.
6980   Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6981 
6982   // Add all of the protocls for the RHS.
6983   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6984 
6985   // Start with the protocol qualifiers.
6986   for (auto proto : RHS->quals()) {
6987     Context.CollectInheritedProtocols(proto, RHSProtocolSet);
6988   }
6989 
6990   // Also add the protocols associated with the RHS interface.
6991   Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
6992 
6993   // Compute the intersection of the collected protocol sets.
6994   for (auto proto : LHSProtocolSet) {
6995     if (RHSProtocolSet.count(proto))
6996       IntersectionSet.push_back(proto);
6997   }
6998 
6999   // Compute the set of protocols that is implied by either the common type or
7000   // the protocols within the intersection.
7001   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7002   Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7003 
7004   // Remove any implied protocols from the list of inherited protocols.
7005   if (!ImpliedProtocols.empty()) {
7006     IntersectionSet.erase(
7007       std::remove_if(IntersectionSet.begin(),
7008                      IntersectionSet.end(),
7009                      [&](ObjCProtocolDecl *proto) -> bool {
7010                        return ImpliedProtocols.count(proto) > 0;
7011                      }),
7012       IntersectionSet.end());
7013   }
7014 
7015   // Sort the remaining protocols by name.
7016   llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7017                        compareObjCProtocolsByName);
7018 }
7019 
7020 /// Determine whether the first type is a subtype of the second.
canAssignObjCObjectTypes(ASTContext & ctx,QualType lhs,QualType rhs)7021 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7022                                      QualType rhs) {
7023   // Common case: two object pointers.
7024   const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7025   const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7026   if (lhsOPT && rhsOPT)
7027     return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7028 
7029   // Two block pointers.
7030   const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7031   const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7032   if (lhsBlock && rhsBlock)
7033     return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7034 
7035   // If either is an unqualified 'id' and the other is a block, it's
7036   // acceptable.
7037   if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7038       (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7039     return true;
7040 
7041   return false;
7042 }
7043 
7044 // Check that the given Objective-C type argument lists are equivalent.
sameObjCTypeArgs(ASTContext & ctx,const ObjCInterfaceDecl * iface,ArrayRef<QualType> lhsArgs,ArrayRef<QualType> rhsArgs,bool stripKindOf)7045 static bool sameObjCTypeArgs(ASTContext &ctx,
7046                              const ObjCInterfaceDecl *iface,
7047                              ArrayRef<QualType> lhsArgs,
7048                              ArrayRef<QualType> rhsArgs,
7049                              bool stripKindOf) {
7050   if (lhsArgs.size() != rhsArgs.size())
7051     return false;
7052 
7053   ObjCTypeParamList *typeParams = iface->getTypeParamList();
7054   for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
7055     if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7056       continue;
7057 
7058     switch (typeParams->begin()[i]->getVariance()) {
7059     case ObjCTypeParamVariance::Invariant:
7060       if (!stripKindOf ||
7061           !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7062                            rhsArgs[i].stripObjCKindOfType(ctx))) {
7063         return false;
7064       }
7065       break;
7066 
7067     case ObjCTypeParamVariance::Covariant:
7068       if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7069         return false;
7070       break;
7071 
7072     case ObjCTypeParamVariance::Contravariant:
7073       if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7074         return false;
7075       break;
7076     }
7077   }
7078 
7079   return true;
7080 }
7081 
areCommonBaseCompatible(const ObjCObjectPointerType * Lptr,const ObjCObjectPointerType * Rptr)7082 QualType ASTContext::areCommonBaseCompatible(
7083            const ObjCObjectPointerType *Lptr,
7084            const ObjCObjectPointerType *Rptr) {
7085   const ObjCObjectType *LHS = Lptr->getObjectType();
7086   const ObjCObjectType *RHS = Rptr->getObjectType();
7087   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7088   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
7089 
7090   if (!LDecl || !RDecl)
7091     return QualType();
7092 
7093   // Follow the left-hand side up the class hierarchy until we either hit a
7094   // root or find the RHS. Record the ancestors in case we don't find it.
7095   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7096     LHSAncestors;
7097   while (true) {
7098     // Record this ancestor. We'll need this if the common type isn't in the
7099     // path from the LHS to the root.
7100     LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
7101 
7102     if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7103       // Get the type arguments.
7104       ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7105       bool anyChanges = false;
7106       if (LHS->isSpecialized() && RHS->isSpecialized()) {
7107         // Both have type arguments, compare them.
7108         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7109                               LHS->getTypeArgs(), RHS->getTypeArgs(),
7110                               /*stripKindOf=*/true))
7111           return QualType();
7112       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7113         // If only one has type arguments, the result will not have type
7114         // arguments.
7115         LHSTypeArgs = { };
7116         anyChanges = true;
7117       }
7118 
7119       // Compute the intersection of protocols.
7120       SmallVector<ObjCProtocolDecl *, 8> Protocols;
7121       getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7122                                  Protocols);
7123       if (!Protocols.empty())
7124         anyChanges = true;
7125 
7126       // If anything in the LHS will have changed, build a new result type.
7127       if (anyChanges) {
7128         QualType Result = getObjCInterfaceType(LHS->getInterface());
7129         Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7130                                    LHS->isKindOfType());
7131         return getObjCObjectPointerType(Result);
7132       }
7133 
7134       return getObjCObjectPointerType(QualType(LHS, 0));
7135     }
7136 
7137     // Find the superclass.
7138     QualType LHSSuperType = LHS->getSuperClassType();
7139     if (LHSSuperType.isNull())
7140       break;
7141 
7142     LHS = LHSSuperType->castAs<ObjCObjectType>();
7143   }
7144 
7145   // We didn't find anything by following the LHS to its root; now check
7146   // the RHS against the cached set of ancestors.
7147   while (true) {
7148     auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7149     if (KnownLHS != LHSAncestors.end()) {
7150       LHS = KnownLHS->second;
7151 
7152       // Get the type arguments.
7153       ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7154       bool anyChanges = false;
7155       if (LHS->isSpecialized() && RHS->isSpecialized()) {
7156         // Both have type arguments, compare them.
7157         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7158                               LHS->getTypeArgs(), RHS->getTypeArgs(),
7159                               /*stripKindOf=*/true))
7160           return QualType();
7161       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7162         // If only one has type arguments, the result will not have type
7163         // arguments.
7164         RHSTypeArgs = { };
7165         anyChanges = true;
7166       }
7167 
7168       // Compute the intersection of protocols.
7169       SmallVector<ObjCProtocolDecl *, 8> Protocols;
7170       getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7171                                  Protocols);
7172       if (!Protocols.empty())
7173         anyChanges = true;
7174 
7175       if (anyChanges) {
7176         QualType Result = getObjCInterfaceType(RHS->getInterface());
7177         Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7178                                    RHS->isKindOfType());
7179         return getObjCObjectPointerType(Result);
7180       }
7181 
7182       return getObjCObjectPointerType(QualType(RHS, 0));
7183     }
7184 
7185     // Find the superclass of the RHS.
7186     QualType RHSSuperType = RHS->getSuperClassType();
7187     if (RHSSuperType.isNull())
7188       break;
7189 
7190     RHS = RHSSuperType->castAs<ObjCObjectType>();
7191   }
7192 
7193   return QualType();
7194 }
7195 
canAssignObjCInterfaces(const ObjCObjectType * LHS,const ObjCObjectType * RHS)7196 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7197                                          const ObjCObjectType *RHS) {
7198   assert(LHS->getInterface() && "LHS is not an interface type");
7199   assert(RHS->getInterface() && "RHS is not an interface type");
7200 
7201   // Verify that the base decls are compatible: the RHS must be a subclass of
7202   // the LHS.
7203   ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7204   bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7205   if (!IsSuperClass)
7206     return false;
7207 
7208   // If the LHS has protocol qualifiers, determine whether all of them are
7209   // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7210   // LHS).
7211   if (LHS->getNumProtocols() > 0) {
7212     // OK if conversion of LHS to SuperClass results in narrowing of types
7213     // ; i.e., SuperClass may implement at least one of the protocols
7214     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7215     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7216     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7217     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7218     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7219     // qualifiers.
7220     for (auto *RHSPI : RHS->quals())
7221       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
7222     // If there is no protocols associated with RHS, it is not a match.
7223     if (SuperClassInheritedProtocols.empty())
7224       return false;
7225 
7226     for (const auto *LHSProto : LHS->quals()) {
7227       bool SuperImplementsProtocol = false;
7228       for (auto *SuperClassProto : SuperClassInheritedProtocols)
7229         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7230           SuperImplementsProtocol = true;
7231           break;
7232         }
7233       if (!SuperImplementsProtocol)
7234         return false;
7235     }
7236   }
7237 
7238   // If the LHS is specialized, we may need to check type arguments.
7239   if (LHS->isSpecialized()) {
7240     // Follow the superclass chain until we've matched the LHS class in the
7241     // hierarchy. This substitutes type arguments through.
7242     const ObjCObjectType *RHSSuper = RHS;
7243     while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7244       RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7245 
7246     // If the RHS is specializd, compare type arguments.
7247     if (RHSSuper->isSpecialized() &&
7248         !sameObjCTypeArgs(*this, LHS->getInterface(),
7249                           LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
7250                           /*stripKindOf=*/true)) {
7251       return false;
7252     }
7253   }
7254 
7255   return true;
7256 }
7257 
areComparableObjCPointerTypes(QualType LHS,QualType RHS)7258 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7259   // get the "pointed to" types
7260   const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7261   const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
7262 
7263   if (!LHSOPT || !RHSOPT)
7264     return false;
7265 
7266   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7267          canAssignObjCInterfaces(RHSOPT, LHSOPT);
7268 }
7269 
canBindObjCObjectType(QualType To,QualType From)7270 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7271   return canAssignObjCInterfaces(
7272                 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7273                 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7274 }
7275 
7276 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
7277 /// both shall have the identically qualified version of a compatible type.
7278 /// C99 6.2.7p1: Two types have compatible types if their types are the
7279 /// same. See 6.7.[2,3,5] for additional rules.
typesAreCompatible(QualType LHS,QualType RHS,bool CompareUnqualified)7280 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7281                                     bool CompareUnqualified) {
7282   if (getLangOpts().CPlusPlus)
7283     return hasSameType(LHS, RHS);
7284 
7285   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
7286 }
7287 
propertyTypesAreCompatible(QualType LHS,QualType RHS)7288 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
7289   return typesAreCompatible(LHS, RHS);
7290 }
7291 
typesAreBlockPointerCompatible(QualType LHS,QualType RHS)7292 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7293   return !mergeTypes(LHS, RHS, true).isNull();
7294 }
7295 
7296 /// mergeTransparentUnionType - if T is a transparent union type and a member
7297 /// of T is compatible with SubType, return the merged type, else return
7298 /// QualType()
mergeTransparentUnionType(QualType T,QualType SubType,bool OfBlockPointer,bool Unqualified)7299 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7300                                                bool OfBlockPointer,
7301                                                bool Unqualified) {
7302   if (const RecordType *UT = T->getAsUnionType()) {
7303     RecordDecl *UD = UT->getDecl();
7304     if (UD->hasAttr<TransparentUnionAttr>()) {
7305       for (const auto *I : UD->fields()) {
7306         QualType ET = I->getType().getUnqualifiedType();
7307         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7308         if (!MT.isNull())
7309           return MT;
7310       }
7311     }
7312   }
7313 
7314   return QualType();
7315 }
7316 
7317 /// mergeFunctionParameterTypes - merge two types which appear as function
7318 /// parameter types
mergeFunctionParameterTypes(QualType lhs,QualType rhs,bool OfBlockPointer,bool Unqualified)7319 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7320                                                  bool OfBlockPointer,
7321                                                  bool Unqualified) {
7322   // GNU extension: two types are compatible if they appear as a function
7323   // argument, one of the types is a transparent union type and the other
7324   // type is compatible with a union member
7325   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7326                                               Unqualified);
7327   if (!lmerge.isNull())
7328     return lmerge;
7329 
7330   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7331                                               Unqualified);
7332   if (!rmerge.isNull())
7333     return rmerge;
7334 
7335   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7336 }
7337 
mergeFunctionTypes(QualType lhs,QualType rhs,bool OfBlockPointer,bool Unqualified)7338 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
7339                                         bool OfBlockPointer,
7340                                         bool Unqualified) {
7341   const FunctionType *lbase = lhs->getAs<FunctionType>();
7342   const FunctionType *rbase = rhs->getAs<FunctionType>();
7343   const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7344   const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
7345   bool allLTypes = true;
7346   bool allRTypes = true;
7347 
7348   // Check return type
7349   QualType retType;
7350   if (OfBlockPointer) {
7351     QualType RHS = rbase->getReturnType();
7352     QualType LHS = lbase->getReturnType();
7353     bool UnqualifiedResult = Unqualified;
7354     if (!UnqualifiedResult)
7355       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
7356     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
7357   }
7358   else
7359     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
7360                          Unqualified);
7361   if (retType.isNull()) return QualType();
7362 
7363   if (Unqualified)
7364     retType = retType.getUnqualifiedType();
7365 
7366   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7367   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
7368   if (Unqualified) {
7369     LRetType = LRetType.getUnqualifiedType();
7370     RRetType = RRetType.getUnqualifiedType();
7371   }
7372 
7373   if (getCanonicalType(retType) != LRetType)
7374     allLTypes = false;
7375   if (getCanonicalType(retType) != RRetType)
7376     allRTypes = false;
7377 
7378   // FIXME: double check this
7379   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7380   //                           rbase->getRegParmAttr() != 0 &&
7381   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
7382   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7383   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
7384 
7385   // Compatible functions must have compatible calling conventions
7386   if (lbaseInfo.getCC() != rbaseInfo.getCC())
7387     return QualType();
7388 
7389   // Regparm is part of the calling convention.
7390   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7391     return QualType();
7392   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7393     return QualType();
7394 
7395   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7396     return QualType();
7397 
7398   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7399   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
7400 
7401   if (lbaseInfo.getNoReturn() != NoReturn)
7402     allLTypes = false;
7403   if (rbaseInfo.getNoReturn() != NoReturn)
7404     allRTypes = false;
7405 
7406   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
7407 
7408   if (lproto && rproto) { // two C99 style function prototypes
7409     assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7410            "C++ shouldn't be here");
7411     // Compatible functions must have the same number of parameters
7412     if (lproto->getNumParams() != rproto->getNumParams())
7413       return QualType();
7414 
7415     // Variadic and non-variadic functions aren't compatible
7416     if (lproto->isVariadic() != rproto->isVariadic())
7417       return QualType();
7418 
7419     if (lproto->getTypeQuals() != rproto->getTypeQuals())
7420       return QualType();
7421 
7422     if (LangOpts.ObjCAutoRefCount &&
7423         !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7424       return QualType();
7425 
7426     // Check parameter type compatibility
7427     SmallVector<QualType, 10> types;
7428     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7429       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7430       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7431       QualType paramType = mergeFunctionParameterTypes(
7432           lParamType, rParamType, OfBlockPointer, Unqualified);
7433       if (paramType.isNull())
7434         return QualType();
7435 
7436       if (Unqualified)
7437         paramType = paramType.getUnqualifiedType();
7438 
7439       types.push_back(paramType);
7440       if (Unqualified) {
7441         lParamType = lParamType.getUnqualifiedType();
7442         rParamType = rParamType.getUnqualifiedType();
7443       }
7444 
7445       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
7446         allLTypes = false;
7447       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
7448         allRTypes = false;
7449     }
7450 
7451     if (allLTypes) return lhs;
7452     if (allRTypes) return rhs;
7453 
7454     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7455     EPI.ExtInfo = einfo;
7456     return getFunctionType(retType, types, EPI);
7457   }
7458 
7459   if (lproto) allRTypes = false;
7460   if (rproto) allLTypes = false;
7461 
7462   const FunctionProtoType *proto = lproto ? lproto : rproto;
7463   if (proto) {
7464     assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7465     if (proto->isVariadic()) return QualType();
7466     // Check that the types are compatible with the types that
7467     // would result from default argument promotions (C99 6.7.5.3p15).
7468     // The only types actually affected are promotable integer
7469     // types and floats, which would be passed as a different
7470     // type depending on whether the prototype is visible.
7471     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7472       QualType paramTy = proto->getParamType(i);
7473 
7474       // Look at the converted type of enum types, since that is the type used
7475       // to pass enum values.
7476       if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7477         paramTy = Enum->getDecl()->getIntegerType();
7478         if (paramTy.isNull())
7479           return QualType();
7480       }
7481 
7482       if (paramTy->isPromotableIntegerType() ||
7483           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
7484         return QualType();
7485     }
7486 
7487     if (allLTypes) return lhs;
7488     if (allRTypes) return rhs;
7489 
7490     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7491     EPI.ExtInfo = einfo;
7492     return getFunctionType(retType, proto->getParamTypes(), EPI);
7493   }
7494 
7495   if (allLTypes) return lhs;
7496   if (allRTypes) return rhs;
7497   return getFunctionNoProtoType(retType, einfo);
7498 }
7499 
7500 /// Given that we have an enum type and a non-enum type, try to merge them.
mergeEnumWithInteger(ASTContext & Context,const EnumType * ET,QualType other,bool isBlockReturnType)7501 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7502                                      QualType other, bool isBlockReturnType) {
7503   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7504   // a signed integer type, or an unsigned integer type.
7505   // Compatibility is based on the underlying type, not the promotion
7506   // type.
7507   QualType underlyingType = ET->getDecl()->getIntegerType();
7508   if (underlyingType.isNull()) return QualType();
7509   if (Context.hasSameType(underlyingType, other))
7510     return other;
7511 
7512   // In block return types, we're more permissive and accept any
7513   // integral type of the same size.
7514   if (isBlockReturnType && other->isIntegerType() &&
7515       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7516     return other;
7517 
7518   return QualType();
7519 }
7520 
mergeTypes(QualType LHS,QualType RHS,bool OfBlockPointer,bool Unqualified,bool BlockReturnType)7521 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
7522                                 bool OfBlockPointer,
7523                                 bool Unqualified, bool BlockReturnType) {
7524   // C++ [expr]: If an expression initially has the type "reference to T", the
7525   // type is adjusted to "T" prior to any further analysis, the expression
7526   // designates the object or function denoted by the reference, and the
7527   // expression is an lvalue unless the reference is an rvalue reference and
7528   // the expression is a function call (possibly inside parentheses).
7529   assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7530   assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
7531 
7532   if (Unqualified) {
7533     LHS = LHS.getUnqualifiedType();
7534     RHS = RHS.getUnqualifiedType();
7535   }
7536 
7537   QualType LHSCan = getCanonicalType(LHS),
7538            RHSCan = getCanonicalType(RHS);
7539 
7540   // If two types are identical, they are compatible.
7541   if (LHSCan == RHSCan)
7542     return LHS;
7543 
7544   // If the qualifiers are different, the types aren't compatible... mostly.
7545   Qualifiers LQuals = LHSCan.getLocalQualifiers();
7546   Qualifiers RQuals = RHSCan.getLocalQualifiers();
7547   if (LQuals != RQuals) {
7548     // If any of these qualifiers are different, we have a type
7549     // mismatch.
7550     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7551         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7552         LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
7553       return QualType();
7554 
7555     // Exactly one GC qualifier difference is allowed: __strong is
7556     // okay if the other type has no GC qualifier but is an Objective
7557     // C object pointer (i.e. implicitly strong by default).  We fix
7558     // this by pretending that the unqualified type was actually
7559     // qualified __strong.
7560     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7561     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7562     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7563 
7564     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7565       return QualType();
7566 
7567     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7568       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7569     }
7570     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7571       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7572     }
7573     return QualType();
7574   }
7575 
7576   // Okay, qualifiers are equal.
7577 
7578   Type::TypeClass LHSClass = LHSCan->getTypeClass();
7579   Type::TypeClass RHSClass = RHSCan->getTypeClass();
7580 
7581   // We want to consider the two function types to be the same for these
7582   // comparisons, just force one to the other.
7583   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7584   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
7585 
7586   // Same as above for arrays
7587   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7588     LHSClass = Type::ConstantArray;
7589   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7590     RHSClass = Type::ConstantArray;
7591 
7592   // ObjCInterfaces are just specialized ObjCObjects.
7593   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7594   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7595 
7596   // Canonicalize ExtVector -> Vector.
7597   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7598   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
7599 
7600   // If the canonical type classes don't match.
7601   if (LHSClass != RHSClass) {
7602     // Note that we only have special rules for turning block enum
7603     // returns into block int returns, not vice-versa.
7604     if (const EnumType* ETy = LHS->getAs<EnumType>()) {
7605       return mergeEnumWithInteger(*this, ETy, RHS, false);
7606     }
7607     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
7608       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
7609     }
7610     // allow block pointer type to match an 'id' type.
7611     if (OfBlockPointer && !BlockReturnType) {
7612        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7613          return LHS;
7614       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7615         return RHS;
7616     }
7617 
7618     return QualType();
7619   }
7620 
7621   // The canonical type classes match.
7622   switch (LHSClass) {
7623 #define TYPE(Class, Base)
7624 #define ABSTRACT_TYPE(Class, Base)
7625 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
7626 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7627 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
7628 #include "clang/AST/TypeNodes.def"
7629     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
7630 
7631   case Type::Auto:
7632   case Type::LValueReference:
7633   case Type::RValueReference:
7634   case Type::MemberPointer:
7635     llvm_unreachable("C++ should never be in mergeTypes");
7636 
7637   case Type::ObjCInterface:
7638   case Type::IncompleteArray:
7639   case Type::VariableArray:
7640   case Type::FunctionProto:
7641   case Type::ExtVector:
7642     llvm_unreachable("Types are eliminated above");
7643 
7644   case Type::Pointer:
7645   {
7646     // Merge two pointer types, while trying to preserve typedef info
7647     QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7648     QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
7649     if (Unqualified) {
7650       LHSPointee = LHSPointee.getUnqualifiedType();
7651       RHSPointee = RHSPointee.getUnqualifiedType();
7652     }
7653     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7654                                      Unqualified);
7655     if (ResultType.isNull()) return QualType();
7656     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7657       return LHS;
7658     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7659       return RHS;
7660     return getPointerType(ResultType);
7661   }
7662   case Type::BlockPointer:
7663   {
7664     // Merge two block pointer types, while trying to preserve typedef info
7665     QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7666     QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7667     if (Unqualified) {
7668       LHSPointee = LHSPointee.getUnqualifiedType();
7669       RHSPointee = RHSPointee.getUnqualifiedType();
7670     }
7671     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7672                                      Unqualified);
7673     if (ResultType.isNull()) return QualType();
7674     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7675       return LHS;
7676     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7677       return RHS;
7678     return getBlockPointerType(ResultType);
7679   }
7680   case Type::Atomic:
7681   {
7682     // Merge two pointer types, while trying to preserve typedef info
7683     QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7684     QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7685     if (Unqualified) {
7686       LHSValue = LHSValue.getUnqualifiedType();
7687       RHSValue = RHSValue.getUnqualifiedType();
7688     }
7689     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7690                                      Unqualified);
7691     if (ResultType.isNull()) return QualType();
7692     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7693       return LHS;
7694     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7695       return RHS;
7696     return getAtomicType(ResultType);
7697   }
7698   case Type::ConstantArray:
7699   {
7700     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7701     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7702     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7703       return QualType();
7704 
7705     QualType LHSElem = getAsArrayType(LHS)->getElementType();
7706     QualType RHSElem = getAsArrayType(RHS)->getElementType();
7707     if (Unqualified) {
7708       LHSElem = LHSElem.getUnqualifiedType();
7709       RHSElem = RHSElem.getUnqualifiedType();
7710     }
7711 
7712     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7713     if (ResultType.isNull()) return QualType();
7714     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7715       return LHS;
7716     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7717       return RHS;
7718     if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7719                                           ArrayType::ArraySizeModifier(), 0);
7720     if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7721                                           ArrayType::ArraySizeModifier(), 0);
7722     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7723     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7724     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7725       return LHS;
7726     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7727       return RHS;
7728     if (LVAT) {
7729       // FIXME: This isn't correct! But tricky to implement because
7730       // the array's size has to be the size of LHS, but the type
7731       // has to be different.
7732       return LHS;
7733     }
7734     if (RVAT) {
7735       // FIXME: This isn't correct! But tricky to implement because
7736       // the array's size has to be the size of RHS, but the type
7737       // has to be different.
7738       return RHS;
7739     }
7740     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7741     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7742     return getIncompleteArrayType(ResultType,
7743                                   ArrayType::ArraySizeModifier(), 0);
7744   }
7745   case Type::FunctionNoProto:
7746     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7747   case Type::Record:
7748   case Type::Enum:
7749     return QualType();
7750   case Type::Builtin:
7751     // Only exactly equal builtin types are compatible, which is tested above.
7752     return QualType();
7753   case Type::Complex:
7754     // Distinct complex types are incompatible.
7755     return QualType();
7756   case Type::Vector:
7757     // FIXME: The merged type should be an ExtVector!
7758     if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7759                              RHSCan->getAs<VectorType>()))
7760       return LHS;
7761     return QualType();
7762   case Type::ObjCObject: {
7763     // Check if the types are assignment compatible.
7764     // FIXME: This should be type compatibility, e.g. whether
7765     // "LHS x; RHS x;" at global scope is legal.
7766     const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7767     const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7768     if (canAssignObjCInterfaces(LHSIface, RHSIface))
7769       return LHS;
7770 
7771     return QualType();
7772   }
7773   case Type::ObjCObjectPointer: {
7774     if (OfBlockPointer) {
7775       if (canAssignObjCInterfacesInBlockPointer(
7776                                           LHS->getAs<ObjCObjectPointerType>(),
7777                                           RHS->getAs<ObjCObjectPointerType>(),
7778                                           BlockReturnType))
7779         return LHS;
7780       return QualType();
7781     }
7782     if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7783                                 RHS->getAs<ObjCObjectPointerType>()))
7784       return LHS;
7785 
7786     return QualType();
7787   }
7788   }
7789 
7790   llvm_unreachable("Invalid Type::Class!");
7791 }
7792 
FunctionTypesMatchOnNSConsumedAttrs(const FunctionProtoType * FromFunctionType,const FunctionProtoType * ToFunctionType)7793 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7794                    const FunctionProtoType *FromFunctionType,
7795                    const FunctionProtoType *ToFunctionType) {
7796   if (FromFunctionType->hasAnyConsumedParams() !=
7797       ToFunctionType->hasAnyConsumedParams())
7798     return false;
7799   FunctionProtoType::ExtProtoInfo FromEPI =
7800     FromFunctionType->getExtProtoInfo();
7801   FunctionProtoType::ExtProtoInfo ToEPI =
7802     ToFunctionType->getExtProtoInfo();
7803   if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
7804     for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7805       if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
7806         return false;
7807     }
7808   return true;
7809 }
7810 
7811 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7812 /// 'RHS' attributes and returns the merged version; including for function
7813 /// return types.
mergeObjCGCQualifiers(QualType LHS,QualType RHS)7814 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7815   QualType LHSCan = getCanonicalType(LHS),
7816   RHSCan = getCanonicalType(RHS);
7817   // If two types are identical, they are compatible.
7818   if (LHSCan == RHSCan)
7819     return LHS;
7820   if (RHSCan->isFunctionType()) {
7821     if (!LHSCan->isFunctionType())
7822       return QualType();
7823     QualType OldReturnType =
7824         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
7825     QualType NewReturnType =
7826         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
7827     QualType ResReturnType =
7828       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7829     if (ResReturnType.isNull())
7830       return QualType();
7831     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7832       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7833       // In either case, use OldReturnType to build the new function type.
7834       const FunctionType *F = LHS->getAs<FunctionType>();
7835       if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7836         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7837         EPI.ExtInfo = getFunctionExtInfo(LHS);
7838         QualType ResultType =
7839             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
7840         return ResultType;
7841       }
7842     }
7843     return QualType();
7844   }
7845 
7846   // If the qualifiers are different, the types can still be merged.
7847   Qualifiers LQuals = LHSCan.getLocalQualifiers();
7848   Qualifiers RQuals = RHSCan.getLocalQualifiers();
7849   if (LQuals != RQuals) {
7850     // If any of these qualifiers are different, we have a type mismatch.
7851     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7852         LQuals.getAddressSpace() != RQuals.getAddressSpace())
7853       return QualType();
7854 
7855     // Exactly one GC qualifier difference is allowed: __strong is
7856     // okay if the other type has no GC qualifier but is an Objective
7857     // C object pointer (i.e. implicitly strong by default).  We fix
7858     // this by pretending that the unqualified type was actually
7859     // qualified __strong.
7860     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7861     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7862     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7863 
7864     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7865       return QualType();
7866 
7867     if (GC_L == Qualifiers::Strong)
7868       return LHS;
7869     if (GC_R == Qualifiers::Strong)
7870       return RHS;
7871     return QualType();
7872   }
7873 
7874   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7875     QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7876     QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7877     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7878     if (ResQT == LHSBaseQT)
7879       return LHS;
7880     if (ResQT == RHSBaseQT)
7881       return RHS;
7882   }
7883   return QualType();
7884 }
7885 
7886 //===----------------------------------------------------------------------===//
7887 //                         Integer Predicates
7888 //===----------------------------------------------------------------------===//
7889 
getIntWidth(QualType T) const7890 unsigned ASTContext::getIntWidth(QualType T) const {
7891   if (const EnumType *ET = T->getAs<EnumType>())
7892     T = ET->getDecl()->getIntegerType();
7893   if (T->isBooleanType())
7894     return 1;
7895   // For builtin types, just use the standard type sizing method
7896   return (unsigned)getTypeSize(T);
7897 }
7898 
getCorrespondingUnsignedType(QualType T) const7899 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
7900   assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
7901 
7902   // Turn <4 x signed int> -> <4 x unsigned int>
7903   if (const VectorType *VTy = T->getAs<VectorType>())
7904     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
7905                          VTy->getNumElements(), VTy->getVectorKind());
7906 
7907   // For enums, we return the unsigned version of the base type.
7908   if (const EnumType *ETy = T->getAs<EnumType>())
7909     T = ETy->getDecl()->getIntegerType();
7910 
7911   const BuiltinType *BTy = T->getAs<BuiltinType>();
7912   assert(BTy && "Unexpected signed integer type");
7913   switch (BTy->getKind()) {
7914   case BuiltinType::Char_S:
7915   case BuiltinType::SChar:
7916     return UnsignedCharTy;
7917   case BuiltinType::Short:
7918     return UnsignedShortTy;
7919   case BuiltinType::Int:
7920     return UnsignedIntTy;
7921   case BuiltinType::Long:
7922     return UnsignedLongTy;
7923   case BuiltinType::LongLong:
7924     return UnsignedLongLongTy;
7925   case BuiltinType::Int128:
7926     return UnsignedInt128Ty;
7927   default:
7928     llvm_unreachable("Unexpected signed integer type");
7929   }
7930 }
7931 
~ASTMutationListener()7932 ASTMutationListener::~ASTMutationListener() { }
7933 
DeducedReturnType(const FunctionDecl * FD,QualType ReturnType)7934 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7935                                             QualType ReturnType) {}
7936 
7937 //===----------------------------------------------------------------------===//
7938 //                          Builtin Type Computation
7939 //===----------------------------------------------------------------------===//
7940 
7941 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
7942 /// pointer over the consumed characters.  This returns the resultant type.  If
7943 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7944 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
7945 /// a vector of "i*".
7946 ///
7947 /// RequiresICE is filled in on return to indicate whether the value is required
7948 /// to be an Integer Constant Expression.
DecodeTypeFromStr(const char * & Str,const ASTContext & Context,ASTContext::GetBuiltinTypeError & Error,bool & RequiresICE,bool AllowTypeModifiers)7949 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
7950                                   ASTContext::GetBuiltinTypeError &Error,
7951                                   bool &RequiresICE,
7952                                   bool AllowTypeModifiers) {
7953   // Modifiers.
7954   int HowLong = 0;
7955   bool Signed = false, Unsigned = false;
7956   RequiresICE = false;
7957 
7958   // Read the prefixed modifiers first.
7959   bool Done = false;
7960   while (!Done) {
7961     switch (*Str++) {
7962     default: Done = true; --Str; break;
7963     case 'I':
7964       RequiresICE = true;
7965       break;
7966     case 'S':
7967       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7968       assert(!Signed && "Can't use 'S' modifier multiple times!");
7969       Signed = true;
7970       break;
7971     case 'U':
7972       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7973       assert(!Unsigned && "Can't use 'U' modifier multiple times!");
7974       Unsigned = true;
7975       break;
7976     case 'L':
7977       assert(HowLong <= 2 && "Can't have LLLL modifier");
7978       ++HowLong;
7979       break;
7980     case 'W':
7981       // This modifier represents int64 type.
7982       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7983       switch (Context.getTargetInfo().getInt64Type()) {
7984       default:
7985         llvm_unreachable("Unexpected integer type");
7986       case TargetInfo::SignedLong:
7987         HowLong = 1;
7988         break;
7989       case TargetInfo::SignedLongLong:
7990         HowLong = 2;
7991         break;
7992       }
7993     }
7994   }
7995 
7996   QualType Type;
7997 
7998   // Read the base type.
7999   switch (*Str++) {
8000   default: llvm_unreachable("Unknown builtin type letter!");
8001   case 'v':
8002     assert(HowLong == 0 && !Signed && !Unsigned &&
8003            "Bad modifiers used with 'v'!");
8004     Type = Context.VoidTy;
8005     break;
8006   case 'h':
8007     assert(HowLong == 0 && !Signed && !Unsigned &&
8008            "Bad modifiers used with 'h'!");
8009     Type = Context.HalfTy;
8010     break;
8011   case 'f':
8012     assert(HowLong == 0 && !Signed && !Unsigned &&
8013            "Bad modifiers used with 'f'!");
8014     Type = Context.FloatTy;
8015     break;
8016   case 'd':
8017     assert(HowLong < 2 && !Signed && !Unsigned &&
8018            "Bad modifiers used with 'd'!");
8019     if (HowLong)
8020       Type = Context.LongDoubleTy;
8021     else
8022       Type = Context.DoubleTy;
8023     break;
8024   case 's':
8025     assert(HowLong == 0 && "Bad modifiers used with 's'!");
8026     if (Unsigned)
8027       Type = Context.UnsignedShortTy;
8028     else
8029       Type = Context.ShortTy;
8030     break;
8031   case 'i':
8032     if (HowLong == 3)
8033       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8034     else if (HowLong == 2)
8035       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8036     else if (HowLong == 1)
8037       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8038     else
8039       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8040     break;
8041   case 'c':
8042     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8043     if (Signed)
8044       Type = Context.SignedCharTy;
8045     else if (Unsigned)
8046       Type = Context.UnsignedCharTy;
8047     else
8048       Type = Context.CharTy;
8049     break;
8050   case 'b': // boolean
8051     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8052     Type = Context.BoolTy;
8053     break;
8054   case 'z':  // size_t.
8055     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8056     Type = Context.getSizeType();
8057     break;
8058   case 'F':
8059     Type = Context.getCFConstantStringType();
8060     break;
8061   case 'G':
8062     Type = Context.getObjCIdType();
8063     break;
8064   case 'H':
8065     Type = Context.getObjCSelType();
8066     break;
8067   case 'M':
8068     Type = Context.getObjCSuperType();
8069     break;
8070   case 'a':
8071     Type = Context.getBuiltinVaListType();
8072     assert(!Type.isNull() && "builtin va list type not initialized!");
8073     break;
8074   case 'A':
8075     // This is a "reference" to a va_list; however, what exactly
8076     // this means depends on how va_list is defined. There are two
8077     // different kinds of va_list: ones passed by value, and ones
8078     // passed by reference.  An example of a by-value va_list is
8079     // x86, where va_list is a char*. An example of by-ref va_list
8080     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8081     // we want this argument to be a char*&; for x86-64, we want
8082     // it to be a __va_list_tag*.
8083     Type = Context.getBuiltinVaListType();
8084     assert(!Type.isNull() && "builtin va list type not initialized!");
8085     if (Type->isArrayType())
8086       Type = Context.getArrayDecayedType(Type);
8087     else
8088       Type = Context.getLValueReferenceType(Type);
8089     break;
8090   case 'V': {
8091     char *End;
8092     unsigned NumElements = strtoul(Str, &End, 10);
8093     assert(End != Str && "Missing vector size");
8094     Str = End;
8095 
8096     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8097                                              RequiresICE, false);
8098     assert(!RequiresICE && "Can't require vector ICE");
8099 
8100     // TODO: No way to make AltiVec vectors in builtins yet.
8101     Type = Context.getVectorType(ElementType, NumElements,
8102                                  VectorType::GenericVector);
8103     break;
8104   }
8105   case 'E': {
8106     char *End;
8107 
8108     unsigned NumElements = strtoul(Str, &End, 10);
8109     assert(End != Str && "Missing vector size");
8110 
8111     Str = End;
8112 
8113     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8114                                              false);
8115     Type = Context.getExtVectorType(ElementType, NumElements);
8116     break;
8117   }
8118   case 'X': {
8119     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8120                                              false);
8121     assert(!RequiresICE && "Can't require complex ICE");
8122     Type = Context.getComplexType(ElementType);
8123     break;
8124   }
8125   case 'Y' : {
8126     Type = Context.getPointerDiffType();
8127     break;
8128   }
8129   case 'P':
8130     Type = Context.getFILEType();
8131     if (Type.isNull()) {
8132       Error = ASTContext::GE_Missing_stdio;
8133       return QualType();
8134     }
8135     break;
8136   case 'J':
8137     if (Signed)
8138       Type = Context.getsigjmp_bufType();
8139     else
8140       Type = Context.getjmp_bufType();
8141 
8142     if (Type.isNull()) {
8143       Error = ASTContext::GE_Missing_setjmp;
8144       return QualType();
8145     }
8146     break;
8147   case 'K':
8148     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8149     Type = Context.getucontext_tType();
8150 
8151     if (Type.isNull()) {
8152       Error = ASTContext::GE_Missing_ucontext;
8153       return QualType();
8154     }
8155     break;
8156   case 'p':
8157     Type = Context.getProcessIDType();
8158     break;
8159   }
8160 
8161   // If there are modifiers and if we're allowed to parse them, go for it.
8162   Done = !AllowTypeModifiers;
8163   while (!Done) {
8164     switch (char c = *Str++) {
8165     default: Done = true; --Str; break;
8166     case '*':
8167     case '&': {
8168       // Both pointers and references can have their pointee types
8169       // qualified with an address space.
8170       char *End;
8171       unsigned AddrSpace = strtoul(Str, &End, 10);
8172       if (End != Str && AddrSpace != 0) {
8173         Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8174         Str = End;
8175       }
8176       if (c == '*')
8177         Type = Context.getPointerType(Type);
8178       else
8179         Type = Context.getLValueReferenceType(Type);
8180       break;
8181     }
8182     // FIXME: There's no way to have a built-in with an rvalue ref arg.
8183     case 'C':
8184       Type = Type.withConst();
8185       break;
8186     case 'D':
8187       Type = Context.getVolatileType(Type);
8188       break;
8189     case 'R':
8190       Type = Type.withRestrict();
8191       break;
8192     }
8193   }
8194 
8195   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
8196          "Integer constant 'I' type must be an integer");
8197 
8198   return Type;
8199 }
8200 
8201 /// GetBuiltinType - Return the type for the specified builtin.
GetBuiltinType(unsigned Id,GetBuiltinTypeError & Error,unsigned * IntegerConstantArgs) const8202 QualType ASTContext::GetBuiltinType(unsigned Id,
8203                                     GetBuiltinTypeError &Error,
8204                                     unsigned *IntegerConstantArgs) const {
8205   const char *TypeStr = BuiltinInfo.getTypeString(Id);
8206 
8207   SmallVector<QualType, 8> ArgTypes;
8208 
8209   bool RequiresICE = false;
8210   Error = GE_None;
8211   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8212                                        RequiresICE, true);
8213   if (Error != GE_None)
8214     return QualType();
8215 
8216   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8217 
8218   while (TypeStr[0] && TypeStr[0] != '.') {
8219     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
8220     if (Error != GE_None)
8221       return QualType();
8222 
8223     // If this argument is required to be an IntegerConstantExpression and the
8224     // caller cares, fill in the bitmask we return.
8225     if (RequiresICE && IntegerConstantArgs)
8226       *IntegerConstantArgs |= 1 << ArgTypes.size();
8227 
8228     // Do array -> pointer decay.  The builtin should use the decayed type.
8229     if (Ty->isArrayType())
8230       Ty = getArrayDecayedType(Ty);
8231 
8232     ArgTypes.push_back(Ty);
8233   }
8234 
8235   if (Id == Builtin::BI__GetExceptionInfo)
8236     return QualType();
8237 
8238   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8239          "'.' should only occur at end of builtin type list!");
8240 
8241   FunctionType::ExtInfo EI(CC_C);
8242   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8243 
8244   bool Variadic = (TypeStr[0] == '.');
8245 
8246   // We really shouldn't be making a no-proto type here, especially in C++.
8247   if (ArgTypes.empty() && Variadic)
8248     return getFunctionNoProtoType(ResType, EI);
8249 
8250   FunctionProtoType::ExtProtoInfo EPI;
8251   EPI.ExtInfo = EI;
8252   EPI.Variadic = Variadic;
8253 
8254   return getFunctionType(ResType, ArgTypes, EPI);
8255 }
8256 
basicGVALinkageForFunction(const ASTContext & Context,const FunctionDecl * FD)8257 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8258                                              const FunctionDecl *FD) {
8259   if (!FD->isExternallyVisible())
8260     return GVA_Internal;
8261 
8262   GVALinkage External = GVA_StrongExternal;
8263   switch (FD->getTemplateSpecializationKind()) {
8264   case TSK_Undeclared:
8265   case TSK_ExplicitSpecialization:
8266     External = GVA_StrongExternal;
8267     break;
8268 
8269   case TSK_ExplicitInstantiationDefinition:
8270     return GVA_StrongODR;
8271 
8272   // C++11 [temp.explicit]p10:
8273   //   [ Note: The intent is that an inline function that is the subject of
8274   //   an explicit instantiation declaration will still be implicitly
8275   //   instantiated when used so that the body can be considered for
8276   //   inlining, but that no out-of-line copy of the inline function would be
8277   //   generated in the translation unit. -- end note ]
8278   case TSK_ExplicitInstantiationDeclaration:
8279     return GVA_AvailableExternally;
8280 
8281   case TSK_ImplicitInstantiation:
8282     External = GVA_DiscardableODR;
8283     break;
8284   }
8285 
8286   if (!FD->isInlined())
8287     return External;
8288 
8289   if ((!Context.getLangOpts().CPlusPlus &&
8290        !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8291        !FD->hasAttr<DLLExportAttr>()) ||
8292       FD->hasAttr<GNUInlineAttr>()) {
8293     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8294 
8295     // GNU or C99 inline semantics. Determine whether this symbol should be
8296     // externally visible.
8297     if (FD->isInlineDefinitionExternallyVisible())
8298       return External;
8299 
8300     // C99 inline semantics, where the symbol is not externally visible.
8301     return GVA_AvailableExternally;
8302   }
8303 
8304   // Functions specified with extern and inline in -fms-compatibility mode
8305   // forcibly get emitted.  While the body of the function cannot be later
8306   // replaced, the function definition cannot be discarded.
8307   if (FD->isMSExternInline())
8308     return GVA_StrongODR;
8309 
8310   return GVA_DiscardableODR;
8311 }
8312 
adjustGVALinkageForAttributes(GVALinkage L,const Decl * D)8313 static GVALinkage adjustGVALinkageForAttributes(GVALinkage L, const Decl *D) {
8314   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8315   // dllexport/dllimport on inline functions.
8316   if (D->hasAttr<DLLImportAttr>()) {
8317     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8318       return GVA_AvailableExternally;
8319   } else if (D->hasAttr<DLLExportAttr>() || D->hasAttr<CUDAGlobalAttr>()) {
8320     if (L == GVA_DiscardableODR)
8321       return GVA_StrongODR;
8322   }
8323   return L;
8324 }
8325 
GetGVALinkageForFunction(const FunctionDecl * FD) const8326 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8327   return adjustGVALinkageForAttributes(basicGVALinkageForFunction(*this, FD),
8328                                        FD);
8329 }
8330 
basicGVALinkageForVariable(const ASTContext & Context,const VarDecl * VD)8331 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8332                                              const VarDecl *VD) {
8333   if (!VD->isExternallyVisible())
8334     return GVA_Internal;
8335 
8336   if (VD->isStaticLocal()) {
8337     GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8338     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8339     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8340       LexicalContext = LexicalContext->getLexicalParent();
8341 
8342     // Let the static local variable inherit its linkage from the nearest
8343     // enclosing function.
8344     if (LexicalContext)
8345       StaticLocalLinkage =
8346           Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8347 
8348     // GVA_StrongODR function linkage is stronger than what we need,
8349     // downgrade to GVA_DiscardableODR.
8350     // This allows us to discard the variable if we never end up needing it.
8351     return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8352                                                : StaticLocalLinkage;
8353   }
8354 
8355   // MSVC treats in-class initialized static data members as definitions.
8356   // By giving them non-strong linkage, out-of-line definitions won't
8357   // cause link errors.
8358   if (Context.isMSStaticDataMemberInlineDefinition(VD))
8359     return GVA_DiscardableODR;
8360 
8361   switch (VD->getTemplateSpecializationKind()) {
8362   case TSK_Undeclared:
8363     return GVA_StrongExternal;
8364 
8365   case TSK_ExplicitSpecialization:
8366     return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8367                    VD->isStaticDataMember()
8368                ? GVA_StrongODR
8369                : GVA_StrongExternal;
8370 
8371   case TSK_ExplicitInstantiationDefinition:
8372     return GVA_StrongODR;
8373 
8374   case TSK_ExplicitInstantiationDeclaration:
8375     return GVA_AvailableExternally;
8376 
8377   case TSK_ImplicitInstantiation:
8378     return GVA_DiscardableODR;
8379   }
8380 
8381   llvm_unreachable("Invalid Linkage!");
8382 }
8383 
GetGVALinkageForVariable(const VarDecl * VD)8384 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8385   return adjustGVALinkageForAttributes(basicGVALinkageForVariable(*this, VD),
8386                                        VD);
8387 }
8388 
DeclMustBeEmitted(const Decl * D)8389 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
8390   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8391     if (!VD->isFileVarDecl())
8392       return false;
8393     // Global named register variables (GNU extension) are never emitted.
8394     if (VD->getStorageClass() == SC_Register)
8395       return false;
8396     if (VD->getDescribedVarTemplate() ||
8397         isa<VarTemplatePartialSpecializationDecl>(VD))
8398       return false;
8399   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8400     // We never need to emit an uninstantiated function template.
8401     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8402       return false;
8403   } else if (isa<OMPThreadPrivateDecl>(D))
8404     return true;
8405   else
8406     return false;
8407 
8408   // If this is a member of a class template, we do not need to emit it.
8409   if (D->getDeclContext()->isDependentContext())
8410     return false;
8411 
8412   // Weak references don't produce any output by themselves.
8413   if (D->hasAttr<WeakRefAttr>())
8414     return false;
8415 
8416   // Aliases and used decls are required.
8417   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8418     return true;
8419 
8420   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8421     // Forward declarations aren't required.
8422     if (!FD->doesThisDeclarationHaveABody())
8423       return FD->doesDeclarationForceExternallyVisibleDefinition();
8424 
8425     // Constructors and destructors are required.
8426     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8427       return true;
8428 
8429     // The key function for a class is required.  This rule only comes
8430     // into play when inline functions can be key functions, though.
8431     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8432       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8433         const CXXRecordDecl *RD = MD->getParent();
8434         if (MD->isOutOfLine() && RD->isDynamicClass()) {
8435           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8436           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8437             return true;
8438         }
8439       }
8440     }
8441 
8442     GVALinkage Linkage = GetGVALinkageForFunction(FD);
8443 
8444     // static, static inline, always_inline, and extern inline functions can
8445     // always be deferred.  Normal inline functions can be deferred in C99/C++.
8446     // Implicit template instantiations can also be deferred in C++.
8447     if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8448         Linkage == GVA_DiscardableODR)
8449       return false;
8450     return true;
8451   }
8452 
8453   const VarDecl *VD = cast<VarDecl>(D);
8454   assert(VD->isFileVarDecl() && "Expected file scoped var");
8455 
8456   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8457       !isMSStaticDataMemberInlineDefinition(VD))
8458     return false;
8459 
8460   // Variables that can be needed in other TUs are required.
8461   GVALinkage L = GetGVALinkageForVariable(VD);
8462   if (L != GVA_Internal && L != GVA_AvailableExternally &&
8463       L != GVA_DiscardableODR)
8464     return true;
8465 
8466   // Variables that have destruction with side-effects are required.
8467   if (VD->getType().isDestructedType())
8468     return true;
8469 
8470   // Variables that have initialization with side-effects are required.
8471   if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
8472       !VD->evaluateValue())
8473     return true;
8474 
8475   return false;
8476 }
8477 
getDefaultCallingConvention(bool IsVariadic,bool IsCXXMethod) const8478 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8479                                                     bool IsCXXMethod) const {
8480   // Pass through to the C++ ABI object
8481   if (IsCXXMethod)
8482     return ABI->getDefaultMethodCallConv(IsVariadic);
8483 
8484   if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8485 
8486   return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
8487 }
8488 
isNearlyEmpty(const CXXRecordDecl * RD) const8489 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
8490   // Pass through to the C++ ABI object
8491   return ABI->isNearlyEmpty(RD);
8492 }
8493 
getVTableContext()8494 VTableContextBase *ASTContext::getVTableContext() {
8495   if (!VTContext.get()) {
8496     if (Target->getCXXABI().isMicrosoft())
8497       VTContext.reset(new MicrosoftVTableContext(*this));
8498     else
8499       VTContext.reset(new ItaniumVTableContext(*this));
8500   }
8501   return VTContext.get();
8502 }
8503 
createMangleContext()8504 MangleContext *ASTContext::createMangleContext() {
8505   switch (Target->getCXXABI().getKind()) {
8506   case TargetCXXABI::GenericAArch64:
8507   case TargetCXXABI::GenericItanium:
8508   case TargetCXXABI::GenericARM:
8509   case TargetCXXABI::GenericMIPS:
8510   case TargetCXXABI::iOS:
8511   case TargetCXXABI::iOS64:
8512   case TargetCXXABI::WebAssembly:
8513   case TargetCXXABI::WatchOS:
8514     return ItaniumMangleContext::create(*this, getDiagnostics());
8515   case TargetCXXABI::Microsoft:
8516     return MicrosoftMangleContext::create(*this, getDiagnostics());
8517   }
8518   llvm_unreachable("Unsupported ABI");
8519 }
8520 
~CXXABI()8521 CXXABI::~CXXABI() {}
8522 
getSideTableAllocatedMemory() const8523 size_t ASTContext::getSideTableAllocatedMemory() const {
8524   return ASTRecordLayouts.getMemorySize() +
8525          llvm::capacity_in_bytes(ObjCLayouts) +
8526          llvm::capacity_in_bytes(KeyFunctions) +
8527          llvm::capacity_in_bytes(ObjCImpls) +
8528          llvm::capacity_in_bytes(BlockVarCopyInits) +
8529          llvm::capacity_in_bytes(DeclAttrs) +
8530          llvm::capacity_in_bytes(TemplateOrInstantiation) +
8531          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8532          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8533          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8534          llvm::capacity_in_bytes(OverriddenMethods) +
8535          llvm::capacity_in_bytes(Types) +
8536          llvm::capacity_in_bytes(VariableArrayTypes) +
8537          llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
8538 }
8539 
8540 /// getIntTypeForBitwidth -
8541 /// sets integer QualTy according to specified details:
8542 /// bitwidth, signed/unsigned.
8543 /// Returns empty type if there is no appropriate target types.
getIntTypeForBitwidth(unsigned DestWidth,unsigned Signed) const8544 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8545                                            unsigned Signed) const {
8546   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8547   CanQualType QualTy = getFromTargetType(Ty);
8548   if (!QualTy && DestWidth == 128)
8549     return Signed ? Int128Ty : UnsignedInt128Ty;
8550   return QualTy;
8551 }
8552 
8553 /// getRealTypeForBitwidth -
8554 /// sets floating point QualTy according to specified bitwidth.
8555 /// Returns empty type if there is no appropriate target types.
getRealTypeForBitwidth(unsigned DestWidth) const8556 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8557   TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8558   switch (Ty) {
8559   case TargetInfo::Float:
8560     return FloatTy;
8561   case TargetInfo::Double:
8562     return DoubleTy;
8563   case TargetInfo::LongDouble:
8564     return LongDoubleTy;
8565   case TargetInfo::NoFloat:
8566     return QualType();
8567   }
8568 
8569   llvm_unreachable("Unhandled TargetInfo::RealType value");
8570 }
8571 
setManglingNumber(const NamedDecl * ND,unsigned Number)8572 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8573   if (Number > 1)
8574     MangleNumbers[ND] = Number;
8575 }
8576 
getManglingNumber(const NamedDecl * ND) const8577 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8578   llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8579     MangleNumbers.find(ND);
8580   return I != MangleNumbers.end() ? I->second : 1;
8581 }
8582 
setStaticLocalNumber(const VarDecl * VD,unsigned Number)8583 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8584   if (Number > 1)
8585     StaticLocalNumbers[VD] = Number;
8586 }
8587 
getStaticLocalNumber(const VarDecl * VD) const8588 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8589   llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8590       StaticLocalNumbers.find(VD);
8591   return I != StaticLocalNumbers.end() ? I->second : 1;
8592 }
8593 
8594 MangleNumberingContext &
getManglingNumberContext(const DeclContext * DC)8595 ASTContext::getManglingNumberContext(const DeclContext *DC) {
8596   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
8597   MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8598   if (!MCtx)
8599     MCtx = createMangleNumberingContext();
8600   return *MCtx;
8601 }
8602 
createMangleNumberingContext() const8603 MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8604   return ABI->createMangleNumberingContext();
8605 }
8606 
8607 const CXXConstructorDecl *
getCopyConstructorForExceptionObject(CXXRecordDecl * RD)8608 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8609   return ABI->getCopyConstructorForExceptionObject(
8610       cast<CXXRecordDecl>(RD->getFirstDecl()));
8611 }
8612 
addCopyConstructorForExceptionObject(CXXRecordDecl * RD,CXXConstructorDecl * CD)8613 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8614                                                       CXXConstructorDecl *CD) {
8615   return ABI->addCopyConstructorForExceptionObject(
8616       cast<CXXRecordDecl>(RD->getFirstDecl()),
8617       cast<CXXConstructorDecl>(CD->getFirstDecl()));
8618 }
8619 
addDefaultArgExprForConstructor(const CXXConstructorDecl * CD,unsigned ParmIdx,Expr * DAE)8620 void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8621                                                  unsigned ParmIdx, Expr *DAE) {
8622   ABI->addDefaultArgExprForConstructor(
8623       cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8624 }
8625 
getDefaultArgExprForConstructor(const CXXConstructorDecl * CD,unsigned ParmIdx)8626 Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8627                                                   unsigned ParmIdx) {
8628   return ABI->getDefaultArgExprForConstructor(
8629       cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8630 }
8631 
addTypedefNameForUnnamedTagDecl(TagDecl * TD,TypedefNameDecl * DD)8632 void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
8633                                                  TypedefNameDecl *DD) {
8634   return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
8635 }
8636 
8637 TypedefNameDecl *
getTypedefNameForUnnamedTagDecl(const TagDecl * TD)8638 ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
8639   return ABI->getTypedefNameForUnnamedTagDecl(TD);
8640 }
8641 
addDeclaratorForUnnamedTagDecl(TagDecl * TD,DeclaratorDecl * DD)8642 void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
8643                                                 DeclaratorDecl *DD) {
8644   return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
8645 }
8646 
getDeclaratorForUnnamedTagDecl(const TagDecl * TD)8647 DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
8648   return ABI->getDeclaratorForUnnamedTagDecl(TD);
8649 }
8650 
setParameterIndex(const ParmVarDecl * D,unsigned int index)8651 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8652   ParamIndices[D] = index;
8653 }
8654 
getParameterIndex(const ParmVarDecl * D) const8655 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8656   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8657   assert(I != ParamIndices.end() &&
8658          "ParmIndices lacks entry set by ParmVarDecl");
8659   return I->second;
8660 }
8661 
8662 APValue *
getMaterializedTemporaryValue(const MaterializeTemporaryExpr * E,bool MayCreate)8663 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8664                                           bool MayCreate) {
8665   assert(E && E->getStorageDuration() == SD_Static &&
8666          "don't need to cache the computed value for this temporary");
8667   if (MayCreate) {
8668     APValue *&MTVI = MaterializedTemporaryValues[E];
8669     if (!MTVI)
8670       MTVI = new (*this) APValue;
8671     return MTVI;
8672   }
8673 
8674   return MaterializedTemporaryValues.lookup(E);
8675 }
8676 
AtomicUsesUnsupportedLibcall(const AtomicExpr * E) const8677 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8678   const llvm::Triple &T = getTargetInfo().getTriple();
8679   if (!T.isOSDarwin())
8680     return false;
8681 
8682   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8683       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8684     return false;
8685 
8686   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8687   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8688   uint64_t Size = sizeChars.getQuantity();
8689   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8690   unsigned Align = alignChars.getQuantity();
8691   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8692   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8693 }
8694 
8695 namespace {
8696 
getSingleDynTypedNodeFromParentMap(ASTContext::ParentMapPointers::mapped_type U)8697 ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
8698     ASTContext::ParentMapPointers::mapped_type U) {
8699   if (const auto *D = U.dyn_cast<const Decl *>())
8700     return ast_type_traits::DynTypedNode::create(*D);
8701   if (const auto *S = U.dyn_cast<const Stmt *>())
8702     return ast_type_traits::DynTypedNode::create(*S);
8703   return *U.get<ast_type_traits::DynTypedNode *>();
8704 }
8705 
8706 /// Template specializations to abstract away from pointers and TypeLocs.
8707 /// @{
8708 template <typename T>
createDynTypedNode(const T & Node)8709 ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
8710   return ast_type_traits::DynTypedNode::create(*Node);
8711 }
8712 template <>
createDynTypedNode(const TypeLoc & Node)8713 ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
8714   return ast_type_traits::DynTypedNode::create(Node);
8715 }
8716 template <>
8717 ast_type_traits::DynTypedNode
createDynTypedNode(const NestedNameSpecifierLoc & Node)8718 createDynTypedNode(const NestedNameSpecifierLoc &Node) {
8719   return ast_type_traits::DynTypedNode::create(Node);
8720 }
8721 /// @}
8722 
8723   /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8724   /// parents as defined by the \c RecursiveASTVisitor.
8725   ///
8726   /// Note that the relationship described here is purely in terms of AST
8727   /// traversal - there are other relationships (for example declaration context)
8728   /// in the AST that are better modeled by special matchers.
8729   ///
8730   /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8731   class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8732   public:
8733     /// \brief Builds and returns the translation unit's parent map.
8734     ///
8735     ///  The caller takes ownership of the returned \c ParentMap.
8736     static std::pair<ASTContext::ParentMapPointers *,
8737                      ASTContext::ParentMapOtherNodes *>
buildMap(TranslationUnitDecl & TU)8738     buildMap(TranslationUnitDecl &TU) {
8739       ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
8740                                   new ASTContext::ParentMapOtherNodes);
8741       Visitor.TraverseDecl(&TU);
8742       return std::make_pair(Visitor.Parents, Visitor.OtherParents);
8743     }
8744 
8745   private:
8746     typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8747 
ParentMapASTVisitor(ASTContext::ParentMapPointers * Parents,ASTContext::ParentMapOtherNodes * OtherParents)8748     ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
8749                         ASTContext::ParentMapOtherNodes *OtherParents)
8750         : Parents(Parents), OtherParents(OtherParents) {}
8751 
shouldVisitTemplateInstantiations() const8752     bool shouldVisitTemplateInstantiations() const {
8753       return true;
8754     }
shouldVisitImplicitCode() const8755     bool shouldVisitImplicitCode() const {
8756       return true;
8757     }
8758 
8759     template <typename T, typename MapNodeTy, typename BaseTraverseFn,
8760               typename MapTy>
TraverseNode(T Node,MapNodeTy MapNode,BaseTraverseFn BaseTraverse,MapTy * Parents)8761     bool TraverseNode(T Node, MapNodeTy MapNode,
8762                       BaseTraverseFn BaseTraverse, MapTy *Parents) {
8763       if (!Node)
8764         return true;
8765       if (ParentStack.size() > 0) {
8766         // FIXME: Currently we add the same parent multiple times, but only
8767         // when no memoization data is available for the type.
8768         // For example when we visit all subexpressions of template
8769         // instantiations; this is suboptimal, but benign: the only way to
8770         // visit those is with hasAncestor / hasParent, and those do not create
8771         // new matches.
8772         // The plan is to enable DynTypedNode to be storable in a map or hash
8773         // map. The main problem there is to implement hash functions /
8774         // comparison operators for all types that DynTypedNode supports that
8775         // do not have pointer identity.
8776         auto &NodeOrVector = (*Parents)[MapNode];
8777         if (NodeOrVector.isNull()) {
8778           if (const auto *D = ParentStack.back().get<Decl>())
8779             NodeOrVector = D;
8780           else if (const auto *S = ParentStack.back().get<Stmt>())
8781             NodeOrVector = S;
8782           else
8783             NodeOrVector =
8784                 new ast_type_traits::DynTypedNode(ParentStack.back());
8785         } else {
8786           if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
8787             auto *Vector = new ASTContext::ParentVector(
8788                 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
8789             if (auto *Node =
8790                     NodeOrVector
8791                         .template dyn_cast<ast_type_traits::DynTypedNode *>())
8792               delete Node;
8793             NodeOrVector = Vector;
8794           }
8795 
8796           auto *Vector =
8797               NodeOrVector.template get<ASTContext::ParentVector *>();
8798           // Skip duplicates for types that have memoization data.
8799           // We must check that the type has memoization data before calling
8800           // std::find() because DynTypedNode::operator== can't compare all
8801           // types.
8802           bool Found = ParentStack.back().getMemoizationData() &&
8803                        std::find(Vector->begin(), Vector->end(),
8804                                  ParentStack.back()) != Vector->end();
8805           if (!Found)
8806             Vector->push_back(ParentStack.back());
8807         }
8808       }
8809       ParentStack.push_back(createDynTypedNode(Node));
8810       bool Result = BaseTraverse();
8811       ParentStack.pop_back();
8812       return Result;
8813     }
8814 
TraverseDecl(Decl * DeclNode)8815     bool TraverseDecl(Decl *DeclNode) {
8816       return TraverseNode(DeclNode, DeclNode,
8817                           [&] { return VisitorBase::TraverseDecl(DeclNode); },
8818                           Parents);
8819     }
8820 
TraverseStmt(Stmt * StmtNode)8821     bool TraverseStmt(Stmt *StmtNode) {
8822       return TraverseNode(StmtNode, StmtNode,
8823                           [&] { return VisitorBase::TraverseStmt(StmtNode); },
8824                           Parents);
8825     }
8826 
TraverseTypeLoc(TypeLoc TypeLocNode)8827     bool TraverseTypeLoc(TypeLoc TypeLocNode) {
8828       return TraverseNode(
8829           TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
8830           [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
8831           OtherParents);
8832     }
8833 
TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode)8834     bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
8835       return TraverseNode(
8836           NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
8837           [&] {
8838             return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
8839           },
8840           OtherParents);
8841     }
8842 
8843     ASTContext::ParentMapPointers *Parents;
8844     ASTContext::ParentMapOtherNodes *OtherParents;
8845     llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8846 
8847     friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8848   };
8849 
8850 } // anonymous namespace
8851 
8852 template <typename NodeTy, typename MapTy>
getDynNodeFromMap(const NodeTy & Node,const MapTy & Map)8853 static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
8854                                                       const MapTy &Map) {
8855   auto I = Map.find(Node);
8856   if (I == Map.end()) {
8857     return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
8858   }
8859   if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
8860     return llvm::makeArrayRef(*V);
8861   }
8862   return getSingleDynTypedNodeFromParentMap(I->second);
8863 }
8864 
8865 ASTContext::DynTypedNodeList
getParents(const ast_type_traits::DynTypedNode & Node)8866 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8867   if (!PointerParents) {
8868     // We always need to run over the whole translation unit, as
8869     // hasAncestor can escape any subtree.
8870     auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
8871     PointerParents.reset(Maps.first);
8872     OtherParents.reset(Maps.second);
8873   }
8874   if (Node.getNodeKind().hasPointerIdentity())
8875     return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
8876   return getDynNodeFromMap(Node, *OtherParents);
8877 }
8878 
8879 bool
ObjCMethodsAreEqual(const ObjCMethodDecl * MethodDecl,const ObjCMethodDecl * MethodImpl)8880 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8881                                 const ObjCMethodDecl *MethodImpl) {
8882   // No point trying to match an unavailable/deprecated mothod.
8883   if (MethodDecl->hasAttr<UnavailableAttr>()
8884       || MethodDecl->hasAttr<DeprecatedAttr>())
8885     return false;
8886   if (MethodDecl->getObjCDeclQualifier() !=
8887       MethodImpl->getObjCDeclQualifier())
8888     return false;
8889   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
8890     return false;
8891 
8892   if (MethodDecl->param_size() != MethodImpl->param_size())
8893     return false;
8894 
8895   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8896        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8897        EF = MethodDecl->param_end();
8898        IM != EM && IF != EF; ++IM, ++IF) {
8899     const ParmVarDecl *DeclVar = (*IF);
8900     const ParmVarDecl *ImplVar = (*IM);
8901     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8902       return false;
8903     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8904       return false;
8905   }
8906   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8907 
8908 }
8909 
8910 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8911 // doesn't include ASTContext.h
8912 template
8913 clang::LazyGenerationalUpdatePtr<
8914     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8915 clang::LazyGenerationalUpdatePtr<
8916     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8917         const clang::ASTContext &Ctx, Decl *Value);
8918