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