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