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