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