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