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