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