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