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