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