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