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