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