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