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