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