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