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