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