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