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