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