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