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