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