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