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