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