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