ASTContext.cpp revision becb8d5a6ab5103393eac5344ae69bcb860601dd
1bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant//
3f5256e16dfc425c1d466f6308d4026d529ce9e0bHoward Hinnant//                     The LLVM Compiler Infrastructure
4bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant//
5b64f8b07c104c6cc986570ac8ee0ed16a9f23976Howard Hinnant// This file is distributed under the University of Illinois Open Source
6b64f8b07c104c6cc986570ac8ee0ed16a9f23976Howard Hinnant// License. See LICENSE.TXT for details.
7bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant//
8bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant//===----------------------------------------------------------------------===//
9bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant//
10bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant//  This file implements the ASTContext interface.
11bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant//
12bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant//===----------------------------------------------------------------------===//
13bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
14bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include "clang/AST/ASTContext.h"
15bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include "clang/AST/CharUnits.h"
16bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include "clang/AST/DeclCXX.h"
17bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include "clang/AST/DeclObjC.h"
18bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include "clang/AST/DeclTemplate.h"
19061d0cc4db18d17bf01ed14c5db0be098205bd47Marshall Clow#include "clang/AST/TypeLoc.h"
2070342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant#include "clang/AST/Expr.h"
21bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include "clang/AST/ExternalASTSource.h"
22bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include "clang/AST/RecordLayout.h"
23bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include "clang/Basic/Builtins.h"
24bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include "clang/Basic/SourceManager.h"
25bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include "clang/Basic/TargetInfo.h"
26bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include "llvm/ADT/SmallString.h"
27bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include "llvm/ADT/StringExtras.h"
28bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include "llvm/Support/MathExtras.h"
29bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include "llvm/Support/raw_ostream.h"
30bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include "RecordLayoutBuilder.h"
31bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
32bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantusing namespace clang;
33bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
34bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantenum FloatingRank {
35bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  FloatRank, DoubleRank, LongDoubleRank
36bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant};
37bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
38bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard HinnantASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
39bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant                       const TargetInfo &t,
40bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant                       IdentifierTable &idents, SelectorTable &sels,
41bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant                       Builtin::Context &builtins,
42bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant                       bool FreeMem, unsigned size_reserve) :
43bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
44bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
45bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
46bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  SourceMgr(SM), LangOpts(LOpts),
47bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
48bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  Idents(idents), Selectors(sels),
49bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
50bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  ObjCIdRedefinitionType = QualType();
51bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  ObjCClassRedefinitionType = QualType();
52bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  ObjCSelRedefinitionType = QualType();
53bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  if (size_reserve > 0) Types.reserve(size_reserve);
54bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  TUDecl = TranslationUnitDecl::Create(*this);
55bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  InitBuiltinTypes();
56bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant}
57bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
58bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard HinnantASTContext::~ASTContext() {
59bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  // Release the DenseMaps associated with DeclContext objects.
60bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  // FIXME: Is this the ideal solution?
61bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  ReleaseDeclContextMaps();
62bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
63bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  // Release all of the memory associated with overridden C++ methods.
64bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
65bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant         OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
66bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant       OM != OMEnd; ++OM)
67bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant    OM->second.Destroy();
68bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
69bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant  if (FreeMemory) {
70bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant    // Deallocate all the types.
71bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant    while (!Types.empty()) {
72bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant      Types.back()->Destroy(*this);
73bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant      Types.pop_back();
74bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant    }
75bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
76bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant    for (llvm::FoldingSet<ExtQuals>::iterator
77bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant         I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
78bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant      // Increment in loop to prevent using deallocated memory.
79bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant      Deallocate(&*I++);
80bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant    }
81bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
82bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant    for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
83bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant         I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
84bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant      // Increment in loop to prevent using deallocated memory.
85bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant      if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
86bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant        R->Destroy(*this);
87bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant    }
88bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant
8970342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant    for (llvm::DenseMap<const ObjCContainerDecl*,
9070342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant         const ASTRecordLayout*>::iterator
9170342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant         I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
9270342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant      // Increment in loop to prevent using deallocated memory.
9370342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant      if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
9470342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant        R->Destroy(*this);
9570342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant    }
9670342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  }
9770342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant
9870342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  // Destroy nested-name-specifiers.
9970342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  for (llvm::FoldingSet<NestedNameSpecifier>::iterator
10070342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant         NNS = NestedNameSpecifiers.begin(),
10170342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant         NNSEnd = NestedNameSpecifiers.end();
10270342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant       NNS != NNSEnd; ) {
10370342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant    // Increment in loop to prevent using deallocated memory.
10470342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant    (*NNS++).Destroy(*this);
10570342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  }
10670342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant
10770342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  if (GlobalNestedNameSpecifier)
10870342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant    GlobalNestedNameSpecifier->Destroy(*this);
10970342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant
11070342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  TUDecl->Destroy(*this);
11170342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant}
11270342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant
11370342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantvoid
11470342b99e227912742972b754ad86e75c5d7eefbHoward HinnantASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
11570342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  ExternalSource.reset(Source.take());
11670342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant}
11770342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant
11870342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantvoid ASTContext::PrintStats() const {
11970342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  fprintf(stderr, "*** AST Context Stats:\n");
12070342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  fprintf(stderr, "  %d types total.\n", (int)Types.size());
12170342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant
12270342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  unsigned counts[] = {
12370342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant#define TYPE(Name, Parent) 0,
12470342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant#define ABSTRACT_TYPE(Name, Parent)
12570342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant#include "clang/AST/TypeNodes.def"
12670342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant    0 // Extra
12770342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  };
12870342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant
12970342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
13070342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant    Type *T = Types[i];
13170342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant    counts[(unsigned)T->getTypeClass()]++;
13270342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  }
13370342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant
13470342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  unsigned Idx = 0;
13570342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  unsigned TotalBytes = 0;
13670342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant#define TYPE(Name, Parent)                                              \
13770342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  if (counts[Idx])                                                      \
13870342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant    fprintf(stderr, "    %d %s types\n", (int)counts[Idx], #Name);      \
13970342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
14070342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  ++Idx;
14170342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant#define ABSTRACT_TYPE(Name, Parent)
14270342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant#include "clang/AST/TypeNodes.def"
14370342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant
14470342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
14570342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant
14670342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  if (ExternalSource.get()) {
14770342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant    fprintf(stderr, "\n");
14870342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant    ExternalSource->PrintStats();
14970342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  }
15070342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant}
15170342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant
15270342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant
15370342b99e227912742972b754ad86e75c5d7eefbHoward Hinnantvoid ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
15470342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
15570342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
15670342b99e227912742972b754ad86e75c5d7eefbHoward Hinnant  Types.push_back(Ty);
157bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant}
158
159void ASTContext::InitBuiltinTypes() {
160  assert(VoidTy.isNull() && "Context reinitialized?");
161
162  // C99 6.2.5p19.
163  InitBuiltinType(VoidTy,              BuiltinType::Void);
164
165  // C99 6.2.5p2.
166  InitBuiltinType(BoolTy,              BuiltinType::Bool);
167  // C99 6.2.5p3.
168  if (LangOpts.CharIsSigned)
169    InitBuiltinType(CharTy,            BuiltinType::Char_S);
170  else
171    InitBuiltinType(CharTy,            BuiltinType::Char_U);
172  // C99 6.2.5p4.
173  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
174  InitBuiltinType(ShortTy,             BuiltinType::Short);
175  InitBuiltinType(IntTy,               BuiltinType::Int);
176  InitBuiltinType(LongTy,              BuiltinType::Long);
177  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
178
179  // C99 6.2.5p6.
180  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
181  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
182  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
183  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
184  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
185
186  // C99 6.2.5p10.
187  InitBuiltinType(FloatTy,             BuiltinType::Float);
188  InitBuiltinType(DoubleTy,            BuiltinType::Double);
189  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
190
191  // GNU extension, 128-bit integers.
192  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
193  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
194
195  if (LangOpts.CPlusPlus) // C++ 3.9.1p5
196    InitBuiltinType(WCharTy,           BuiltinType::WChar);
197  else // C99
198    WCharTy = getFromTargetType(Target.getWCharType());
199
200  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
201    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
202  else // C99
203    Char16Ty = getFromTargetType(Target.getChar16Type());
204
205  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
206    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
207  else // C99
208    Char32Ty = getFromTargetType(Target.getChar32Type());
209
210  // Placeholder type for functions.
211  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
212
213  // Placeholder type for type-dependent expressions whose type is
214  // completely unknown. No code should ever check a type against
215  // DependentTy and users should never see it; however, it is here to
216  // help diagnose failures to properly check for type-dependent
217  // expressions.
218  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
219
220  // Placeholder type for C++0x auto declarations whose real type has
221  // not yet been deduced.
222  InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
223
224  // C99 6.2.5p11.
225  FloatComplexTy      = getComplexType(FloatTy);
226  DoubleComplexTy     = getComplexType(DoubleTy);
227  LongDoubleComplexTy = getComplexType(LongDoubleTy);
228
229  BuiltinVaListType = QualType();
230
231  // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
232  ObjCIdTypedefType = QualType();
233  ObjCClassTypedefType = QualType();
234  ObjCSelTypedefType = QualType();
235
236  // Builtin types for 'id', 'Class', and 'SEL'.
237  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
238  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
239  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
240
241  ObjCConstantStringType = QualType();
242
243  // void * type
244  VoidPtrTy = getPointerType(VoidTy);
245
246  // nullptr type (C++0x 2.14.7)
247  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
248}
249
250MemberSpecializationInfo *
251ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
252  assert(Var->isStaticDataMember() && "Not a static data member");
253  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
254    = InstantiatedFromStaticDataMember.find(Var);
255  if (Pos == InstantiatedFromStaticDataMember.end())
256    return 0;
257
258  return Pos->second;
259}
260
261void
262ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
263                                                TemplateSpecializationKind TSK) {
264  assert(Inst->isStaticDataMember() && "Not a static data member");
265  assert(Tmpl->isStaticDataMember() && "Not a static data member");
266  assert(!InstantiatedFromStaticDataMember[Inst] &&
267         "Already noted what static data member was instantiated from");
268  InstantiatedFromStaticDataMember[Inst]
269    = new (*this) MemberSpecializationInfo(Tmpl, TSK);
270}
271
272NamedDecl *
273ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
274  llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
275    = InstantiatedFromUsingDecl.find(UUD);
276  if (Pos == InstantiatedFromUsingDecl.end())
277    return 0;
278
279  return Pos->second;
280}
281
282void
283ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
284  assert((isa<UsingDecl>(Pattern) ||
285          isa<UnresolvedUsingValueDecl>(Pattern) ||
286          isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
287         "pattern decl is not a using decl");
288  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
289  InstantiatedFromUsingDecl[Inst] = Pattern;
290}
291
292UsingShadowDecl *
293ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
294  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
295    = InstantiatedFromUsingShadowDecl.find(Inst);
296  if (Pos == InstantiatedFromUsingShadowDecl.end())
297    return 0;
298
299  return Pos->second;
300}
301
302void
303ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
304                                               UsingShadowDecl *Pattern) {
305  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
306  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
307}
308
309FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
310  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
311    = InstantiatedFromUnnamedFieldDecl.find(Field);
312  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
313    return 0;
314
315  return Pos->second;
316}
317
318void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
319                                                     FieldDecl *Tmpl) {
320  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
321  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
322  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
323         "Already noted what unnamed field was instantiated from");
324
325  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
326}
327
328CXXMethodVector::iterator CXXMethodVector::begin() const {
329  if ((Storage & 0x01) == 0)
330    return reinterpret_cast<iterator>(&Storage);
331
332  vector_type *Vec = reinterpret_cast<vector_type *>(Storage & ~0x01);
333  return &Vec->front();
334}
335
336CXXMethodVector::iterator CXXMethodVector::end() const {
337  if ((Storage & 0x01) == 0) {
338    if (Storage == 0)
339      return reinterpret_cast<iterator>(&Storage);
340
341    return reinterpret_cast<iterator>(&Storage) + 1;
342  }
343
344  vector_type *Vec = reinterpret_cast<vector_type *>(Storage & ~0x01);
345  return &Vec->front() + Vec->size();
346}
347
348void CXXMethodVector::push_back(const CXXMethodDecl *Method) {
349  if (Storage == 0) {
350    // 0 -> 1 element.
351    Storage = reinterpret_cast<uintptr_t>(Method);
352    return;
353  }
354
355  vector_type *Vec;
356  if ((Storage & 0x01) == 0) {
357    // 1 -> 2 elements. Allocate a new vector and push the element into that
358    // vector.
359    Vec = new vector_type;
360    Vec->push_back(reinterpret_cast<const CXXMethodDecl *>(Storage));
361    Storage = reinterpret_cast<uintptr_t>(Vec) | 0x01;
362  } else
363    Vec = reinterpret_cast<vector_type *>(Storage & ~0x01);
364
365  // Add the new method to the vector.
366  Vec->push_back(Method);
367}
368
369void CXXMethodVector::Destroy() {
370  if (Storage & 0x01)
371    delete reinterpret_cast<vector_type *>(Storage & ~0x01);
372
373  Storage = 0;
374}
375
376
377ASTContext::overridden_cxx_method_iterator
378ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
379  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
380    = OverriddenMethods.find(Method);
381  if (Pos == OverriddenMethods.end())
382    return 0;
383
384  return Pos->second.begin();
385}
386
387ASTContext::overridden_cxx_method_iterator
388ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
389  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
390    = OverriddenMethods.find(Method);
391  if (Pos == OverriddenMethods.end())
392    return 0;
393
394  return Pos->second.end();
395}
396
397void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
398                                     const CXXMethodDecl *Overridden) {
399  OverriddenMethods[Method].push_back(Overridden);
400}
401
402namespace {
403  class BeforeInTranslationUnit
404    : std::binary_function<SourceRange, SourceRange, bool> {
405    SourceManager *SourceMgr;
406
407  public:
408    explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
409
410    bool operator()(SourceRange X, SourceRange Y) {
411      return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
412    }
413  };
414}
415
416/// \brief Determine whether the given comment is a Doxygen-style comment.
417///
418/// \param Start the start of the comment text.
419///
420/// \param End the end of the comment text.
421///
422/// \param Member whether we want to check whether this is a member comment
423/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
424/// we only return true when we find a non-member comment.
425static bool
426isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
427                 bool Member = false) {
428  const char *BufferStart
429    = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
430  const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
431  const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
432
433  if (End - Start < 4)
434    return false;
435
436  assert(Start[0] == '/' && "Not a comment?");
437  if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
438    return false;
439  if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
440    return false;
441
442  return (Start[3] == '<') == Member;
443}
444
445/// \brief Retrieve the comment associated with the given declaration, if
446/// it has one.
447const char *ASTContext::getCommentForDecl(const Decl *D) {
448  if (!D)
449    return 0;
450
451  // Check whether we have cached a comment string for this declaration
452  // already.
453  llvm::DenseMap<const Decl *, std::string>::iterator Pos
454    = DeclComments.find(D);
455  if (Pos != DeclComments.end())
456    return Pos->second.c_str();
457
458  // If we have an external AST source and have not yet loaded comments from
459  // that source, do so now.
460  if (ExternalSource && !LoadedExternalComments) {
461    std::vector<SourceRange> LoadedComments;
462    ExternalSource->ReadComments(LoadedComments);
463
464    if (!LoadedComments.empty())
465      Comments.insert(Comments.begin(), LoadedComments.begin(),
466                      LoadedComments.end());
467
468    LoadedExternalComments = true;
469  }
470
471  // If there are no comments anywhere, we won't find anything.
472  if (Comments.empty())
473    return 0;
474
475  // If the declaration doesn't map directly to a location in a file, we
476  // can't find the comment.
477  SourceLocation DeclStartLoc = D->getLocStart();
478  if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
479    return 0;
480
481  // Find the comment that occurs just before this declaration.
482  std::vector<SourceRange>::iterator LastComment
483    = std::lower_bound(Comments.begin(), Comments.end(),
484                       SourceRange(DeclStartLoc),
485                       BeforeInTranslationUnit(&SourceMgr));
486
487  // Decompose the location for the start of the declaration and find the
488  // beginning of the file buffer.
489  std::pair<FileID, unsigned> DeclStartDecomp
490    = SourceMgr.getDecomposedLoc(DeclStartLoc);
491  const char *FileBufferStart
492    = SourceMgr.getBufferData(DeclStartDecomp.first).first;
493
494  // First check whether we have a comment for a member.
495  if (LastComment != Comments.end() &&
496      !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
497      isDoxygenComment(SourceMgr, *LastComment, true)) {
498    std::pair<FileID, unsigned> LastCommentEndDecomp
499      = SourceMgr.getDecomposedLoc(LastComment->getEnd());
500    if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
501        SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
502          == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
503                                     LastCommentEndDecomp.second)) {
504      // The Doxygen member comment comes after the declaration starts and
505      // is on the same line and in the same file as the declaration. This
506      // is the comment we want.
507      std::string &Result = DeclComments[D];
508      Result.append(FileBufferStart +
509                      SourceMgr.getFileOffset(LastComment->getBegin()),
510                    FileBufferStart + LastCommentEndDecomp.second + 1);
511      return Result.c_str();
512    }
513  }
514
515  if (LastComment == Comments.begin())
516    return 0;
517  --LastComment;
518
519  // Decompose the end of the comment.
520  std::pair<FileID, unsigned> LastCommentEndDecomp
521    = SourceMgr.getDecomposedLoc(LastComment->getEnd());
522
523  // If the comment and the declaration aren't in the same file, then they
524  // aren't related.
525  if (DeclStartDecomp.first != LastCommentEndDecomp.first)
526    return 0;
527
528  // Check that we actually have a Doxygen comment.
529  if (!isDoxygenComment(SourceMgr, *LastComment))
530    return 0;
531
532  // Compute the starting line for the declaration and for the end of the
533  // comment (this is expensive).
534  unsigned DeclStartLine
535    = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
536  unsigned CommentEndLine
537    = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
538                              LastCommentEndDecomp.second);
539
540  // If the comment does not end on the line prior to the declaration, then
541  // the comment is not associated with the declaration at all.
542  if (CommentEndLine + 1 != DeclStartLine)
543    return 0;
544
545  // We have a comment, but there may be more comments on the previous lines.
546  // Keep looking so long as the comments are still Doxygen comments and are
547  // still adjacent.
548  unsigned ExpectedLine
549    = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
550  std::vector<SourceRange>::iterator FirstComment = LastComment;
551  while (FirstComment != Comments.begin()) {
552    // Look at the previous comment
553    --FirstComment;
554    std::pair<FileID, unsigned> Decomp
555      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
556
557    // If this previous comment is in a different file, we're done.
558    if (Decomp.first != DeclStartDecomp.first) {
559      ++FirstComment;
560      break;
561    }
562
563    // If this comment is not a Doxygen comment, we're done.
564    if (!isDoxygenComment(SourceMgr, *FirstComment)) {
565      ++FirstComment;
566      break;
567    }
568
569    // If the line number is not what we expected, we're done.
570    unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
571    if (Line != ExpectedLine) {
572      ++FirstComment;
573      break;
574    }
575
576    // Set the next expected line number.
577    ExpectedLine
578      = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
579  }
580
581  // The iterator range [FirstComment, LastComment] contains all of the
582  // BCPL comments that, together, are associated with this declaration.
583  // Form a single comment block string for this declaration that concatenates
584  // all of these comments.
585  std::string &Result = DeclComments[D];
586  while (FirstComment != LastComment) {
587    std::pair<FileID, unsigned> DecompStart
588      = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
589    std::pair<FileID, unsigned> DecompEnd
590      = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
591    Result.append(FileBufferStart + DecompStart.second,
592                  FileBufferStart + DecompEnd.second + 1);
593    ++FirstComment;
594  }
595
596  // Append the last comment line.
597  Result.append(FileBufferStart +
598                  SourceMgr.getFileOffset(LastComment->getBegin()),
599                FileBufferStart + LastCommentEndDecomp.second + 1);
600  return Result.c_str();
601}
602
603//===----------------------------------------------------------------------===//
604//                         Type Sizing and Analysis
605//===----------------------------------------------------------------------===//
606
607/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
608/// scalar floating point type.
609const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
610  const BuiltinType *BT = T->getAs<BuiltinType>();
611  assert(BT && "Not a floating point type!");
612  switch (BT->getKind()) {
613  default: assert(0 && "Not a floating point type!");
614  case BuiltinType::Float:      return Target.getFloatFormat();
615  case BuiltinType::Double:     return Target.getDoubleFormat();
616  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
617  }
618}
619
620/// getDeclAlign - Return a conservative estimate of the alignment of the
621/// specified decl.  Note that bitfields do not have a valid alignment, so
622/// this method will assert on them.
623/// If @p RefAsPointee, references are treated like their underlying type
624/// (for alignof), else they're treated like pointers (for CodeGen).
625CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
626  unsigned Align = Target.getCharWidth();
627
628  if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
629    Align = std::max(Align, AA->getMaxAlignment());
630
631  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
632    QualType T = VD->getType();
633    if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
634      if (RefAsPointee)
635        T = RT->getPointeeType();
636      else
637        T = getPointerType(RT->getPointeeType());
638    }
639    if (!T->isIncompleteType() && !T->isFunctionType()) {
640      // Incomplete or function types default to 1.
641      while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
642        T = cast<ArrayType>(T)->getElementType();
643
644      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
645    }
646    if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
647      // In the case of a field in a packed struct, we want the minimum
648      // of the alignment of the field and the alignment of the struct.
649      Align = std::min(Align,
650        getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
651    }
652  }
653
654  return CharUnits::fromQuantity(Align / Target.getCharWidth());
655}
656
657/// getTypeSize - Return the size of the specified type, in bits.  This method
658/// does not work on incomplete types.
659///
660/// FIXME: Pointers into different addr spaces could have different sizes and
661/// alignment requirements: getPointerInfo should take an AddrSpace, this
662/// should take a QualType, &c.
663std::pair<uint64_t, unsigned>
664ASTContext::getTypeInfo(const Type *T) {
665  uint64_t Width=0;
666  unsigned Align=8;
667  switch (T->getTypeClass()) {
668#define TYPE(Class, Base)
669#define ABSTRACT_TYPE(Class, Base)
670#define NON_CANONICAL_TYPE(Class, Base)
671#define DEPENDENT_TYPE(Class, Base) case Type::Class:
672#include "clang/AST/TypeNodes.def"
673    assert(false && "Should not see dependent types");
674    break;
675
676  case Type::FunctionNoProto:
677  case Type::FunctionProto:
678    // GCC extension: alignof(function) = 32 bits
679    Width = 0;
680    Align = 32;
681    break;
682
683  case Type::IncompleteArray:
684  case Type::VariableArray:
685    Width = 0;
686    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
687    break;
688
689  case Type::ConstantArray: {
690    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
691
692    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
693    Width = EltInfo.first*CAT->getSize().getZExtValue();
694    Align = EltInfo.second;
695    break;
696  }
697  case Type::ExtVector:
698  case Type::Vector: {
699    const VectorType *VT = cast<VectorType>(T);
700    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
701    Width = EltInfo.first*VT->getNumElements();
702    Align = Width;
703    // If the alignment is not a power of 2, round up to the next power of 2.
704    // This happens for non-power-of-2 length vectors.
705    if (VT->getNumElements() & (VT->getNumElements()-1)) {
706      Align = llvm::NextPowerOf2(Align);
707      Width = llvm::RoundUpToAlignment(Width, Align);
708    }
709    break;
710  }
711
712  case Type::Builtin:
713    switch (cast<BuiltinType>(T)->getKind()) {
714    default: assert(0 && "Unknown builtin type!");
715    case BuiltinType::Void:
716      // GCC extension: alignof(void) = 8 bits.
717      Width = 0;
718      Align = 8;
719      break;
720
721    case BuiltinType::Bool:
722      Width = Target.getBoolWidth();
723      Align = Target.getBoolAlign();
724      break;
725    case BuiltinType::Char_S:
726    case BuiltinType::Char_U:
727    case BuiltinType::UChar:
728    case BuiltinType::SChar:
729      Width = Target.getCharWidth();
730      Align = Target.getCharAlign();
731      break;
732    case BuiltinType::WChar:
733      Width = Target.getWCharWidth();
734      Align = Target.getWCharAlign();
735      break;
736    case BuiltinType::Char16:
737      Width = Target.getChar16Width();
738      Align = Target.getChar16Align();
739      break;
740    case BuiltinType::Char32:
741      Width = Target.getChar32Width();
742      Align = Target.getChar32Align();
743      break;
744    case BuiltinType::UShort:
745    case BuiltinType::Short:
746      Width = Target.getShortWidth();
747      Align = Target.getShortAlign();
748      break;
749    case BuiltinType::UInt:
750    case BuiltinType::Int:
751      Width = Target.getIntWidth();
752      Align = Target.getIntAlign();
753      break;
754    case BuiltinType::ULong:
755    case BuiltinType::Long:
756      Width = Target.getLongWidth();
757      Align = Target.getLongAlign();
758      break;
759    case BuiltinType::ULongLong:
760    case BuiltinType::LongLong:
761      Width = Target.getLongLongWidth();
762      Align = Target.getLongLongAlign();
763      break;
764    case BuiltinType::Int128:
765    case BuiltinType::UInt128:
766      Width = 128;
767      Align = 128; // int128_t is 128-bit aligned on all targets.
768      break;
769    case BuiltinType::Float:
770      Width = Target.getFloatWidth();
771      Align = Target.getFloatAlign();
772      break;
773    case BuiltinType::Double:
774      Width = Target.getDoubleWidth();
775      Align = Target.getDoubleAlign();
776      break;
777    case BuiltinType::LongDouble:
778      Width = Target.getLongDoubleWidth();
779      Align = Target.getLongDoubleAlign();
780      break;
781    case BuiltinType::NullPtr:
782      Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
783      Align = Target.getPointerAlign(0); //   == sizeof(void*)
784      break;
785    }
786    break;
787  case Type::ObjCObjectPointer:
788    Width = Target.getPointerWidth(0);
789    Align = Target.getPointerAlign(0);
790    break;
791  case Type::BlockPointer: {
792    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
793    Width = Target.getPointerWidth(AS);
794    Align = Target.getPointerAlign(AS);
795    break;
796  }
797  case Type::LValueReference:
798  case Type::RValueReference: {
799    // alignof and sizeof should never enter this code path here, so we go
800    // the pointer route.
801    unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
802    Width = Target.getPointerWidth(AS);
803    Align = Target.getPointerAlign(AS);
804    break;
805  }
806  case Type::Pointer: {
807    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
808    Width = Target.getPointerWidth(AS);
809    Align = Target.getPointerAlign(AS);
810    break;
811  }
812  case Type::MemberPointer: {
813    QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
814    std::pair<uint64_t, unsigned> PtrDiffInfo =
815      getTypeInfo(getPointerDiffType());
816    Width = PtrDiffInfo.first;
817    if (Pointee->isFunctionType())
818      Width *= 2;
819    Align = PtrDiffInfo.second;
820    break;
821  }
822  case Type::Complex: {
823    // Complex types have the same alignment as their elements, but twice the
824    // size.
825    std::pair<uint64_t, unsigned> EltInfo =
826      getTypeInfo(cast<ComplexType>(T)->getElementType());
827    Width = EltInfo.first*2;
828    Align = EltInfo.second;
829    break;
830  }
831  case Type::ObjCInterface: {
832    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
833    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
834    Width = Layout.getSize();
835    Align = Layout.getAlignment();
836    break;
837  }
838  case Type::Record:
839  case Type::Enum: {
840    const TagType *TT = cast<TagType>(T);
841
842    if (TT->getDecl()->isInvalidDecl()) {
843      Width = 1;
844      Align = 1;
845      break;
846    }
847
848    if (const EnumType *ET = dyn_cast<EnumType>(TT))
849      return getTypeInfo(ET->getDecl()->getIntegerType());
850
851    const RecordType *RT = cast<RecordType>(TT);
852    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
853    Width = Layout.getSize();
854    Align = Layout.getAlignment();
855    break;
856  }
857
858  case Type::SubstTemplateTypeParm:
859    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
860                       getReplacementType().getTypePtr());
861
862  case Type::Elaborated:
863    return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
864                         .getTypePtr());
865
866  case Type::Typedef: {
867    const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
868    if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
869      Align = std::max(Aligned->getMaxAlignment(),
870                       getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
871      Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
872    } else
873      return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
874    break;
875  }
876
877  case Type::TypeOfExpr:
878    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
879                         .getTypePtr());
880
881  case Type::TypeOf:
882    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
883
884  case Type::Decltype:
885    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
886                        .getTypePtr());
887
888  case Type::QualifiedName:
889    return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
890
891 case Type::InjectedClassName:
892   return getTypeInfo(cast<InjectedClassNameType>(T)
893                        ->getUnderlyingType().getTypePtr());
894
895  case Type::TemplateSpecialization:
896    assert(getCanonicalType(T) != T &&
897           "Cannot request the size of a dependent type");
898    // FIXME: this is likely to be wrong once we support template
899    // aliases, since a template alias could refer to a typedef that
900    // has an __aligned__ attribute on it.
901    return getTypeInfo(getCanonicalType(T));
902  }
903
904  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
905  return std::make_pair(Width, Align);
906}
907
908/// getTypeSizeInChars - Return the size of the specified type, in characters.
909/// This method does not work on incomplete types.
910CharUnits ASTContext::getTypeSizeInChars(QualType T) {
911  return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
912}
913CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
914  return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
915}
916
917/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
918/// characters. This method does not work on incomplete types.
919CharUnits ASTContext::getTypeAlignInChars(QualType T) {
920  return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
921}
922CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
923  return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
924}
925
926/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
927/// type for the current target in bits.  This can be different than the ABI
928/// alignment in cases where it is beneficial for performance to overalign
929/// a data type.
930unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
931  unsigned ABIAlign = getTypeAlign(T);
932
933  // Double and long long should be naturally aligned if possible.
934  if (const ComplexType* CT = T->getAs<ComplexType>())
935    T = CT->getElementType().getTypePtr();
936  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
937      T->isSpecificBuiltinType(BuiltinType::LongLong))
938    return std::max(ABIAlign, (unsigned)getTypeSize(T));
939
940  return ABIAlign;
941}
942
943static void CollectLocalObjCIvars(ASTContext *Ctx,
944                                  const ObjCInterfaceDecl *OI,
945                                  llvm::SmallVectorImpl<FieldDecl*> &Fields) {
946  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
947       E = OI->ivar_end(); I != E; ++I) {
948    ObjCIvarDecl *IVDecl = *I;
949    if (!IVDecl->isInvalidDecl())
950      Fields.push_back(cast<FieldDecl>(IVDecl));
951  }
952}
953
954void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
955                             llvm::SmallVectorImpl<FieldDecl*> &Fields) {
956  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
957    CollectObjCIvars(SuperClass, Fields);
958  CollectLocalObjCIvars(this, OI, Fields);
959}
960
961/// ShallowCollectObjCIvars -
962/// Collect all ivars, including those synthesized, in the current class.
963///
964void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
965                                 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
966  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
967         E = OI->ivar_end(); I != E; ++I) {
968     Ivars.push_back(*I);
969  }
970
971  CollectNonClassIvars(OI, Ivars);
972}
973
974void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
975                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
976  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
977       E = PD->prop_end(); I != E; ++I)
978    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
979      Ivars.push_back(Ivar);
980
981  // Also look into nested protocols.
982  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
983       E = PD->protocol_end(); P != E; ++P)
984    CollectProtocolSynthesizedIvars(*P, Ivars);
985}
986
987/// CollectNonClassIvars -
988/// This routine collects all other ivars which are not declared in the class.
989/// This includes synthesized ivars and those in class's implementation.
990///
991void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
992                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
993  // Find ivars declared in class extension.
994  if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
995    for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
996         E = CDecl->ivar_end(); I != E; ++I) {
997      Ivars.push_back(*I);
998    }
999  }
1000
1001  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1002       E = OI->prop_end(); I != E; ++I) {
1003    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
1004      Ivars.push_back(Ivar);
1005  }
1006  // Also look into interface's protocol list for properties declared
1007  // in the protocol and whose ivars are synthesized.
1008  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1009       PE = OI->protocol_end(); P != PE; ++P) {
1010    ObjCProtocolDecl *PD = (*P);
1011    CollectProtocolSynthesizedIvars(PD, Ivars);
1012  }
1013
1014  // Also add any ivar defined in this class's implementation
1015  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
1016    for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
1017         E = ImplDecl->ivar_end(); I != E; ++I)
1018      Ivars.push_back(*I);
1019  }
1020}
1021
1022/// CollectInheritedProtocols - Collect all protocols in current class and
1023/// those inherited by it.
1024void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1025                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1026  if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1027    for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1028         PE = OI->protocol_end(); P != PE; ++P) {
1029      ObjCProtocolDecl *Proto = (*P);
1030      Protocols.insert(Proto);
1031      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1032           PE = Proto->protocol_end(); P != PE; ++P) {
1033        Protocols.insert(*P);
1034        CollectInheritedProtocols(*P, Protocols);
1035      }
1036    }
1037
1038    // Categories of this Interface.
1039    for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1040         CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1041      CollectInheritedProtocols(CDeclChain, Protocols);
1042    if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1043      while (SD) {
1044        CollectInheritedProtocols(SD, Protocols);
1045        SD = SD->getSuperClass();
1046      }
1047    return;
1048  }
1049  if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1050    for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
1051         PE = OC->protocol_end(); P != PE; ++P) {
1052      ObjCProtocolDecl *Proto = (*P);
1053      Protocols.insert(Proto);
1054      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1055           PE = Proto->protocol_end(); P != PE; ++P)
1056        CollectInheritedProtocols(*P, Protocols);
1057    }
1058    return;
1059  }
1060  if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1061    for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1062         PE = OP->protocol_end(); P != PE; ++P) {
1063      ObjCProtocolDecl *Proto = (*P);
1064      Protocols.insert(Proto);
1065      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1066           PE = Proto->protocol_end(); P != PE; ++P)
1067        CollectInheritedProtocols(*P, Protocols);
1068    }
1069    return;
1070  }
1071}
1072
1073unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
1074  unsigned count = 0;
1075  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
1076       E = PD->prop_end(); I != E; ++I)
1077    if ((*I)->getPropertyIvarDecl())
1078      ++count;
1079
1080  // Also look into nested protocols.
1081  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
1082       E = PD->protocol_end(); P != E; ++P)
1083    count += CountProtocolSynthesizedIvars(*P);
1084  return count;
1085}
1086
1087unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
1088  unsigned count = 0;
1089  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1090       E = OI->prop_end(); I != E; ++I) {
1091    if ((*I)->getPropertyIvarDecl())
1092      ++count;
1093  }
1094  // Also look into interface's protocol list for properties declared
1095  // in the protocol and whose ivars are synthesized.
1096  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1097       PE = OI->protocol_end(); P != PE; ++P) {
1098    ObjCProtocolDecl *PD = (*P);
1099    count += CountProtocolSynthesizedIvars(PD);
1100  }
1101  return count;
1102}
1103
1104/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1105ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1106  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1107    I = ObjCImpls.find(D);
1108  if (I != ObjCImpls.end())
1109    return cast<ObjCImplementationDecl>(I->second);
1110  return 0;
1111}
1112/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1113ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1114  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1115    I = ObjCImpls.find(D);
1116  if (I != ObjCImpls.end())
1117    return cast<ObjCCategoryImplDecl>(I->second);
1118  return 0;
1119}
1120
1121/// \brief Set the implementation of ObjCInterfaceDecl.
1122void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1123                           ObjCImplementationDecl *ImplD) {
1124  assert(IFaceD && ImplD && "Passed null params");
1125  ObjCImpls[IFaceD] = ImplD;
1126}
1127/// \brief Set the implementation of ObjCCategoryDecl.
1128void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1129                           ObjCCategoryImplDecl *ImplD) {
1130  assert(CatD && ImplD && "Passed null params");
1131  ObjCImpls[CatD] = ImplD;
1132}
1133
1134/// \brief Allocate an uninitialized TypeSourceInfo.
1135///
1136/// The caller should initialize the memory held by TypeSourceInfo using
1137/// the TypeLoc wrappers.
1138///
1139/// \param T the type that will be the basis for type source info. This type
1140/// should refer to how the declarator was written in source code, not to
1141/// what type semantic analysis resolved the declarator to.
1142TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1143                                                 unsigned DataSize) {
1144  if (!DataSize)
1145    DataSize = TypeLoc::getFullDataSizeForType(T);
1146  else
1147    assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1148           "incorrect data size provided to CreateTypeSourceInfo!");
1149
1150  TypeSourceInfo *TInfo =
1151    (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1152  new (TInfo) TypeSourceInfo(T);
1153  return TInfo;
1154}
1155
1156TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1157                                                     SourceLocation L) {
1158  TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1159  DI->getTypeLoc().initialize(L);
1160  return DI;
1161}
1162
1163/// getInterfaceLayoutImpl - Get or compute information about the
1164/// layout of the given interface.
1165///
1166/// \param Impl - If given, also include the layout of the interface's
1167/// implementation. This may differ by including synthesized ivars.
1168const ASTRecordLayout &
1169ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1170                          const ObjCImplementationDecl *Impl) {
1171  assert(!D->isForwardDecl() && "Invalid interface decl!");
1172
1173  // Look up this layout, if already laid out, return what we have.
1174  ObjCContainerDecl *Key =
1175    Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1176  if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1177    return *Entry;
1178
1179  // Add in synthesized ivar count if laying out an implementation.
1180  if (Impl) {
1181    unsigned SynthCount = CountSynthesizedIvars(D);
1182    // If there aren't any sythesized ivars then reuse the interface
1183    // entry. Note we can't cache this because we simply free all
1184    // entries later; however we shouldn't look up implementations
1185    // frequently.
1186    if (SynthCount == 0)
1187      return getObjCLayout(D, 0);
1188  }
1189
1190  const ASTRecordLayout *NewEntry =
1191    ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1192  ObjCLayouts[Key] = NewEntry;
1193
1194  return *NewEntry;
1195}
1196
1197const ASTRecordLayout &
1198ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1199  return getObjCLayout(D, 0);
1200}
1201
1202const ASTRecordLayout &
1203ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1204  return getObjCLayout(D->getClassInterface(), D);
1205}
1206
1207/// getASTRecordLayout - Get or compute information about the layout of the
1208/// specified record (struct/union/class), which indicates its size and field
1209/// position information.
1210const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
1211  D = D->getDefinition();
1212  assert(D && "Cannot get layout of forward declarations!");
1213
1214  // Look up this layout, if already laid out, return what we have.
1215  // Note that we can't save a reference to the entry because this function
1216  // is recursive.
1217  const ASTRecordLayout *Entry = ASTRecordLayouts[D];
1218  if (Entry) return *Entry;
1219
1220  const ASTRecordLayout *NewEntry =
1221    ASTRecordLayoutBuilder::ComputeLayout(*this, D);
1222  ASTRecordLayouts[D] = NewEntry;
1223
1224  return *NewEntry;
1225}
1226
1227const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
1228  RD = cast<CXXRecordDecl>(RD->getDefinition());
1229  assert(RD && "Cannot get key function for forward declarations!");
1230
1231  const CXXMethodDecl *&Entry = KeyFunctions[RD];
1232  if (!Entry)
1233    Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1234  else
1235    assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1236           "Key function changed!");
1237
1238  return Entry;
1239}
1240
1241//===----------------------------------------------------------------------===//
1242//                   Type creation/memoization methods
1243//===----------------------------------------------------------------------===//
1244
1245QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1246  unsigned Fast = Quals.getFastQualifiers();
1247  Quals.removeFastQualifiers();
1248
1249  // Check if we've already instantiated this type.
1250  llvm::FoldingSetNodeID ID;
1251  ExtQuals::Profile(ID, TypeNode, Quals);
1252  void *InsertPos = 0;
1253  if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1254    assert(EQ->getQualifiers() == Quals);
1255    QualType T = QualType(EQ, Fast);
1256    return T;
1257  }
1258
1259  ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
1260  ExtQualNodes.InsertNode(New, InsertPos);
1261  QualType T = QualType(New, Fast);
1262  return T;
1263}
1264
1265QualType ASTContext::getVolatileType(QualType T) {
1266  QualType CanT = getCanonicalType(T);
1267  if (CanT.isVolatileQualified()) return T;
1268
1269  QualifierCollector Quals;
1270  const Type *TypeNode = Quals.strip(T);
1271  Quals.addVolatile();
1272
1273  return getExtQualType(TypeNode, Quals);
1274}
1275
1276QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
1277  QualType CanT = getCanonicalType(T);
1278  if (CanT.getAddressSpace() == AddressSpace)
1279    return T;
1280
1281  // If we are composing extended qualifiers together, merge together
1282  // into one ExtQuals node.
1283  QualifierCollector Quals;
1284  const Type *TypeNode = Quals.strip(T);
1285
1286  // If this type already has an address space specified, it cannot get
1287  // another one.
1288  assert(!Quals.hasAddressSpace() &&
1289         "Type cannot be in multiple addr spaces!");
1290  Quals.addAddressSpace(AddressSpace);
1291
1292  return getExtQualType(TypeNode, Quals);
1293}
1294
1295QualType ASTContext::getObjCGCQualType(QualType T,
1296                                       Qualifiers::GC GCAttr) {
1297  QualType CanT = getCanonicalType(T);
1298  if (CanT.getObjCGCAttr() == GCAttr)
1299    return T;
1300
1301  if (T->isPointerType()) {
1302    QualType Pointee = T->getAs<PointerType>()->getPointeeType();
1303    if (Pointee->isAnyPointerType()) {
1304      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1305      return getPointerType(ResultType);
1306    }
1307  }
1308
1309  // If we are composing extended qualifiers together, merge together
1310  // into one ExtQuals node.
1311  QualifierCollector Quals;
1312  const Type *TypeNode = Quals.strip(T);
1313
1314  // If this type already has an ObjCGC specified, it cannot get
1315  // another one.
1316  assert(!Quals.hasObjCGCAttr() &&
1317         "Type cannot have multiple ObjCGCs!");
1318  Quals.addObjCGCAttr(GCAttr);
1319
1320  return getExtQualType(TypeNode, Quals);
1321}
1322
1323static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1324                                        bool AddNoReturn,
1325                                        CallingConv CallConv) {
1326  QualType ResultType;
1327  if (const PointerType *Pointer = T->getAs<PointerType>()) {
1328    QualType Pointee = Pointer->getPointeeType();
1329    ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1330                                         CallConv);
1331    if (ResultType == Pointee)
1332      return T;
1333
1334    ResultType = Context.getPointerType(ResultType);
1335  } else if (const BlockPointerType *BlockPointer
1336                                              = T->getAs<BlockPointerType>()) {
1337    QualType Pointee = BlockPointer->getPointeeType();
1338    ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1339                                         CallConv);
1340    if (ResultType == Pointee)
1341      return T;
1342
1343    ResultType = Context.getBlockPointerType(ResultType);
1344   } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1345    if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
1346      return T;
1347
1348    if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
1349      ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1350                                                  AddNoReturn, CallConv);
1351    } else {
1352      const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
1353      ResultType
1354        = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1355                                  FPT->getNumArgs(), FPT->isVariadic(),
1356                                  FPT->getTypeQuals(),
1357                                  FPT->hasExceptionSpec(),
1358                                  FPT->hasAnyExceptionSpec(),
1359                                  FPT->getNumExceptions(),
1360                                  FPT->exception_begin(),
1361                                  AddNoReturn, CallConv);
1362    }
1363  } else
1364    return T;
1365
1366  return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1367}
1368
1369QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1370  return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1371}
1372
1373QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1374  return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
1375}
1376
1377/// getComplexType - Return the uniqued reference to the type for a complex
1378/// number with the specified element type.
1379QualType ASTContext::getComplexType(QualType T) {
1380  // Unique pointers, to guarantee there is only one pointer of a particular
1381  // structure.
1382  llvm::FoldingSetNodeID ID;
1383  ComplexType::Profile(ID, T);
1384
1385  void *InsertPos = 0;
1386  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1387    return QualType(CT, 0);
1388
1389  // If the pointee type isn't canonical, this won't be a canonical type either,
1390  // so fill in the canonical type field.
1391  QualType Canonical;
1392  if (!T.isCanonical()) {
1393    Canonical = getComplexType(getCanonicalType(T));
1394
1395    // Get the new insert position for the node we care about.
1396    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1397    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1398  }
1399  ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
1400  Types.push_back(New);
1401  ComplexTypes.InsertNode(New, InsertPos);
1402  return QualType(New, 0);
1403}
1404
1405/// getPointerType - Return the uniqued reference to the type for a pointer to
1406/// the specified type.
1407QualType ASTContext::getPointerType(QualType T) {
1408  // Unique pointers, to guarantee there is only one pointer of a particular
1409  // structure.
1410  llvm::FoldingSetNodeID ID;
1411  PointerType::Profile(ID, T);
1412
1413  void *InsertPos = 0;
1414  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1415    return QualType(PT, 0);
1416
1417  // If the pointee type isn't canonical, this won't be a canonical type either,
1418  // so fill in the canonical type field.
1419  QualType Canonical;
1420  if (!T.isCanonical()) {
1421    Canonical = getPointerType(getCanonicalType(T));
1422
1423    // Get the new insert position for the node we care about.
1424    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1425    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1426  }
1427  PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
1428  Types.push_back(New);
1429  PointerTypes.InsertNode(New, InsertPos);
1430  return QualType(New, 0);
1431}
1432
1433/// getBlockPointerType - Return the uniqued reference to the type for
1434/// a pointer to the specified block.
1435QualType ASTContext::getBlockPointerType(QualType T) {
1436  assert(T->isFunctionType() && "block of function types only");
1437  // Unique pointers, to guarantee there is only one block of a particular
1438  // structure.
1439  llvm::FoldingSetNodeID ID;
1440  BlockPointerType::Profile(ID, T);
1441
1442  void *InsertPos = 0;
1443  if (BlockPointerType *PT =
1444        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1445    return QualType(PT, 0);
1446
1447  // If the block pointee type isn't canonical, this won't be a canonical
1448  // type either so fill in the canonical type field.
1449  QualType Canonical;
1450  if (!T.isCanonical()) {
1451    Canonical = getBlockPointerType(getCanonicalType(T));
1452
1453    // Get the new insert position for the node we care about.
1454    BlockPointerType *NewIP =
1455      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1456    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1457  }
1458  BlockPointerType *New
1459    = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
1460  Types.push_back(New);
1461  BlockPointerTypes.InsertNode(New, InsertPos);
1462  return QualType(New, 0);
1463}
1464
1465/// getLValueReferenceType - Return the uniqued reference to the type for an
1466/// lvalue reference to the specified type.
1467QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
1468  // Unique pointers, to guarantee there is only one pointer of a particular
1469  // structure.
1470  llvm::FoldingSetNodeID ID;
1471  ReferenceType::Profile(ID, T, SpelledAsLValue);
1472
1473  void *InsertPos = 0;
1474  if (LValueReferenceType *RT =
1475        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1476    return QualType(RT, 0);
1477
1478  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1479
1480  // If the referencee type isn't canonical, this won't be a canonical type
1481  // either, so fill in the canonical type field.
1482  QualType Canonical;
1483  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1484    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1485    Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
1486
1487    // Get the new insert position for the node we care about.
1488    LValueReferenceType *NewIP =
1489      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1490    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1491  }
1492
1493  LValueReferenceType *New
1494    = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1495                                                     SpelledAsLValue);
1496  Types.push_back(New);
1497  LValueReferenceTypes.InsertNode(New, InsertPos);
1498
1499  return QualType(New, 0);
1500}
1501
1502/// getRValueReferenceType - Return the uniqued reference to the type for an
1503/// rvalue reference to the specified type.
1504QualType ASTContext::getRValueReferenceType(QualType T) {
1505  // Unique pointers, to guarantee there is only one pointer of a particular
1506  // structure.
1507  llvm::FoldingSetNodeID ID;
1508  ReferenceType::Profile(ID, T, false);
1509
1510  void *InsertPos = 0;
1511  if (RValueReferenceType *RT =
1512        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1513    return QualType(RT, 0);
1514
1515  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1516
1517  // If the referencee type isn't canonical, this won't be a canonical type
1518  // either, so fill in the canonical type field.
1519  QualType Canonical;
1520  if (InnerRef || !T.isCanonical()) {
1521    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1522    Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
1523
1524    // Get the new insert position for the node we care about.
1525    RValueReferenceType *NewIP =
1526      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1527    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1528  }
1529
1530  RValueReferenceType *New
1531    = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
1532  Types.push_back(New);
1533  RValueReferenceTypes.InsertNode(New, InsertPos);
1534  return QualType(New, 0);
1535}
1536
1537/// getMemberPointerType - Return the uniqued reference to the type for a
1538/// member pointer to the specified type, in the specified class.
1539QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
1540  // Unique pointers, to guarantee there is only one pointer of a particular
1541  // structure.
1542  llvm::FoldingSetNodeID ID;
1543  MemberPointerType::Profile(ID, T, Cls);
1544
1545  void *InsertPos = 0;
1546  if (MemberPointerType *PT =
1547      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1548    return QualType(PT, 0);
1549
1550  // If the pointee or class type isn't canonical, this won't be a canonical
1551  // type either, so fill in the canonical type field.
1552  QualType Canonical;
1553  if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
1554    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1555
1556    // Get the new insert position for the node we care about.
1557    MemberPointerType *NewIP =
1558      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1559    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1560  }
1561  MemberPointerType *New
1562    = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
1563  Types.push_back(New);
1564  MemberPointerTypes.InsertNode(New, InsertPos);
1565  return QualType(New, 0);
1566}
1567
1568/// getConstantArrayType - Return the unique reference to the type for an
1569/// array of the specified element type.
1570QualType ASTContext::getConstantArrayType(QualType EltTy,
1571                                          const llvm::APInt &ArySizeIn,
1572                                          ArrayType::ArraySizeModifier ASM,
1573                                          unsigned EltTypeQuals) {
1574  assert((EltTy->isDependentType() ||
1575          EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
1576         "Constant array of VLAs is illegal!");
1577
1578  // Convert the array size into a canonical width matching the pointer size for
1579  // the target.
1580  llvm::APInt ArySize(ArySizeIn);
1581  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1582
1583  llvm::FoldingSetNodeID ID;
1584  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
1585
1586  void *InsertPos = 0;
1587  if (ConstantArrayType *ATP =
1588      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1589    return QualType(ATP, 0);
1590
1591  // If the element type isn't canonical, this won't be a canonical type either,
1592  // so fill in the canonical type field.
1593  QualType Canonical;
1594  if (!EltTy.isCanonical()) {
1595    Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
1596                                     ASM, EltTypeQuals);
1597    // Get the new insert position for the node we care about.
1598    ConstantArrayType *NewIP =
1599      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1600    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1601  }
1602
1603  ConstantArrayType *New = new(*this,TypeAlignment)
1604    ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
1605  ConstantArrayTypes.InsertNode(New, InsertPos);
1606  Types.push_back(New);
1607  return QualType(New, 0);
1608}
1609
1610/// getVariableArrayType - Returns a non-unique reference to the type for a
1611/// variable array of the specified element type.
1612QualType ASTContext::getVariableArrayType(QualType EltTy,
1613                                          Expr *NumElts,
1614                                          ArrayType::ArraySizeModifier ASM,
1615                                          unsigned EltTypeQuals,
1616                                          SourceRange Brackets) {
1617  // Since we don't unique expressions, it isn't possible to unique VLA's
1618  // that have an expression provided for their size.
1619
1620  VariableArrayType *New = new(*this, TypeAlignment)
1621    VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
1622
1623  VariableArrayTypes.push_back(New);
1624  Types.push_back(New);
1625  return QualType(New, 0);
1626}
1627
1628/// getDependentSizedArrayType - Returns a non-unique reference to
1629/// the type for a dependently-sized array of the specified element
1630/// type.
1631QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1632                                                Expr *NumElts,
1633                                                ArrayType::ArraySizeModifier ASM,
1634                                                unsigned EltTypeQuals,
1635                                                SourceRange Brackets) {
1636  assert((!NumElts || NumElts->isTypeDependent() ||
1637          NumElts->isValueDependent()) &&
1638         "Size must be type- or value-dependent!");
1639
1640  void *InsertPos = 0;
1641  DependentSizedArrayType *Canon = 0;
1642  llvm::FoldingSetNodeID ID;
1643
1644  if (NumElts) {
1645    // Dependently-sized array types that do not have a specified
1646    // number of elements will have their sizes deduced from an
1647    // initializer.
1648    DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1649                                     EltTypeQuals, NumElts);
1650
1651    Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1652  }
1653
1654  DependentSizedArrayType *New;
1655  if (Canon) {
1656    // We already have a canonical version of this array type; use it as
1657    // the canonical type for a newly-built type.
1658    New = new (*this, TypeAlignment)
1659      DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1660                              NumElts, ASM, EltTypeQuals, Brackets);
1661  } else {
1662    QualType CanonEltTy = getCanonicalType(EltTy);
1663    if (CanonEltTy == EltTy) {
1664      New = new (*this, TypeAlignment)
1665        DependentSizedArrayType(*this, EltTy, QualType(),
1666                                NumElts, ASM, EltTypeQuals, Brackets);
1667
1668      if (NumElts) {
1669        DependentSizedArrayType *CanonCheck
1670          = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1671        assert(!CanonCheck && "Dependent-sized canonical array type broken");
1672        (void)CanonCheck;
1673        DependentSizedArrayTypes.InsertNode(New, InsertPos);
1674      }
1675    } else {
1676      QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1677                                                  ASM, EltTypeQuals,
1678                                                  SourceRange());
1679      New = new (*this, TypeAlignment)
1680        DependentSizedArrayType(*this, EltTy, Canon,
1681                                NumElts, ASM, EltTypeQuals, Brackets);
1682    }
1683  }
1684
1685  Types.push_back(New);
1686  return QualType(New, 0);
1687}
1688
1689QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1690                                            ArrayType::ArraySizeModifier ASM,
1691                                            unsigned EltTypeQuals) {
1692  llvm::FoldingSetNodeID ID;
1693  IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
1694
1695  void *InsertPos = 0;
1696  if (IncompleteArrayType *ATP =
1697       IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1698    return QualType(ATP, 0);
1699
1700  // If the element type isn't canonical, this won't be a canonical type
1701  // either, so fill in the canonical type field.
1702  QualType Canonical;
1703
1704  if (!EltTy.isCanonical()) {
1705    Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
1706                                       ASM, EltTypeQuals);
1707
1708    // Get the new insert position for the node we care about.
1709    IncompleteArrayType *NewIP =
1710      IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1711    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1712  }
1713
1714  IncompleteArrayType *New = new (*this, TypeAlignment)
1715    IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
1716
1717  IncompleteArrayTypes.InsertNode(New, InsertPos);
1718  Types.push_back(New);
1719  return QualType(New, 0);
1720}
1721
1722/// getVectorType - Return the unique reference to a vector type of
1723/// the specified element type and size. VectorType must be a built-in type.
1724QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1725                                   bool IsAltiVec, bool IsPixel) {
1726  BuiltinType *baseType;
1727
1728  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1729  assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1730
1731  // Check if we've already instantiated a vector of this type.
1732  llvm::FoldingSetNodeID ID;
1733  VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1734    IsAltiVec, IsPixel);
1735  void *InsertPos = 0;
1736  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1737    return QualType(VTP, 0);
1738
1739  // If the element type isn't canonical, this won't be a canonical type either,
1740  // so fill in the canonical type field.
1741  QualType Canonical;
1742  if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1743    Canonical = getVectorType(getCanonicalType(vecType),
1744      NumElts, false, false);
1745
1746    // Get the new insert position for the node we care about.
1747    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1748    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1749  }
1750  VectorType *New = new (*this, TypeAlignment)
1751    VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
1752  VectorTypes.InsertNode(New, InsertPos);
1753  Types.push_back(New);
1754  return QualType(New, 0);
1755}
1756
1757/// getExtVectorType - Return the unique reference to an extended vector type of
1758/// the specified element type and size. VectorType must be a built-in type.
1759QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
1760  BuiltinType *baseType;
1761
1762  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1763  assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
1764
1765  // Check if we've already instantiated a vector of this type.
1766  llvm::FoldingSetNodeID ID;
1767  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
1768  void *InsertPos = 0;
1769  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1770    return QualType(VTP, 0);
1771
1772  // If the element type isn't canonical, this won't be a canonical type either,
1773  // so fill in the canonical type field.
1774  QualType Canonical;
1775  if (!vecType.isCanonical()) {
1776    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1777
1778    // Get the new insert position for the node we care about.
1779    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1780    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1781  }
1782  ExtVectorType *New = new (*this, TypeAlignment)
1783    ExtVectorType(vecType, NumElts, Canonical);
1784  VectorTypes.InsertNode(New, InsertPos);
1785  Types.push_back(New);
1786  return QualType(New, 0);
1787}
1788
1789QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1790                                                    Expr *SizeExpr,
1791                                                    SourceLocation AttrLoc) {
1792  llvm::FoldingSetNodeID ID;
1793  DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
1794                                       SizeExpr);
1795
1796  void *InsertPos = 0;
1797  DependentSizedExtVectorType *Canon
1798    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1799  DependentSizedExtVectorType *New;
1800  if (Canon) {
1801    // We already have a canonical version of this array type; use it as
1802    // the canonical type for a newly-built type.
1803    New = new (*this, TypeAlignment)
1804      DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1805                                  SizeExpr, AttrLoc);
1806  } else {
1807    QualType CanonVecTy = getCanonicalType(vecType);
1808    if (CanonVecTy == vecType) {
1809      New = new (*this, TypeAlignment)
1810        DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1811                                    AttrLoc);
1812
1813      DependentSizedExtVectorType *CanonCheck
1814        = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1815      assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1816      (void)CanonCheck;
1817      DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1818    } else {
1819      QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1820                                                      SourceLocation());
1821      New = new (*this, TypeAlignment)
1822        DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
1823    }
1824  }
1825
1826  Types.push_back(New);
1827  return QualType(New, 0);
1828}
1829
1830/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1831///
1832QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1833                                            CallingConv CallConv) {
1834  // Unique functions, to guarantee there is only one function of a particular
1835  // structure.
1836  llvm::FoldingSetNodeID ID;
1837  FunctionNoProtoType::Profile(ID, ResultTy, NoReturn, CallConv);
1838
1839  void *InsertPos = 0;
1840  if (FunctionNoProtoType *FT =
1841        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1842    return QualType(FT, 0);
1843
1844  QualType Canonical;
1845  if (!ResultTy.isCanonical() ||
1846      getCanonicalCallConv(CallConv) != CallConv) {
1847    Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
1848                                       getCanonicalCallConv(CallConv));
1849
1850    // Get the new insert position for the node we care about.
1851    FunctionNoProtoType *NewIP =
1852      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1853    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1854  }
1855
1856  FunctionNoProtoType *New = new (*this, TypeAlignment)
1857    FunctionNoProtoType(ResultTy, Canonical, NoReturn, CallConv);
1858  Types.push_back(New);
1859  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1860  return QualType(New, 0);
1861}
1862
1863/// getFunctionType - Return a normal function type with a typed argument
1864/// list.  isVariadic indicates whether the argument list includes '...'.
1865QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
1866                                     unsigned NumArgs, bool isVariadic,
1867                                     unsigned TypeQuals, bool hasExceptionSpec,
1868                                     bool hasAnyExceptionSpec, unsigned NumExs,
1869                                     const QualType *ExArray, bool NoReturn,
1870                                     CallingConv CallConv) {
1871  // Unique functions, to guarantee there is only one function of a particular
1872  // structure.
1873  llvm::FoldingSetNodeID ID;
1874  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
1875                             TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1876                             NumExs, ExArray, NoReturn, CallConv);
1877
1878  void *InsertPos = 0;
1879  if (FunctionProtoType *FTP =
1880        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1881    return QualType(FTP, 0);
1882
1883  // Determine whether the type being created is already canonical or not.
1884  bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
1885  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1886    if (!ArgArray[i].isCanonicalAsParam())
1887      isCanonical = false;
1888
1889  // If this type isn't canonical, get the canonical version of it.
1890  // The exception spec is not part of the canonical type.
1891  QualType Canonical;
1892  if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
1893    llvm::SmallVector<QualType, 16> CanonicalArgs;
1894    CanonicalArgs.reserve(NumArgs);
1895    for (unsigned i = 0; i != NumArgs; ++i)
1896      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
1897
1898    Canonical = getFunctionType(getCanonicalType(ResultTy),
1899                                CanonicalArgs.data(), NumArgs,
1900                                isVariadic, TypeQuals, false,
1901                                false, 0, 0, NoReturn,
1902                                getCanonicalCallConv(CallConv));
1903
1904    // Get the new insert position for the node we care about.
1905    FunctionProtoType *NewIP =
1906      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1907    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1908  }
1909
1910  // FunctionProtoType objects are allocated with extra bytes after them
1911  // for two variable size arrays (for parameter and exception types) at the
1912  // end of them.
1913  FunctionProtoType *FTP =
1914    (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1915                                 NumArgs*sizeof(QualType) +
1916                                 NumExs*sizeof(QualType), TypeAlignment);
1917  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
1918                              TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1919                              ExArray, NumExs, Canonical, NoReturn, CallConv);
1920  Types.push_back(FTP);
1921  FunctionProtoTypes.InsertNode(FTP, InsertPos);
1922  return QualType(FTP, 0);
1923}
1924
1925#ifndef NDEBUG
1926static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1927  if (!isa<CXXRecordDecl>(D)) return false;
1928  const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1929  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1930    return true;
1931  if (RD->getDescribedClassTemplate() &&
1932      !isa<ClassTemplateSpecializationDecl>(RD))
1933    return true;
1934  return false;
1935}
1936#endif
1937
1938/// getInjectedClassNameType - Return the unique reference to the
1939/// injected class name type for the specified templated declaration.
1940QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1941                                              QualType TST) {
1942  assert(NeedsInjectedClassNameType(Decl));
1943  if (Decl->TypeForDecl) {
1944    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1945  } else if (CXXRecordDecl *PrevDecl
1946               = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1947    assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1948    Decl->TypeForDecl = PrevDecl->TypeForDecl;
1949    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1950  } else {
1951    Decl->TypeForDecl = new (*this, TypeAlignment)
1952      InjectedClassNameType(Decl, TST, TST->getCanonicalTypeInternal());
1953    Types.push_back(Decl->TypeForDecl);
1954  }
1955  return QualType(Decl->TypeForDecl, 0);
1956}
1957
1958/// getTypeDeclType - Return the unique reference to the type for the
1959/// specified type declaration.
1960QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
1961  assert(Decl && "Passed null for Decl param");
1962  assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
1963
1964  if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
1965    return getTypedefType(Typedef);
1966
1967  if (const ObjCInterfaceDecl *ObjCInterface
1968               = dyn_cast<ObjCInterfaceDecl>(Decl))
1969    return getObjCInterfaceType(ObjCInterface);
1970
1971  assert(!isa<TemplateTypeParmDecl>(Decl) &&
1972         "Template type parameter types are always available.");
1973
1974  if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
1975    assert(!Record->getPreviousDeclaration() &&
1976           "struct/union has previous declaration");
1977    assert(!NeedsInjectedClassNameType(Record));
1978    Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
1979  } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1980    assert(!Enum->getPreviousDeclaration() &&
1981           "enum has previous declaration");
1982    Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
1983  } else if (const UnresolvedUsingTypenameDecl *Using =
1984               dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1985    Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
1986  } else
1987    llvm_unreachable("TypeDecl without a type?");
1988
1989  Types.push_back(Decl->TypeForDecl);
1990  return QualType(Decl->TypeForDecl, 0);
1991}
1992
1993/// getTypedefType - Return the unique reference to the type for the
1994/// specified typename decl.
1995QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
1996  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1997
1998  QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
1999  Decl->TypeForDecl = new(*this, TypeAlignment)
2000    TypedefType(Type::Typedef, Decl, Canonical);
2001  Types.push_back(Decl->TypeForDecl);
2002  return QualType(Decl->TypeForDecl, 0);
2003}
2004
2005/// \brief Retrieve a substitution-result type.
2006QualType
2007ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
2008                                         QualType Replacement) {
2009  assert(Replacement.isCanonical()
2010         && "replacement types must always be canonical");
2011
2012  llvm::FoldingSetNodeID ID;
2013  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2014  void *InsertPos = 0;
2015  SubstTemplateTypeParmType *SubstParm
2016    = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2017
2018  if (!SubstParm) {
2019    SubstParm = new (*this, TypeAlignment)
2020      SubstTemplateTypeParmType(Parm, Replacement);
2021    Types.push_back(SubstParm);
2022    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2023  }
2024
2025  return QualType(SubstParm, 0);
2026}
2027
2028/// \brief Retrieve the template type parameter type for a template
2029/// parameter or parameter pack with the given depth, index, and (optionally)
2030/// name.
2031QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
2032                                             bool ParameterPack,
2033                                             IdentifierInfo *Name) {
2034  llvm::FoldingSetNodeID ID;
2035  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
2036  void *InsertPos = 0;
2037  TemplateTypeParmType *TypeParm
2038    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2039
2040  if (TypeParm)
2041    return QualType(TypeParm, 0);
2042
2043  if (Name) {
2044    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
2045    TypeParm = new (*this, TypeAlignment)
2046      TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
2047
2048    TemplateTypeParmType *TypeCheck
2049      = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2050    assert(!TypeCheck && "Template type parameter canonical type broken");
2051    (void)TypeCheck;
2052  } else
2053    TypeParm = new (*this, TypeAlignment)
2054      TemplateTypeParmType(Depth, Index, ParameterPack);
2055
2056  Types.push_back(TypeParm);
2057  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2058
2059  return QualType(TypeParm, 0);
2060}
2061
2062TypeSourceInfo *
2063ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2064                                              SourceLocation NameLoc,
2065                                        const TemplateArgumentListInfo &Args,
2066                                              QualType CanonType) {
2067  QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2068
2069  TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2070  TemplateSpecializationTypeLoc TL
2071    = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2072  TL.setTemplateNameLoc(NameLoc);
2073  TL.setLAngleLoc(Args.getLAngleLoc());
2074  TL.setRAngleLoc(Args.getRAngleLoc());
2075  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2076    TL.setArgLocInfo(i, Args[i].getLocInfo());
2077  return DI;
2078}
2079
2080QualType
2081ASTContext::getTemplateSpecializationType(TemplateName Template,
2082                                          const TemplateArgumentListInfo &Args,
2083                                          QualType Canon) {
2084  unsigned NumArgs = Args.size();
2085
2086  llvm::SmallVector<TemplateArgument, 4> ArgVec;
2087  ArgVec.reserve(NumArgs);
2088  for (unsigned i = 0; i != NumArgs; ++i)
2089    ArgVec.push_back(Args[i].getArgument());
2090
2091  return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
2092}
2093
2094QualType
2095ASTContext::getTemplateSpecializationType(TemplateName Template,
2096                                          const TemplateArgument *Args,
2097                                          unsigned NumArgs,
2098                                          QualType Canon) {
2099  if (!Canon.isNull())
2100    Canon = getCanonicalType(Canon);
2101  else {
2102    // Build the canonical template specialization type.
2103    TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2104    llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2105    CanonArgs.reserve(NumArgs);
2106    for (unsigned I = 0; I != NumArgs; ++I)
2107      CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2108
2109    // Determine whether this canonical template specialization type already
2110    // exists.
2111    llvm::FoldingSetNodeID ID;
2112    TemplateSpecializationType::Profile(ID, CanonTemplate,
2113                                        CanonArgs.data(), NumArgs, *this);
2114
2115    void *InsertPos = 0;
2116    TemplateSpecializationType *Spec
2117      = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2118
2119    if (!Spec) {
2120      // Allocate a new canonical template specialization type.
2121      void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2122                            sizeof(TemplateArgument) * NumArgs),
2123                           TypeAlignment);
2124      Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
2125                                                  CanonArgs.data(), NumArgs,
2126                                                  Canon);
2127      Types.push_back(Spec);
2128      TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2129    }
2130
2131    if (Canon.isNull())
2132      Canon = QualType(Spec, 0);
2133    assert(Canon->isDependentType() &&
2134           "Non-dependent template-id type must have a canonical type");
2135  }
2136
2137  // Allocate the (non-canonical) template specialization type, but don't
2138  // try to unique it: these types typically have location information that
2139  // we don't unique and don't want to lose.
2140  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2141                        sizeof(TemplateArgument) * NumArgs),
2142                       TypeAlignment);
2143  TemplateSpecializationType *Spec
2144    = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
2145                                           Canon);
2146
2147  Types.push_back(Spec);
2148  return QualType(Spec, 0);
2149}
2150
2151QualType
2152ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
2153                                 QualType NamedType) {
2154  llvm::FoldingSetNodeID ID;
2155  QualifiedNameType::Profile(ID, NNS, NamedType);
2156
2157  void *InsertPos = 0;
2158  QualifiedNameType *T
2159    = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2160  if (T)
2161    return QualType(T, 0);
2162
2163  QualType Canon = NamedType;
2164  if (!Canon.isCanonical()) {
2165    Canon = getCanonicalType(NamedType);
2166    QualifiedNameType *CheckT
2167      = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2168    assert(!CheckT && "Qualified name canonical type broken");
2169    (void)CheckT;
2170  }
2171
2172  T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
2173  Types.push_back(T);
2174  QualifiedNameTypes.InsertNode(T, InsertPos);
2175  return QualType(T, 0);
2176}
2177
2178QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
2179                                     const IdentifierInfo *Name,
2180                                     QualType Canon) {
2181  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2182
2183  if (Canon.isNull()) {
2184    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2185    if (CanonNNS != NNS)
2186      Canon = getTypenameType(CanonNNS, Name);
2187  }
2188
2189  llvm::FoldingSetNodeID ID;
2190  TypenameType::Profile(ID, NNS, Name);
2191
2192  void *InsertPos = 0;
2193  TypenameType *T
2194    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2195  if (T)
2196    return QualType(T, 0);
2197
2198  T = new (*this) TypenameType(NNS, Name, Canon);
2199  Types.push_back(T);
2200  TypenameTypes.InsertNode(T, InsertPos);
2201  return QualType(T, 0);
2202}
2203
2204QualType
2205ASTContext::getTypenameType(NestedNameSpecifier *NNS,
2206                            const TemplateSpecializationType *TemplateId,
2207                            QualType Canon) {
2208  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2209
2210  llvm::FoldingSetNodeID ID;
2211  TypenameType::Profile(ID, NNS, TemplateId);
2212
2213  void *InsertPos = 0;
2214  TypenameType *T
2215    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2216  if (T)
2217    return QualType(T, 0);
2218
2219  if (Canon.isNull()) {
2220    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2221    QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2222    if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2223      const TemplateSpecializationType *CanonTemplateId
2224        = CanonType->getAs<TemplateSpecializationType>();
2225      assert(CanonTemplateId &&
2226             "Canonical type must also be a template specialization type");
2227      Canon = getTypenameType(CanonNNS, CanonTemplateId);
2228    }
2229
2230    TypenameType *CheckT
2231      = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2232    assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
2233  }
2234
2235  T = new (*this) TypenameType(NNS, TemplateId, Canon);
2236  Types.push_back(T);
2237  TypenameTypes.InsertNode(T, InsertPos);
2238  return QualType(T, 0);
2239}
2240
2241QualType
2242ASTContext::getElaboratedType(QualType UnderlyingType,
2243                              ElaboratedType::TagKind Tag) {
2244  llvm::FoldingSetNodeID ID;
2245  ElaboratedType::Profile(ID, UnderlyingType, Tag);
2246
2247  void *InsertPos = 0;
2248  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2249  if (T)
2250    return QualType(T, 0);
2251
2252  QualType Canon = UnderlyingType;
2253  if (!Canon.isCanonical()) {
2254    Canon = getCanonicalType(Canon);
2255    ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2256    assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2257  }
2258
2259  T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2260  Types.push_back(T);
2261  ElaboratedTypes.InsertNode(T, InsertPos);
2262  return QualType(T, 0);
2263}
2264
2265/// CmpProtocolNames - Comparison predicate for sorting protocols
2266/// alphabetically.
2267static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2268                            const ObjCProtocolDecl *RHS) {
2269  return LHS->getDeclName() < RHS->getDeclName();
2270}
2271
2272static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2273                                unsigned NumProtocols) {
2274  if (NumProtocols == 0) return true;
2275
2276  for (unsigned i = 1; i != NumProtocols; ++i)
2277    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2278      return false;
2279  return true;
2280}
2281
2282static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
2283                                   unsigned &NumProtocols) {
2284  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
2285
2286  // Sort protocols, keyed by name.
2287  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2288
2289  // Remove duplicates.
2290  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2291  NumProtocols = ProtocolsEnd-Protocols;
2292}
2293
2294/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2295/// the given interface decl and the conforming protocol list.
2296QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
2297                                              ObjCProtocolDecl **Protocols,
2298                                              unsigned NumProtocols,
2299                                              unsigned Quals) {
2300  llvm::FoldingSetNodeID ID;
2301  ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
2302  Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
2303
2304  void *InsertPos = 0;
2305  if (ObjCObjectPointerType *QT =
2306              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2307    return getQualifiedType(QualType(QT, 0), Qs);
2308
2309  // Sort the protocol list alphabetically to canonicalize it.
2310  QualType Canonical;
2311  if (!InterfaceT.isCanonical() ||
2312      !areSortedAndUniqued(Protocols, NumProtocols)) {
2313    if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2314      llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2315      unsigned UniqueCount = NumProtocols;
2316
2317      std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2318      SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2319
2320      Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2321                                           &Sorted[0], UniqueCount);
2322    } else {
2323      Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2324                                           Protocols, NumProtocols);
2325    }
2326
2327    // Regenerate InsertPos.
2328    ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2329  }
2330
2331  // No match.
2332  unsigned Size = sizeof(ObjCObjectPointerType)
2333                + NumProtocols * sizeof(ObjCProtocolDecl *);
2334  void *Mem = Allocate(Size, TypeAlignment);
2335  ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2336                                                                 InterfaceT,
2337                                                                 Protocols,
2338                                                                 NumProtocols);
2339
2340  Types.push_back(QType);
2341  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2342  return getQualifiedType(QualType(QType, 0), Qs);
2343}
2344
2345/// getObjCInterfaceType - Return the unique reference to the type for the
2346/// specified ObjC interface decl. The list of protocols is optional.
2347QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2348                       ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
2349  llvm::FoldingSetNodeID ID;
2350  ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
2351
2352  void *InsertPos = 0;
2353  if (ObjCInterfaceType *QT =
2354      ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
2355    return QualType(QT, 0);
2356
2357  // Sort the protocol list alphabetically to canonicalize it.
2358  QualType Canonical;
2359  if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2360    llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2361    std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2362
2363    unsigned UniqueCount = NumProtocols;
2364    SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2365
2366    Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2367
2368    ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2369  }
2370
2371  unsigned Size = sizeof(ObjCInterfaceType)
2372    + NumProtocols * sizeof(ObjCProtocolDecl *);
2373  void *Mem = Allocate(Size, TypeAlignment);
2374  ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2375                                        const_cast<ObjCInterfaceDecl*>(Decl),
2376                                                         Protocols,
2377                                                         NumProtocols);
2378
2379  Types.push_back(QType);
2380  ObjCInterfaceTypes.InsertNode(QType, InsertPos);
2381  return QualType(QType, 0);
2382}
2383
2384/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2385/// TypeOfExprType AST's (since expression's are never shared). For example,
2386/// multiple declarations that refer to "typeof(x)" all contain different
2387/// DeclRefExpr's. This doesn't effect the type checker, since it operates
2388/// on canonical type's (which are always unique).
2389QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
2390  TypeOfExprType *toe;
2391  if (tofExpr->isTypeDependent()) {
2392    llvm::FoldingSetNodeID ID;
2393    DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2394
2395    void *InsertPos = 0;
2396    DependentTypeOfExprType *Canon
2397      = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2398    if (Canon) {
2399      // We already have a "canonical" version of an identical, dependent
2400      // typeof(expr) type. Use that as our canonical type.
2401      toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
2402                                          QualType((TypeOfExprType*)Canon, 0));
2403    }
2404    else {
2405      // Build a new, canonical typeof(expr) type.
2406      Canon
2407        = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
2408      DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2409      toe = Canon;
2410    }
2411  } else {
2412    QualType Canonical = getCanonicalType(tofExpr->getType());
2413    toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
2414  }
2415  Types.push_back(toe);
2416  return QualType(toe, 0);
2417}
2418
2419/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
2420/// TypeOfType AST's. The only motivation to unique these nodes would be
2421/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2422/// an issue. This doesn't effect the type checker, since it operates
2423/// on canonical type's (which are always unique).
2424QualType ASTContext::getTypeOfType(QualType tofType) {
2425  QualType Canonical = getCanonicalType(tofType);
2426  TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
2427  Types.push_back(tot);
2428  return QualType(tot, 0);
2429}
2430
2431/// getDecltypeForExpr - Given an expr, will return the decltype for that
2432/// expression, according to the rules in C++0x [dcl.type.simple]p4
2433static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
2434  if (e->isTypeDependent())
2435    return Context.DependentTy;
2436
2437  // If e is an id expression or a class member access, decltype(e) is defined
2438  // as the type of the entity named by e.
2439  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2440    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2441      return VD->getType();
2442  }
2443  if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2444    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2445      return FD->getType();
2446  }
2447  // If e is a function call or an invocation of an overloaded operator,
2448  // (parentheses around e are ignored), decltype(e) is defined as the
2449  // return type of that function.
2450  if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2451    return CE->getCallReturnType();
2452
2453  QualType T = e->getType();
2454
2455  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2456  // defined as T&, otherwise decltype(e) is defined as T.
2457  if (e->isLvalue(Context) == Expr::LV_Valid)
2458    T = Context.getLValueReferenceType(T);
2459
2460  return T;
2461}
2462
2463/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
2464/// DecltypeType AST's. The only motivation to unique these nodes would be
2465/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2466/// an issue. This doesn't effect the type checker, since it operates
2467/// on canonical type's (which are always unique).
2468QualType ASTContext::getDecltypeType(Expr *e) {
2469  DecltypeType *dt;
2470  if (e->isTypeDependent()) {
2471    llvm::FoldingSetNodeID ID;
2472    DependentDecltypeType::Profile(ID, *this, e);
2473
2474    void *InsertPos = 0;
2475    DependentDecltypeType *Canon
2476      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2477    if (Canon) {
2478      // We already have a "canonical" version of an equivalent, dependent
2479      // decltype type. Use that as our canonical type.
2480      dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
2481                                       QualType((DecltypeType*)Canon, 0));
2482    }
2483    else {
2484      // Build a new, canonical typeof(expr) type.
2485      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
2486      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2487      dt = Canon;
2488    }
2489  } else {
2490    QualType T = getDecltypeForExpr(e, *this);
2491    dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
2492  }
2493  Types.push_back(dt);
2494  return QualType(dt, 0);
2495}
2496
2497/// getTagDeclType - Return the unique reference to the type for the
2498/// specified TagDecl (struct/union/class/enum) decl.
2499QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
2500  assert (Decl);
2501  // FIXME: What is the design on getTagDeclType when it requires casting
2502  // away const?  mutable?
2503  return getTypeDeclType(const_cast<TagDecl*>(Decl));
2504}
2505
2506/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2507/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2508/// needs to agree with the definition in <stddef.h>.
2509CanQualType ASTContext::getSizeType() const {
2510  return getFromTargetType(Target.getSizeType());
2511}
2512
2513/// getSignedWCharType - Return the type of "signed wchar_t".
2514/// Used when in C++, as a GCC extension.
2515QualType ASTContext::getSignedWCharType() const {
2516  // FIXME: derive from "Target" ?
2517  return WCharTy;
2518}
2519
2520/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2521/// Used when in C++, as a GCC extension.
2522QualType ASTContext::getUnsignedWCharType() const {
2523  // FIXME: derive from "Target" ?
2524  return UnsignedIntTy;
2525}
2526
2527/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2528/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2529QualType ASTContext::getPointerDiffType() const {
2530  return getFromTargetType(Target.getPtrDiffType(0));
2531}
2532
2533//===----------------------------------------------------------------------===//
2534//                              Type Operators
2535//===----------------------------------------------------------------------===//
2536
2537CanQualType ASTContext::getCanonicalParamType(QualType T) {
2538  // Push qualifiers into arrays, and then discard any remaining
2539  // qualifiers.
2540  T = getCanonicalType(T);
2541  const Type *Ty = T.getTypePtr();
2542
2543  QualType Result;
2544  if (isa<ArrayType>(Ty)) {
2545    Result = getArrayDecayedType(QualType(Ty,0));
2546  } else if (isa<FunctionType>(Ty)) {
2547    Result = getPointerType(QualType(Ty, 0));
2548  } else {
2549    Result = QualType(Ty, 0);
2550  }
2551
2552  return CanQualType::CreateUnsafe(Result);
2553}
2554
2555/// getCanonicalType - Return the canonical (structural) type corresponding to
2556/// the specified potentially non-canonical type.  The non-canonical version
2557/// of a type may have many "decorated" versions of types.  Decorators can
2558/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2559/// to be free of any of these, allowing two canonical types to be compared
2560/// for exact equality with a simple pointer comparison.
2561CanQualType ASTContext::getCanonicalType(QualType T) {
2562  QualifierCollector Quals;
2563  const Type *Ptr = Quals.strip(T);
2564  QualType CanType = Ptr->getCanonicalTypeInternal();
2565
2566  // The canonical internal type will be the canonical type *except*
2567  // that we push type qualifiers down through array types.
2568
2569  // If there are no new qualifiers to push down, stop here.
2570  if (!Quals.hasQualifiers())
2571    return CanQualType::CreateUnsafe(CanType);
2572
2573  // If the type qualifiers are on an array type, get the canonical
2574  // type of the array with the qualifiers applied to the element
2575  // type.
2576  ArrayType *AT = dyn_cast<ArrayType>(CanType);
2577  if (!AT)
2578    return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
2579
2580  // Get the canonical version of the element with the extra qualifiers on it.
2581  // This can recursively sink qualifiers through multiple levels of arrays.
2582  QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
2583  NewEltTy = getCanonicalType(NewEltTy);
2584
2585  if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2586    return CanQualType::CreateUnsafe(
2587             getConstantArrayType(NewEltTy, CAT->getSize(),
2588                                  CAT->getSizeModifier(),
2589                                  CAT->getIndexTypeCVRQualifiers()));
2590  if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2591    return CanQualType::CreateUnsafe(
2592             getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2593                                    IAT->getIndexTypeCVRQualifiers()));
2594
2595  if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
2596    return CanQualType::CreateUnsafe(
2597             getDependentSizedArrayType(NewEltTy,
2598                                        DSAT->getSizeExpr() ?
2599                                          DSAT->getSizeExpr()->Retain() : 0,
2600                                        DSAT->getSizeModifier(),
2601                                        DSAT->getIndexTypeCVRQualifiers(),
2602                        DSAT->getBracketsRange())->getCanonicalTypeInternal());
2603
2604  VariableArrayType *VAT = cast<VariableArrayType>(AT);
2605  return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
2606                                                        VAT->getSizeExpr() ?
2607                                              VAT->getSizeExpr()->Retain() : 0,
2608                                                        VAT->getSizeModifier(),
2609                                              VAT->getIndexTypeCVRQualifiers(),
2610                                                     VAT->getBracketsRange()));
2611}
2612
2613QualType ASTContext::getUnqualifiedArrayType(QualType T,
2614                                             Qualifiers &Quals) {
2615  Quals = T.getQualifiers();
2616  if (!isa<ArrayType>(T)) {
2617    return T.getUnqualifiedType();
2618  }
2619
2620  const ArrayType *AT = cast<ArrayType>(T);
2621  QualType Elt = AT->getElementType();
2622  QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
2623  if (Elt == UnqualElt)
2624    return T;
2625
2626  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2627    return getConstantArrayType(UnqualElt, CAT->getSize(),
2628                                CAT->getSizeModifier(), 0);
2629  }
2630
2631  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2632    return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2633  }
2634
2635  const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2636  return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2637                                    DSAT->getSizeModifier(), 0,
2638                                    SourceRange());
2639}
2640
2641DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2642  if (TemplateDecl *TD = Name.getAsTemplateDecl())
2643    return TD->getDeclName();
2644
2645  if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2646    if (DTN->isIdentifier()) {
2647      return DeclarationNames.getIdentifier(DTN->getIdentifier());
2648    } else {
2649      return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2650    }
2651  }
2652
2653  OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2654  assert(Storage);
2655  return (*Storage->begin())->getDeclName();
2656}
2657
2658TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2659  // If this template name refers to a template, the canonical
2660  // template name merely stores the template itself.
2661  if (TemplateDecl *Template = Name.getAsTemplateDecl())
2662    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
2663
2664  assert(!Name.getAsOverloadedTemplate());
2665
2666  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2667  assert(DTN && "Non-dependent template names must refer to template decls.");
2668  return DTN->CanonicalTemplateName;
2669}
2670
2671bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2672  X = getCanonicalTemplateName(X);
2673  Y = getCanonicalTemplateName(Y);
2674  return X.getAsVoidPointer() == Y.getAsVoidPointer();
2675}
2676
2677TemplateArgument
2678ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2679  switch (Arg.getKind()) {
2680    case TemplateArgument::Null:
2681      return Arg;
2682
2683    case TemplateArgument::Expression:
2684      return Arg;
2685
2686    case TemplateArgument::Declaration:
2687      return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
2688
2689    case TemplateArgument::Template:
2690      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2691
2692    case TemplateArgument::Integral:
2693      return TemplateArgument(*Arg.getAsIntegral(),
2694                              getCanonicalType(Arg.getIntegralType()));
2695
2696    case TemplateArgument::Type:
2697      return TemplateArgument(getCanonicalType(Arg.getAsType()));
2698
2699    case TemplateArgument::Pack: {
2700      // FIXME: Allocate in ASTContext
2701      TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2702      unsigned Idx = 0;
2703      for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2704                                        AEnd = Arg.pack_end();
2705           A != AEnd; (void)++A, ++Idx)
2706        CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
2707
2708      TemplateArgument Result;
2709      Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2710      return Result;
2711    }
2712  }
2713
2714  // Silence GCC warning
2715  assert(false && "Unhandled template argument kind");
2716  return TemplateArgument();
2717}
2718
2719NestedNameSpecifier *
2720ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2721  if (!NNS)
2722    return 0;
2723
2724  switch (NNS->getKind()) {
2725  case NestedNameSpecifier::Identifier:
2726    // Canonicalize the prefix but keep the identifier the same.
2727    return NestedNameSpecifier::Create(*this,
2728                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2729                                       NNS->getAsIdentifier());
2730
2731  case NestedNameSpecifier::Namespace:
2732    // A namespace is canonical; build a nested-name-specifier with
2733    // this namespace and no prefix.
2734    return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2735
2736  case NestedNameSpecifier::TypeSpec:
2737  case NestedNameSpecifier::TypeSpecWithTemplate: {
2738    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2739    return NestedNameSpecifier::Create(*this, 0,
2740                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2741                                       T.getTypePtr());
2742  }
2743
2744  case NestedNameSpecifier::Global:
2745    // The global specifier is canonical and unique.
2746    return NNS;
2747  }
2748
2749  // Required to silence a GCC warning
2750  return 0;
2751}
2752
2753
2754const ArrayType *ASTContext::getAsArrayType(QualType T) {
2755  // Handle the non-qualified case efficiently.
2756  if (!T.hasLocalQualifiers()) {
2757    // Handle the common positive case fast.
2758    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2759      return AT;
2760  }
2761
2762  // Handle the common negative case fast.
2763  QualType CType = T->getCanonicalTypeInternal();
2764  if (!isa<ArrayType>(CType))
2765    return 0;
2766
2767  // Apply any qualifiers from the array type to the element type.  This
2768  // implements C99 6.7.3p8: "If the specification of an array type includes
2769  // any type qualifiers, the element type is so qualified, not the array type."
2770
2771  // If we get here, we either have type qualifiers on the type, or we have
2772  // sugar such as a typedef in the way.  If we have type qualifiers on the type
2773  // we must propagate them down into the element type.
2774
2775  QualifierCollector Qs;
2776  const Type *Ty = Qs.strip(T.getDesugaredType());
2777
2778  // If we have a simple case, just return now.
2779  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2780  if (ATy == 0 || Qs.empty())
2781    return ATy;
2782
2783  // Otherwise, we have an array and we have qualifiers on it.  Push the
2784  // qualifiers into the array element type and return a new array type.
2785  // Get the canonical version of the element with the extra qualifiers on it.
2786  // This can recursively sink qualifiers through multiple levels of arrays.
2787  QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
2788
2789  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2790    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2791                                                CAT->getSizeModifier(),
2792                                           CAT->getIndexTypeCVRQualifiers()));
2793  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2794    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2795                                                  IAT->getSizeModifier(),
2796                                           IAT->getIndexTypeCVRQualifiers()));
2797
2798  if (const DependentSizedArrayType *DSAT
2799        = dyn_cast<DependentSizedArrayType>(ATy))
2800    return cast<ArrayType>(
2801                     getDependentSizedArrayType(NewEltTy,
2802                                                DSAT->getSizeExpr() ?
2803                                              DSAT->getSizeExpr()->Retain() : 0,
2804                                                DSAT->getSizeModifier(),
2805                                              DSAT->getIndexTypeCVRQualifiers(),
2806                                                DSAT->getBracketsRange()));
2807
2808  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
2809  return cast<ArrayType>(getVariableArrayType(NewEltTy,
2810                                              VAT->getSizeExpr() ?
2811                                              VAT->getSizeExpr()->Retain() : 0,
2812                                              VAT->getSizeModifier(),
2813                                              VAT->getIndexTypeCVRQualifiers(),
2814                                              VAT->getBracketsRange()));
2815}
2816
2817
2818/// getArrayDecayedType - Return the properly qualified result of decaying the
2819/// specified array type to a pointer.  This operation is non-trivial when
2820/// handling typedefs etc.  The canonical type of "T" must be an array type,
2821/// this returns a pointer to a properly qualified element of the array.
2822///
2823/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2824QualType ASTContext::getArrayDecayedType(QualType Ty) {
2825  // Get the element type with 'getAsArrayType' so that we don't lose any
2826  // typedefs in the element type of the array.  This also handles propagation
2827  // of type qualifiers from the array type into the element type if present
2828  // (C99 6.7.3p8).
2829  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2830  assert(PrettyArrayType && "Not an array type!");
2831
2832  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
2833
2834  // int x[restrict 4] ->  int *restrict
2835  return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
2836}
2837
2838QualType ASTContext::getBaseElementType(QualType QT) {
2839  QualifierCollector Qs;
2840  while (true) {
2841    const Type *UT = Qs.strip(QT);
2842    if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2843      QT = AT->getElementType();
2844    } else {
2845      return Qs.apply(QT);
2846    }
2847  }
2848}
2849
2850QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2851  QualType ElemTy = AT->getElementType();
2852
2853  if (const ArrayType *AT = getAsArrayType(ElemTy))
2854    return getBaseElementType(AT);
2855
2856  return ElemTy;
2857}
2858
2859/// getConstantArrayElementCount - Returns number of constant array elements.
2860uint64_t
2861ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
2862  uint64_t ElementCount = 1;
2863  do {
2864    ElementCount *= CA->getSize().getZExtValue();
2865    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2866  } while (CA);
2867  return ElementCount;
2868}
2869
2870/// getFloatingRank - Return a relative rank for floating point types.
2871/// This routine will assert if passed a built-in type that isn't a float.
2872static FloatingRank getFloatingRank(QualType T) {
2873  if (const ComplexType *CT = T->getAs<ComplexType>())
2874    return getFloatingRank(CT->getElementType());
2875
2876  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2877  switch (T->getAs<BuiltinType>()->getKind()) {
2878  default: assert(0 && "getFloatingRank(): not a floating type");
2879  case BuiltinType::Float:      return FloatRank;
2880  case BuiltinType::Double:     return DoubleRank;
2881  case BuiltinType::LongDouble: return LongDoubleRank;
2882  }
2883}
2884
2885/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2886/// point or a complex type (based on typeDomain/typeSize).
2887/// 'typeDomain' is a real floating point or complex type.
2888/// 'typeSize' is a real floating point or complex type.
2889QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2890                                                       QualType Domain) const {
2891  FloatingRank EltRank = getFloatingRank(Size);
2892  if (Domain->isComplexType()) {
2893    switch (EltRank) {
2894    default: assert(0 && "getFloatingRank(): illegal value for rank");
2895    case FloatRank:      return FloatComplexTy;
2896    case DoubleRank:     return DoubleComplexTy;
2897    case LongDoubleRank: return LongDoubleComplexTy;
2898    }
2899  }
2900
2901  assert(Domain->isRealFloatingType() && "Unknown domain!");
2902  switch (EltRank) {
2903  default: assert(0 && "getFloatingRank(): illegal value for rank");
2904  case FloatRank:      return FloatTy;
2905  case DoubleRank:     return DoubleTy;
2906  case LongDoubleRank: return LongDoubleTy;
2907  }
2908}
2909
2910/// getFloatingTypeOrder - Compare the rank of the two specified floating
2911/// point types, ignoring the domain of the type (i.e. 'double' ==
2912/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2913/// LHS < RHS, return -1.
2914int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2915  FloatingRank LHSR = getFloatingRank(LHS);
2916  FloatingRank RHSR = getFloatingRank(RHS);
2917
2918  if (LHSR == RHSR)
2919    return 0;
2920  if (LHSR > RHSR)
2921    return 1;
2922  return -1;
2923}
2924
2925/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2926/// routine will assert if passed a built-in type that isn't an integer or enum,
2927/// or if it is not canonicalized.
2928unsigned ASTContext::getIntegerRank(Type *T) {
2929  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
2930  if (EnumType* ET = dyn_cast<EnumType>(T))
2931    T = ET->getDecl()->getPromotionType().getTypePtr();
2932
2933  if (T->isSpecificBuiltinType(BuiltinType::WChar))
2934    T = getFromTargetType(Target.getWCharType()).getTypePtr();
2935
2936  if (T->isSpecificBuiltinType(BuiltinType::Char16))
2937    T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2938
2939  if (T->isSpecificBuiltinType(BuiltinType::Char32))
2940    T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2941
2942  switch (cast<BuiltinType>(T)->getKind()) {
2943  default: assert(0 && "getIntegerRank(): not a built-in integer");
2944  case BuiltinType::Bool:
2945    return 1 + (getIntWidth(BoolTy) << 3);
2946  case BuiltinType::Char_S:
2947  case BuiltinType::Char_U:
2948  case BuiltinType::SChar:
2949  case BuiltinType::UChar:
2950    return 2 + (getIntWidth(CharTy) << 3);
2951  case BuiltinType::Short:
2952  case BuiltinType::UShort:
2953    return 3 + (getIntWidth(ShortTy) << 3);
2954  case BuiltinType::Int:
2955  case BuiltinType::UInt:
2956    return 4 + (getIntWidth(IntTy) << 3);
2957  case BuiltinType::Long:
2958  case BuiltinType::ULong:
2959    return 5 + (getIntWidth(LongTy) << 3);
2960  case BuiltinType::LongLong:
2961  case BuiltinType::ULongLong:
2962    return 6 + (getIntWidth(LongLongTy) << 3);
2963  case BuiltinType::Int128:
2964  case BuiltinType::UInt128:
2965    return 7 + (getIntWidth(Int128Ty) << 3);
2966  }
2967}
2968
2969/// \brief Whether this is a promotable bitfield reference according
2970/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2971///
2972/// \returns the type this bit-field will promote to, or NULL if no
2973/// promotion occurs.
2974QualType ASTContext::isPromotableBitField(Expr *E) {
2975  FieldDecl *Field = E->getBitField();
2976  if (!Field)
2977    return QualType();
2978
2979  QualType FT = Field->getType();
2980
2981  llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2982  uint64_t BitWidth = BitWidthAP.getZExtValue();
2983  uint64_t IntSize = getTypeSize(IntTy);
2984  // GCC extension compatibility: if the bit-field size is less than or equal
2985  // to the size of int, it gets promoted no matter what its type is.
2986  // For instance, unsigned long bf : 4 gets promoted to signed int.
2987  if (BitWidth < IntSize)
2988    return IntTy;
2989
2990  if (BitWidth == IntSize)
2991    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2992
2993  // Types bigger than int are not subject to promotions, and therefore act
2994  // like the base type.
2995  // FIXME: This doesn't quite match what gcc does, but what gcc does here
2996  // is ridiculous.
2997  return QualType();
2998}
2999
3000/// getPromotedIntegerType - Returns the type that Promotable will
3001/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3002/// integer type.
3003QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
3004  assert(!Promotable.isNull());
3005  assert(Promotable->isPromotableIntegerType());
3006  if (const EnumType *ET = Promotable->getAs<EnumType>())
3007    return ET->getDecl()->getPromotionType();
3008  if (Promotable->isSignedIntegerType())
3009    return IntTy;
3010  uint64_t PromotableSize = getTypeSize(Promotable);
3011  uint64_t IntSize = getTypeSize(IntTy);
3012  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3013  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3014}
3015
3016/// getIntegerTypeOrder - Returns the highest ranked integer type:
3017/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3018/// LHS < RHS, return -1.
3019int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
3020  Type *LHSC = getCanonicalType(LHS).getTypePtr();
3021  Type *RHSC = getCanonicalType(RHS).getTypePtr();
3022  if (LHSC == RHSC) return 0;
3023
3024  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3025  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
3026
3027  unsigned LHSRank = getIntegerRank(LHSC);
3028  unsigned RHSRank = getIntegerRank(RHSC);
3029
3030  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
3031    if (LHSRank == RHSRank) return 0;
3032    return LHSRank > RHSRank ? 1 : -1;
3033  }
3034
3035  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3036  if (LHSUnsigned) {
3037    // If the unsigned [LHS] type is larger, return it.
3038    if (LHSRank >= RHSRank)
3039      return 1;
3040
3041    // If the signed type can represent all values of the unsigned type, it
3042    // wins.  Because we are dealing with 2's complement and types that are
3043    // powers of two larger than each other, this is always safe.
3044    return -1;
3045  }
3046
3047  // If the unsigned [RHS] type is larger, return it.
3048  if (RHSRank >= LHSRank)
3049    return -1;
3050
3051  // If the signed type can represent all values of the unsigned type, it
3052  // wins.  Because we are dealing with 2's complement and types that are
3053  // powers of two larger than each other, this is always safe.
3054  return 1;
3055}
3056
3057static RecordDecl *
3058CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3059                 SourceLocation L, IdentifierInfo *Id) {
3060  if (Ctx.getLangOptions().CPlusPlus)
3061    return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3062  else
3063    return RecordDecl::Create(Ctx, TK, DC, L, Id);
3064}
3065
3066// getCFConstantStringType - Return the type used for constant CFStrings.
3067QualType ASTContext::getCFConstantStringType() {
3068  if (!CFConstantStringTypeDecl) {
3069    CFConstantStringTypeDecl =
3070      CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3071                       &Idents.get("NSConstantString"));
3072    CFConstantStringTypeDecl->startDefinition();
3073
3074    QualType FieldTypes[4];
3075
3076    // const int *isa;
3077    FieldTypes[0] = getPointerType(IntTy.withConst());
3078    // int flags;
3079    FieldTypes[1] = IntTy;
3080    // const char *str;
3081    FieldTypes[2] = getPointerType(CharTy.withConst());
3082    // long length;
3083    FieldTypes[3] = LongTy;
3084
3085    // Create fields
3086    for (unsigned i = 0; i < 4; ++i) {
3087      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
3088                                           SourceLocation(), 0,
3089                                           FieldTypes[i], /*TInfo=*/0,
3090                                           /*BitWidth=*/0,
3091                                           /*Mutable=*/false);
3092      CFConstantStringTypeDecl->addDecl(Field);
3093    }
3094
3095    CFConstantStringTypeDecl->completeDefinition();
3096  }
3097
3098  return getTagDeclType(CFConstantStringTypeDecl);
3099}
3100
3101void ASTContext::setCFConstantStringType(QualType T) {
3102  const RecordType *Rec = T->getAs<RecordType>();
3103  assert(Rec && "Invalid CFConstantStringType");
3104  CFConstantStringTypeDecl = Rec->getDecl();
3105}
3106
3107QualType ASTContext::getObjCFastEnumerationStateType() {
3108  if (!ObjCFastEnumerationStateTypeDecl) {
3109    ObjCFastEnumerationStateTypeDecl =
3110      CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3111                       &Idents.get("__objcFastEnumerationState"));
3112    ObjCFastEnumerationStateTypeDecl->startDefinition();
3113
3114    QualType FieldTypes[] = {
3115      UnsignedLongTy,
3116      getPointerType(ObjCIdTypedefType),
3117      getPointerType(UnsignedLongTy),
3118      getConstantArrayType(UnsignedLongTy,
3119                           llvm::APInt(32, 5), ArrayType::Normal, 0)
3120    };
3121
3122    for (size_t i = 0; i < 4; ++i) {
3123      FieldDecl *Field = FieldDecl::Create(*this,
3124                                           ObjCFastEnumerationStateTypeDecl,
3125                                           SourceLocation(), 0,
3126                                           FieldTypes[i], /*TInfo=*/0,
3127                                           /*BitWidth=*/0,
3128                                           /*Mutable=*/false);
3129      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
3130    }
3131
3132    ObjCFastEnumerationStateTypeDecl->completeDefinition();
3133  }
3134
3135  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3136}
3137
3138QualType ASTContext::getBlockDescriptorType() {
3139  if (BlockDescriptorType)
3140    return getTagDeclType(BlockDescriptorType);
3141
3142  RecordDecl *T;
3143  // FIXME: Needs the FlagAppleBlock bit.
3144  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3145                       &Idents.get("__block_descriptor"));
3146  T->startDefinition();
3147
3148  QualType FieldTypes[] = {
3149    UnsignedLongTy,
3150    UnsignedLongTy,
3151  };
3152
3153  const char *FieldNames[] = {
3154    "reserved",
3155    "Size"
3156  };
3157
3158  for (size_t i = 0; i < 2; ++i) {
3159    FieldDecl *Field = FieldDecl::Create(*this,
3160                                         T,
3161                                         SourceLocation(),
3162                                         &Idents.get(FieldNames[i]),
3163                                         FieldTypes[i], /*TInfo=*/0,
3164                                         /*BitWidth=*/0,
3165                                         /*Mutable=*/false);
3166    T->addDecl(Field);
3167  }
3168
3169  T->completeDefinition();
3170
3171  BlockDescriptorType = T;
3172
3173  return getTagDeclType(BlockDescriptorType);
3174}
3175
3176void ASTContext::setBlockDescriptorType(QualType T) {
3177  const RecordType *Rec = T->getAs<RecordType>();
3178  assert(Rec && "Invalid BlockDescriptorType");
3179  BlockDescriptorType = Rec->getDecl();
3180}
3181
3182QualType ASTContext::getBlockDescriptorExtendedType() {
3183  if (BlockDescriptorExtendedType)
3184    return getTagDeclType(BlockDescriptorExtendedType);
3185
3186  RecordDecl *T;
3187  // FIXME: Needs the FlagAppleBlock bit.
3188  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3189                       &Idents.get("__block_descriptor_withcopydispose"));
3190  T->startDefinition();
3191
3192  QualType FieldTypes[] = {
3193    UnsignedLongTy,
3194    UnsignedLongTy,
3195    getPointerType(VoidPtrTy),
3196    getPointerType(VoidPtrTy)
3197  };
3198
3199  const char *FieldNames[] = {
3200    "reserved",
3201    "Size",
3202    "CopyFuncPtr",
3203    "DestroyFuncPtr"
3204  };
3205
3206  for (size_t i = 0; i < 4; ++i) {
3207    FieldDecl *Field = FieldDecl::Create(*this,
3208                                         T,
3209                                         SourceLocation(),
3210                                         &Idents.get(FieldNames[i]),
3211                                         FieldTypes[i], /*TInfo=*/0,
3212                                         /*BitWidth=*/0,
3213                                         /*Mutable=*/false);
3214    T->addDecl(Field);
3215  }
3216
3217  T->completeDefinition();
3218
3219  BlockDescriptorExtendedType = T;
3220
3221  return getTagDeclType(BlockDescriptorExtendedType);
3222}
3223
3224void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3225  const RecordType *Rec = T->getAs<RecordType>();
3226  assert(Rec && "Invalid BlockDescriptorType");
3227  BlockDescriptorExtendedType = Rec->getDecl();
3228}
3229
3230bool ASTContext::BlockRequiresCopying(QualType Ty) {
3231  if (Ty->isBlockPointerType())
3232    return true;
3233  if (isObjCNSObjectType(Ty))
3234    return true;
3235  if (Ty->isObjCObjectPointerType())
3236    return true;
3237  return false;
3238}
3239
3240QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3241  //  type = struct __Block_byref_1_X {
3242  //    void *__isa;
3243  //    struct __Block_byref_1_X *__forwarding;
3244  //    unsigned int __flags;
3245  //    unsigned int __size;
3246  //    void *__copy_helper;		// as needed
3247  //    void *__destroy_help		// as needed
3248  //    int X;
3249  //  } *
3250
3251  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3252
3253  // FIXME: Move up
3254  static unsigned int UniqueBlockByRefTypeID = 0;
3255  llvm::SmallString<36> Name;
3256  llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3257                                  ++UniqueBlockByRefTypeID << '_' << DeclName;
3258  RecordDecl *T;
3259  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3260                       &Idents.get(Name.str()));
3261  T->startDefinition();
3262  QualType Int32Ty = IntTy;
3263  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3264  QualType FieldTypes[] = {
3265    getPointerType(VoidPtrTy),
3266    getPointerType(getTagDeclType(T)),
3267    Int32Ty,
3268    Int32Ty,
3269    getPointerType(VoidPtrTy),
3270    getPointerType(VoidPtrTy),
3271    Ty
3272  };
3273
3274  const char *FieldNames[] = {
3275    "__isa",
3276    "__forwarding",
3277    "__flags",
3278    "__size",
3279    "__copy_helper",
3280    "__destroy_helper",
3281    DeclName,
3282  };
3283
3284  for (size_t i = 0; i < 7; ++i) {
3285    if (!HasCopyAndDispose && i >=4 && i <= 5)
3286      continue;
3287    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3288                                         &Idents.get(FieldNames[i]),
3289                                         FieldTypes[i], /*TInfo=*/0,
3290                                         /*BitWidth=*/0, /*Mutable=*/false);
3291    T->addDecl(Field);
3292  }
3293
3294  T->completeDefinition();
3295
3296  return getPointerType(getTagDeclType(T));
3297}
3298
3299
3300QualType ASTContext::getBlockParmType(
3301  bool BlockHasCopyDispose,
3302  llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
3303  // FIXME: Move up
3304  static unsigned int UniqueBlockParmTypeID = 0;
3305  llvm::SmallString<36> Name;
3306  llvm::raw_svector_ostream(Name) << "__block_literal_"
3307                                  << ++UniqueBlockParmTypeID;
3308  RecordDecl *T;
3309  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3310                       &Idents.get(Name.str()));
3311  T->startDefinition();
3312  QualType FieldTypes[] = {
3313    getPointerType(VoidPtrTy),
3314    IntTy,
3315    IntTy,
3316    getPointerType(VoidPtrTy),
3317    (BlockHasCopyDispose ?
3318     getPointerType(getBlockDescriptorExtendedType()) :
3319     getPointerType(getBlockDescriptorType()))
3320  };
3321
3322  const char *FieldNames[] = {
3323    "__isa",
3324    "__flags",
3325    "__reserved",
3326    "__FuncPtr",
3327    "__descriptor"
3328  };
3329
3330  for (size_t i = 0; i < 5; ++i) {
3331    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3332                                         &Idents.get(FieldNames[i]),
3333                                         FieldTypes[i], /*TInfo=*/0,
3334                                         /*BitWidth=*/0, /*Mutable=*/false);
3335    T->addDecl(Field);
3336  }
3337
3338  for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3339    const Expr *E = BlockDeclRefDecls[i];
3340    const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3341    clang::IdentifierInfo *Name = 0;
3342    if (BDRE) {
3343      const ValueDecl *D = BDRE->getDecl();
3344      Name = &Idents.get(D->getName());
3345    }
3346    QualType FieldType = E->getType();
3347
3348    if (BDRE && BDRE->isByRef())
3349      FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3350                                 FieldType);
3351
3352    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3353                                         Name, FieldType, /*TInfo=*/0,
3354                                         /*BitWidth=*/0, /*Mutable=*/false);
3355    T->addDecl(Field);
3356  }
3357
3358  T->completeDefinition();
3359
3360  return getPointerType(getTagDeclType(T));
3361}
3362
3363void ASTContext::setObjCFastEnumerationStateType(QualType T) {
3364  const RecordType *Rec = T->getAs<RecordType>();
3365  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3366  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3367}
3368
3369// This returns true if a type has been typedefed to BOOL:
3370// typedef <type> BOOL;
3371static bool isTypeTypedefedAsBOOL(QualType T) {
3372  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
3373    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3374      return II->isStr("BOOL");
3375
3376  return false;
3377}
3378
3379/// getObjCEncodingTypeSize returns size of type for objective-c encoding
3380/// purpose.
3381CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
3382  CharUnits sz = getTypeSizeInChars(type);
3383
3384  // Make all integer and enum types at least as large as an int
3385  if (sz.isPositive() && type->isIntegralType())
3386    sz = std::max(sz, getTypeSizeInChars(IntTy));
3387  // Treat arrays as pointers, since that's how they're passed in.
3388  else if (type->isArrayType())
3389    sz = getTypeSizeInChars(VoidPtrTy);
3390  return sz;
3391}
3392
3393static inline
3394std::string charUnitsToString(const CharUnits &CU) {
3395  return llvm::itostr(CU.getQuantity());
3396}
3397
3398/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3399/// declaration.
3400void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3401                                             std::string& S) {
3402  const BlockDecl *Decl = Expr->getBlockDecl();
3403  QualType BlockTy =
3404      Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3405  // Encode result type.
3406  getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3407  // Compute size of all parameters.
3408  // Start with computing size of a pointer in number of bytes.
3409  // FIXME: There might(should) be a better way of doing this computation!
3410  SourceLocation Loc;
3411  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3412  CharUnits ParmOffset = PtrSize;
3413  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3414       E = Decl->param_end(); PI != E; ++PI) {
3415    QualType PType = (*PI)->getType();
3416    CharUnits sz = getObjCEncodingTypeSize(PType);
3417    assert (sz.isPositive() && "BlockExpr - Incomplete param type");
3418    ParmOffset += sz;
3419  }
3420  // Size of the argument frame
3421  S += charUnitsToString(ParmOffset);
3422  // Block pointer and offset.
3423  S += "@?0";
3424  ParmOffset = PtrSize;
3425
3426  // Argument types.
3427  ParmOffset = PtrSize;
3428  for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3429       Decl->param_end(); PI != E; ++PI) {
3430    ParmVarDecl *PVDecl = *PI;
3431    QualType PType = PVDecl->getOriginalType();
3432    if (const ArrayType *AT =
3433          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3434      // Use array's original type only if it has known number of
3435      // elements.
3436      if (!isa<ConstantArrayType>(AT))
3437        PType = PVDecl->getType();
3438    } else if (PType->isFunctionType())
3439      PType = PVDecl->getType();
3440    getObjCEncodingForType(PType, S);
3441    S += charUnitsToString(ParmOffset);
3442    ParmOffset += getObjCEncodingTypeSize(PType);
3443  }
3444}
3445
3446/// getObjCEncodingForMethodDecl - Return the encoded type for this method
3447/// declaration.
3448void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
3449                                              std::string& S) {
3450  // FIXME: This is not very efficient.
3451  // Encode type qualifer, 'in', 'inout', etc. for the return type.
3452  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
3453  // Encode result type.
3454  getObjCEncodingForType(Decl->getResultType(), S);
3455  // Compute size of all parameters.
3456  // Start with computing size of a pointer in number of bytes.
3457  // FIXME: There might(should) be a better way of doing this computation!
3458  SourceLocation Loc;
3459  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3460  // The first two arguments (self and _cmd) are pointers; account for
3461  // their size.
3462  CharUnits ParmOffset = 2 * PtrSize;
3463  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3464       E = Decl->param_end(); PI != E; ++PI) {
3465    QualType PType = (*PI)->getType();
3466    CharUnits sz = getObjCEncodingTypeSize(PType);
3467    assert (sz.isPositive() &&
3468        "getObjCEncodingForMethodDecl - Incomplete param type");
3469    ParmOffset += sz;
3470  }
3471  S += charUnitsToString(ParmOffset);
3472  S += "@0:";
3473  S += charUnitsToString(PtrSize);
3474
3475  // Argument types.
3476  ParmOffset = 2 * PtrSize;
3477  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3478       E = Decl->param_end(); PI != E; ++PI) {
3479    ParmVarDecl *PVDecl = *PI;
3480    QualType PType = PVDecl->getOriginalType();
3481    if (const ArrayType *AT =
3482          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3483      // Use array's original type only if it has known number of
3484      // elements.
3485      if (!isa<ConstantArrayType>(AT))
3486        PType = PVDecl->getType();
3487    } else if (PType->isFunctionType())
3488      PType = PVDecl->getType();
3489    // Process argument qualifiers for user supplied arguments; such as,
3490    // 'in', 'inout', etc.
3491    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
3492    getObjCEncodingForType(PType, S);
3493    S += charUnitsToString(ParmOffset);
3494    ParmOffset += getObjCEncodingTypeSize(PType);
3495  }
3496}
3497
3498/// getObjCEncodingForPropertyDecl - Return the encoded type for this
3499/// property declaration. If non-NULL, Container must be either an
3500/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3501/// NULL when getting encodings for protocol properties.
3502/// Property attributes are stored as a comma-delimited C string. The simple
3503/// attributes readonly and bycopy are encoded as single characters. The
3504/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3505/// encoded as single characters, followed by an identifier. Property types
3506/// are also encoded as a parametrized attribute. The characters used to encode
3507/// these attributes are defined by the following enumeration:
3508/// @code
3509/// enum PropertyAttributes {
3510/// kPropertyReadOnly = 'R',   // property is read-only.
3511/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
3512/// kPropertyByref = '&',  // property is a reference to the value last assigned
3513/// kPropertyDynamic = 'D',    // property is dynamic
3514/// kPropertyGetter = 'G',     // followed by getter selector name
3515/// kPropertySetter = 'S',     // followed by setter selector name
3516/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
3517/// kPropertyType = 't'              // followed by old-style type encoding.
3518/// kPropertyWeak = 'W'              // 'weak' property
3519/// kPropertyStrong = 'P'            // property GC'able
3520/// kPropertyNonAtomic = 'N'         // property non-atomic
3521/// };
3522/// @endcode
3523void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
3524                                                const Decl *Container,
3525                                                std::string& S) {
3526  // Collect information from the property implementation decl(s).
3527  bool Dynamic = false;
3528  ObjCPropertyImplDecl *SynthesizePID = 0;
3529
3530  // FIXME: Duplicated code due to poor abstraction.
3531  if (Container) {
3532    if (const ObjCCategoryImplDecl *CID =
3533        dyn_cast<ObjCCategoryImplDecl>(Container)) {
3534      for (ObjCCategoryImplDecl::propimpl_iterator
3535             i = CID->propimpl_begin(), e = CID->propimpl_end();
3536           i != e; ++i) {
3537        ObjCPropertyImplDecl *PID = *i;
3538        if (PID->getPropertyDecl() == PD) {
3539          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3540            Dynamic = true;
3541          } else {
3542            SynthesizePID = PID;
3543          }
3544        }
3545      }
3546    } else {
3547      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
3548      for (ObjCCategoryImplDecl::propimpl_iterator
3549             i = OID->propimpl_begin(), e = OID->propimpl_end();
3550           i != e; ++i) {
3551        ObjCPropertyImplDecl *PID = *i;
3552        if (PID->getPropertyDecl() == PD) {
3553          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3554            Dynamic = true;
3555          } else {
3556            SynthesizePID = PID;
3557          }
3558        }
3559      }
3560    }
3561  }
3562
3563  // FIXME: This is not very efficient.
3564  S = "T";
3565
3566  // Encode result type.
3567  // GCC has some special rules regarding encoding of properties which
3568  // closely resembles encoding of ivars.
3569  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
3570                             true /* outermost type */,
3571                             true /* encoding for property */);
3572
3573  if (PD->isReadOnly()) {
3574    S += ",R";
3575  } else {
3576    switch (PD->getSetterKind()) {
3577    case ObjCPropertyDecl::Assign: break;
3578    case ObjCPropertyDecl::Copy:   S += ",C"; break;
3579    case ObjCPropertyDecl::Retain: S += ",&"; break;
3580    }
3581  }
3582
3583  // It really isn't clear at all what this means, since properties
3584  // are "dynamic by default".
3585  if (Dynamic)
3586    S += ",D";
3587
3588  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3589    S += ",N";
3590
3591  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3592    S += ",G";
3593    S += PD->getGetterName().getAsString();
3594  }
3595
3596  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3597    S += ",S";
3598    S += PD->getSetterName().getAsString();
3599  }
3600
3601  if (SynthesizePID) {
3602    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3603    S += ",V";
3604    S += OID->getNameAsString();
3605  }
3606
3607  // FIXME: OBJCGC: weak & strong
3608}
3609
3610/// getLegacyIntegralTypeEncoding -
3611/// Another legacy compatibility encoding: 32-bit longs are encoded as
3612/// 'l' or 'L' , but not always.  For typedefs, we need to use
3613/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3614///
3615void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
3616  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
3617    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
3618      if (BT->getKind() == BuiltinType::ULong &&
3619          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3620        PointeeTy = UnsignedIntTy;
3621      else
3622        if (BT->getKind() == BuiltinType::Long &&
3623            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3624          PointeeTy = IntTy;
3625    }
3626  }
3627}
3628
3629void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
3630                                        const FieldDecl *Field) {
3631  // We follow the behavior of gcc, expanding structures which are
3632  // directly pointed to, and expanding embedded structures. Note that
3633  // these rules are sufficient to prevent recursive encoding of the
3634  // same type.
3635  getObjCEncodingForTypeImpl(T, S, true, true, Field,
3636                             true /* outermost type */);
3637}
3638
3639static void EncodeBitField(const ASTContext *Context, std::string& S,
3640                           const FieldDecl *FD) {
3641  const Expr *E = FD->getBitWidth();
3642  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3643  ASTContext *Ctx = const_cast<ASTContext*>(Context);
3644  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
3645  S += 'b';
3646  S += llvm::utostr(N);
3647}
3648
3649// FIXME: Use SmallString for accumulating string.
3650void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3651                                            bool ExpandPointedToStructures,
3652                                            bool ExpandStructures,
3653                                            const FieldDecl *FD,
3654                                            bool OutermostType,
3655                                            bool EncodingProperty) {
3656  if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
3657    if (FD && FD->isBitField())
3658      return EncodeBitField(this, S, FD);
3659    char encoding;
3660    switch (BT->getKind()) {
3661    default: assert(0 && "Unhandled builtin type kind");
3662    case BuiltinType::Void:       encoding = 'v'; break;
3663    case BuiltinType::Bool:       encoding = 'B'; break;
3664    case BuiltinType::Char_U:
3665    case BuiltinType::UChar:      encoding = 'C'; break;
3666    case BuiltinType::UShort:     encoding = 'S'; break;
3667    case BuiltinType::UInt:       encoding = 'I'; break;
3668    case BuiltinType::ULong:
3669        encoding =
3670          (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
3671        break;
3672    case BuiltinType::UInt128:    encoding = 'T'; break;
3673    case BuiltinType::ULongLong:  encoding = 'Q'; break;
3674    case BuiltinType::Char_S:
3675    case BuiltinType::SChar:      encoding = 'c'; break;
3676    case BuiltinType::Short:      encoding = 's'; break;
3677    case BuiltinType::Int:        encoding = 'i'; break;
3678    case BuiltinType::Long:
3679      encoding =
3680        (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
3681      break;
3682    case BuiltinType::LongLong:   encoding = 'q'; break;
3683    case BuiltinType::Int128:     encoding = 't'; break;
3684    case BuiltinType::Float:      encoding = 'f'; break;
3685    case BuiltinType::Double:     encoding = 'd'; break;
3686    case BuiltinType::LongDouble: encoding = 'd'; break;
3687    }
3688
3689    S += encoding;
3690    return;
3691  }
3692
3693  if (const ComplexType *CT = T->getAs<ComplexType>()) {
3694    S += 'j';
3695    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
3696                               false);
3697    return;
3698  }
3699
3700  if (const PointerType *PT = T->getAs<PointerType>()) {
3701    if (PT->isObjCSelType()) {
3702      S += ':';
3703      return;
3704    }
3705    QualType PointeeTy = PT->getPointeeType();
3706
3707    bool isReadOnly = false;
3708    // For historical/compatibility reasons, the read-only qualifier of the
3709    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
3710    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
3711    // Also, do not emit the 'r' for anything but the outermost type!
3712    if (isa<TypedefType>(T.getTypePtr())) {
3713      if (OutermostType && T.isConstQualified()) {
3714        isReadOnly = true;
3715        S += 'r';
3716      }
3717    } else if (OutermostType) {
3718      QualType P = PointeeTy;
3719      while (P->getAs<PointerType>())
3720        P = P->getAs<PointerType>()->getPointeeType();
3721      if (P.isConstQualified()) {
3722        isReadOnly = true;
3723        S += 'r';
3724      }
3725    }
3726    if (isReadOnly) {
3727      // Another legacy compatibility encoding. Some ObjC qualifier and type
3728      // combinations need to be rearranged.
3729      // Rewrite "in const" from "nr" to "rn"
3730      const char * s = S.c_str();
3731      int len = S.length();
3732      if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3733        std::string replace = "rn";
3734        S.replace(S.end()-2, S.end(), replace);
3735      }
3736    }
3737
3738    if (PointeeTy->isCharType()) {
3739      // char pointer types should be encoded as '*' unless it is a
3740      // type that has been typedef'd to 'BOOL'.
3741      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
3742        S += '*';
3743        return;
3744      }
3745    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
3746      // GCC binary compat: Need to convert "struct objc_class *" to "#".
3747      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3748        S += '#';
3749        return;
3750      }
3751      // GCC binary compat: Need to convert "struct objc_object *" to "@".
3752      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3753        S += '@';
3754        return;
3755      }
3756      // fall through...
3757    }
3758    S += '^';
3759    getLegacyIntegralTypeEncoding(PointeeTy);
3760
3761    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
3762                               NULL);
3763    return;
3764  }
3765
3766  if (const ArrayType *AT =
3767      // Ignore type qualifiers etc.
3768        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
3769    if (isa<IncompleteArrayType>(AT)) {
3770      // Incomplete arrays are encoded as a pointer to the array element.
3771      S += '^';
3772
3773      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3774                                 false, ExpandStructures, FD);
3775    } else {
3776      S += '[';
3777
3778      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3779        S += llvm::utostr(CAT->getSize().getZExtValue());
3780      else {
3781        //Variable length arrays are encoded as a regular array with 0 elements.
3782        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3783        S += '0';
3784      }
3785
3786      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3787                                 false, ExpandStructures, FD);
3788      S += ']';
3789    }
3790    return;
3791  }
3792
3793  if (T->getAs<FunctionType>()) {
3794    S += '?';
3795    return;
3796  }
3797
3798  if (const RecordType *RTy = T->getAs<RecordType>()) {
3799    RecordDecl *RDecl = RTy->getDecl();
3800    S += RDecl->isUnion() ? '(' : '{';
3801    // Anonymous structures print as '?'
3802    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3803      S += II->getName();
3804    } else {
3805      S += '?';
3806    }
3807    if (ExpandStructures) {
3808      S += '=';
3809      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3810                                   FieldEnd = RDecl->field_end();
3811           Field != FieldEnd; ++Field) {
3812        if (FD) {
3813          S += '"';
3814          S += Field->getNameAsString();
3815          S += '"';
3816        }
3817
3818        // Special case bit-fields.
3819        if (Field->isBitField()) {
3820          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
3821                                     (*Field));
3822        } else {
3823          QualType qt = Field->getType();
3824          getLegacyIntegralTypeEncoding(qt);
3825          getObjCEncodingForTypeImpl(qt, S, false, true,
3826                                     FD);
3827        }
3828      }
3829    }
3830    S += RDecl->isUnion() ? ')' : '}';
3831    return;
3832  }
3833
3834  if (T->isEnumeralType()) {
3835    if (FD && FD->isBitField())
3836      EncodeBitField(this, S, FD);
3837    else
3838      S += 'i';
3839    return;
3840  }
3841
3842  if (T->isBlockPointerType()) {
3843    S += "@?"; // Unlike a pointer-to-function, which is "^?".
3844    return;
3845  }
3846
3847  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
3848    // @encode(class_name)
3849    ObjCInterfaceDecl *OI = OIT->getDecl();
3850    S += '{';
3851    const IdentifierInfo *II = OI->getIdentifier();
3852    S += II->getName();
3853    S += '=';
3854    llvm::SmallVector<FieldDecl*, 32> RecFields;
3855    CollectObjCIvars(OI, RecFields);
3856    for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
3857      if (RecFields[i]->isBitField())
3858        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3859                                   RecFields[i]);
3860      else
3861        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3862                                   FD);
3863    }
3864    S += '}';
3865    return;
3866  }
3867
3868  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
3869    if (OPT->isObjCIdType()) {
3870      S += '@';
3871      return;
3872    }
3873
3874    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3875      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3876      // Since this is a binary compatibility issue, need to consult with runtime
3877      // folks. Fortunately, this is a *very* obsure construct.
3878      S += '#';
3879      return;
3880    }
3881
3882    if (OPT->isObjCQualifiedIdType()) {
3883      getObjCEncodingForTypeImpl(getObjCIdType(), S,
3884                                 ExpandPointedToStructures,
3885                                 ExpandStructures, FD);
3886      if (FD || EncodingProperty) {
3887        // Note that we do extended encoding of protocol qualifer list
3888        // Only when doing ivar or property encoding.
3889        S += '"';
3890        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3891             E = OPT->qual_end(); I != E; ++I) {
3892          S += '<';
3893          S += (*I)->getNameAsString();
3894          S += '>';
3895        }
3896        S += '"';
3897      }
3898      return;
3899    }
3900
3901    QualType PointeeTy = OPT->getPointeeType();
3902    if (!EncodingProperty &&
3903        isa<TypedefType>(PointeeTy.getTypePtr())) {
3904      // Another historical/compatibility reason.
3905      // We encode the underlying type which comes out as
3906      // {...};
3907      S += '^';
3908      getObjCEncodingForTypeImpl(PointeeTy, S,
3909                                 false, ExpandPointedToStructures,
3910                                 NULL);
3911      return;
3912    }
3913
3914    S += '@';
3915    if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
3916      S += '"';
3917      S += OPT->getInterfaceDecl()->getIdentifier()->getName();
3918      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3919           E = OPT->qual_end(); I != E; ++I) {
3920        S += '<';
3921        S += (*I)->getNameAsString();
3922        S += '>';
3923      }
3924      S += '"';
3925    }
3926    return;
3927  }
3928
3929  assert(0 && "@encode for type not implemented!");
3930}
3931
3932void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
3933                                                 std::string& S) const {
3934  if (QT & Decl::OBJC_TQ_In)
3935    S += 'n';
3936  if (QT & Decl::OBJC_TQ_Inout)
3937    S += 'N';
3938  if (QT & Decl::OBJC_TQ_Out)
3939    S += 'o';
3940  if (QT & Decl::OBJC_TQ_Bycopy)
3941    S += 'O';
3942  if (QT & Decl::OBJC_TQ_Byref)
3943    S += 'R';
3944  if (QT & Decl::OBJC_TQ_Oneway)
3945    S += 'V';
3946}
3947
3948void ASTContext::setBuiltinVaListType(QualType T) {
3949  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3950
3951  BuiltinVaListType = T;
3952}
3953
3954void ASTContext::setObjCIdType(QualType T) {
3955  ObjCIdTypedefType = T;
3956}
3957
3958void ASTContext::setObjCSelType(QualType T) {
3959  ObjCSelTypedefType = T;
3960}
3961
3962void ASTContext::setObjCProtoType(QualType QT) {
3963  ObjCProtoType = QT;
3964}
3965
3966void ASTContext::setObjCClassType(QualType T) {
3967  ObjCClassTypedefType = T;
3968}
3969
3970void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3971  assert(ObjCConstantStringType.isNull() &&
3972         "'NSConstantString' type already set!");
3973
3974  ObjCConstantStringType = getObjCInterfaceType(Decl);
3975}
3976
3977/// \brief Retrieve the template name that corresponds to a non-empty
3978/// lookup.
3979TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3980                                                   UnresolvedSetIterator End) {
3981  unsigned size = End - Begin;
3982  assert(size > 1 && "set is not overloaded!");
3983
3984  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3985                          size * sizeof(FunctionTemplateDecl*));
3986  OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3987
3988  NamedDecl **Storage = OT->getStorage();
3989  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
3990    NamedDecl *D = *I;
3991    assert(isa<FunctionTemplateDecl>(D) ||
3992           (isa<UsingShadowDecl>(D) &&
3993            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3994    *Storage++ = D;
3995  }
3996
3997  return TemplateName(OT);
3998}
3999
4000/// \brief Retrieve the template name that represents a qualified
4001/// template name such as \c std::vector.
4002TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4003                                                  bool TemplateKeyword,
4004                                                  TemplateDecl *Template) {
4005  // FIXME: Canonicalization?
4006  llvm::FoldingSetNodeID ID;
4007  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4008
4009  void *InsertPos = 0;
4010  QualifiedTemplateName *QTN =
4011    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4012  if (!QTN) {
4013    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4014    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4015  }
4016
4017  return TemplateName(QTN);
4018}
4019
4020/// \brief Retrieve the template name that represents a dependent
4021/// template name such as \c MetaFun::template apply.
4022TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4023                                                  const IdentifierInfo *Name) {
4024  assert((!NNS || NNS->isDependent()) &&
4025         "Nested name specifier must be dependent");
4026
4027  llvm::FoldingSetNodeID ID;
4028  DependentTemplateName::Profile(ID, NNS, Name);
4029
4030  void *InsertPos = 0;
4031  DependentTemplateName *QTN =
4032    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4033
4034  if (QTN)
4035    return TemplateName(QTN);
4036
4037  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4038  if (CanonNNS == NNS) {
4039    QTN = new (*this,4) DependentTemplateName(NNS, Name);
4040  } else {
4041    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4042    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
4043    DependentTemplateName *CheckQTN =
4044      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4045    assert(!CheckQTN && "Dependent type name canonicalization broken");
4046    (void)CheckQTN;
4047  }
4048
4049  DependentTemplateNames.InsertNode(QTN, InsertPos);
4050  return TemplateName(QTN);
4051}
4052
4053/// \brief Retrieve the template name that represents a dependent
4054/// template name such as \c MetaFun::template operator+.
4055TemplateName
4056ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4057                                     OverloadedOperatorKind Operator) {
4058  assert((!NNS || NNS->isDependent()) &&
4059         "Nested name specifier must be dependent");
4060
4061  llvm::FoldingSetNodeID ID;
4062  DependentTemplateName::Profile(ID, NNS, Operator);
4063
4064  void *InsertPos = 0;
4065  DependentTemplateName *QTN
4066    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4067
4068  if (QTN)
4069    return TemplateName(QTN);
4070
4071  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4072  if (CanonNNS == NNS) {
4073    QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4074  } else {
4075    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4076    QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
4077
4078    DependentTemplateName *CheckQTN
4079      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4080    assert(!CheckQTN && "Dependent template name canonicalization broken");
4081    (void)CheckQTN;
4082  }
4083
4084  DependentTemplateNames.InsertNode(QTN, InsertPos);
4085  return TemplateName(QTN);
4086}
4087
4088/// getFromTargetType - Given one of the integer types provided by
4089/// TargetInfo, produce the corresponding type. The unsigned @p Type
4090/// is actually a value of type @c TargetInfo::IntType.
4091CanQualType ASTContext::getFromTargetType(unsigned Type) const {
4092  switch (Type) {
4093  case TargetInfo::NoInt: return CanQualType();
4094  case TargetInfo::SignedShort: return ShortTy;
4095  case TargetInfo::UnsignedShort: return UnsignedShortTy;
4096  case TargetInfo::SignedInt: return IntTy;
4097  case TargetInfo::UnsignedInt: return UnsignedIntTy;
4098  case TargetInfo::SignedLong: return LongTy;
4099  case TargetInfo::UnsignedLong: return UnsignedLongTy;
4100  case TargetInfo::SignedLongLong: return LongLongTy;
4101  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4102  }
4103
4104  assert(false && "Unhandled TargetInfo::IntType value");
4105  return CanQualType();
4106}
4107
4108//===----------------------------------------------------------------------===//
4109//                        Type Predicates.
4110//===----------------------------------------------------------------------===//
4111
4112/// isObjCNSObjectType - Return true if this is an NSObject object using
4113/// NSObject attribute on a c-style pointer type.
4114/// FIXME - Make it work directly on types.
4115/// FIXME: Move to Type.
4116///
4117bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4118  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4119    if (TypedefDecl *TD = TDT->getDecl())
4120      if (TD->getAttr<ObjCNSObjectAttr>())
4121        return true;
4122  }
4123  return false;
4124}
4125
4126/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4127/// garbage collection attribute.
4128///
4129Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4130  Qualifiers::GC GCAttrs = Qualifiers::GCNone;
4131  if (getLangOptions().ObjC1 &&
4132      getLangOptions().getGCMode() != LangOptions::NonGC) {
4133    GCAttrs = Ty.getObjCGCAttr();
4134    // Default behavious under objective-c's gc is for objective-c pointers
4135    // (or pointers to them) be treated as though they were declared
4136    // as __strong.
4137    if (GCAttrs == Qualifiers::GCNone) {
4138      if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4139        GCAttrs = Qualifiers::Strong;
4140      else if (Ty->isPointerType())
4141        return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4142    }
4143    // Non-pointers have none gc'able attribute regardless of the attribute
4144    // set on them.
4145    else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
4146      return Qualifiers::GCNone;
4147  }
4148  return GCAttrs;
4149}
4150
4151//===----------------------------------------------------------------------===//
4152//                        Type Compatibility Testing
4153//===----------------------------------------------------------------------===//
4154
4155/// areCompatVectorTypes - Return true if the two specified vector types are
4156/// compatible.
4157static bool areCompatVectorTypes(const VectorType *LHS,
4158                                 const VectorType *RHS) {
4159  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
4160  return LHS->getElementType() == RHS->getElementType() &&
4161         LHS->getNumElements() == RHS->getNumElements();
4162}
4163
4164//===----------------------------------------------------------------------===//
4165// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4166//===----------------------------------------------------------------------===//
4167
4168/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4169/// inheritance hierarchy of 'rProto'.
4170bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4171                                                ObjCProtocolDecl *rProto) {
4172  if (lProto == rProto)
4173    return true;
4174  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4175       E = rProto->protocol_end(); PI != E; ++PI)
4176    if (ProtocolCompatibleWithProtocol(lProto, *PI))
4177      return true;
4178  return false;
4179}
4180
4181/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4182/// return true if lhs's protocols conform to rhs's protocol; false
4183/// otherwise.
4184bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4185  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4186    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4187  return false;
4188}
4189
4190/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4191/// ObjCQualifiedIDType.
4192bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4193                                                   bool compare) {
4194  // Allow id<P..> and an 'id' or void* type in all cases.
4195  if (lhs->isVoidPointerType() ||
4196      lhs->isObjCIdType() || lhs->isObjCClassType())
4197    return true;
4198  else if (rhs->isVoidPointerType() ||
4199           rhs->isObjCIdType() || rhs->isObjCClassType())
4200    return true;
4201
4202  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
4203    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4204
4205    if (!rhsOPT) return false;
4206
4207    if (rhsOPT->qual_empty()) {
4208      // If the RHS is a unqualified interface pointer "NSString*",
4209      // make sure we check the class hierarchy.
4210      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4211        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4212             E = lhsQID->qual_end(); I != E; ++I) {
4213          // when comparing an id<P> on lhs with a static type on rhs,
4214          // see if static class implements all of id's protocols, directly or
4215          // through its super class and categories.
4216          if (!rhsID->ClassImplementsProtocol(*I, true))
4217            return false;
4218        }
4219      }
4220      // If there are no qualifiers and no interface, we have an 'id'.
4221      return true;
4222    }
4223    // Both the right and left sides have qualifiers.
4224    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4225         E = lhsQID->qual_end(); I != E; ++I) {
4226      ObjCProtocolDecl *lhsProto = *I;
4227      bool match = false;
4228
4229      // when comparing an id<P> on lhs with a static type on rhs,
4230      // see if static class implements all of id's protocols, directly or
4231      // through its super class and categories.
4232      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4233           E = rhsOPT->qual_end(); J != E; ++J) {
4234        ObjCProtocolDecl *rhsProto = *J;
4235        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4236            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4237          match = true;
4238          break;
4239        }
4240      }
4241      // If the RHS is a qualified interface pointer "NSString<P>*",
4242      // make sure we check the class hierarchy.
4243      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4244        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4245             E = lhsQID->qual_end(); I != E; ++I) {
4246          // when comparing an id<P> on lhs with a static type on rhs,
4247          // see if static class implements all of id's protocols, directly or
4248          // through its super class and categories.
4249          if (rhsID->ClassImplementsProtocol(*I, true)) {
4250            match = true;
4251            break;
4252          }
4253        }
4254      }
4255      if (!match)
4256        return false;
4257    }
4258
4259    return true;
4260  }
4261
4262  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4263  assert(rhsQID && "One of the LHS/RHS should be id<x>");
4264
4265  if (const ObjCObjectPointerType *lhsOPT =
4266        lhs->getAsObjCInterfacePointerType()) {
4267    if (lhsOPT->qual_empty()) {
4268      bool match = false;
4269      if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4270        for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4271             E = rhsQID->qual_end(); I != E; ++I) {
4272          // when comparing an id<P> on lhs with a static type on rhs,
4273          // see if static class implements all of id's protocols, directly or
4274          // through its super class and categories.
4275          if (lhsID->ClassImplementsProtocol(*I, true)) {
4276            match = true;
4277            break;
4278          }
4279        }
4280        if (!match)
4281          return false;
4282      }
4283      return true;
4284    }
4285    // Both the right and left sides have qualifiers.
4286    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4287         E = lhsOPT->qual_end(); I != E; ++I) {
4288      ObjCProtocolDecl *lhsProto = *I;
4289      bool match = false;
4290
4291      // when comparing an id<P> on lhs with a static type on rhs,
4292      // see if static class implements all of id's protocols, directly or
4293      // through its super class and categories.
4294      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4295           E = rhsQID->qual_end(); J != E; ++J) {
4296        ObjCProtocolDecl *rhsProto = *J;
4297        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4298            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4299          match = true;
4300          break;
4301        }
4302      }
4303      if (!match)
4304        return false;
4305    }
4306    return true;
4307  }
4308  return false;
4309}
4310
4311/// canAssignObjCInterfaces - Return true if the two interface types are
4312/// compatible for assignment from RHS to LHS.  This handles validation of any
4313/// protocol qualifiers on the LHS or RHS.
4314///
4315bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4316                                         const ObjCObjectPointerType *RHSOPT) {
4317  // If either type represents the built-in 'id' or 'Class' types, return true.
4318  if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
4319    return true;
4320
4321  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
4322    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4323                                             QualType(RHSOPT,0),
4324                                             false);
4325
4326  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4327  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4328  if (LHS && RHS) // We have 2 user-defined types.
4329    return canAssignObjCInterfaces(LHS, RHS);
4330
4331  return false;
4332}
4333
4334/// getIntersectionOfProtocols - This routine finds the intersection of set
4335/// of protocols inherited from two distinct objective-c pointer objects.
4336/// It is used to build composite qualifier list of the composite type of
4337/// the conditional expression involving two objective-c pointer objects.
4338static
4339void getIntersectionOfProtocols(ASTContext &Context,
4340                                const ObjCObjectPointerType *LHSOPT,
4341                                const ObjCObjectPointerType *RHSOPT,
4342      llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4343
4344  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4345  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4346
4347  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4348  unsigned LHSNumProtocols = LHS->getNumProtocols();
4349  if (LHSNumProtocols > 0)
4350    InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4351  else {
4352    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4353    Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4354    InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4355                                LHSInheritedProtocols.end());
4356  }
4357
4358  unsigned RHSNumProtocols = RHS->getNumProtocols();
4359  if (RHSNumProtocols > 0) {
4360    ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4361    for (unsigned i = 0; i < RHSNumProtocols; ++i)
4362      if (InheritedProtocolSet.count(RHSProtocols[i]))
4363        IntersectionOfProtocols.push_back(RHSProtocols[i]);
4364  }
4365  else {
4366    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4367    Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4368    for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4369         RHSInheritedProtocols.begin(),
4370         E = RHSInheritedProtocols.end(); I != E; ++I)
4371      if (InheritedProtocolSet.count((*I)))
4372        IntersectionOfProtocols.push_back((*I));
4373  }
4374}
4375
4376/// areCommonBaseCompatible - Returns common base class of the two classes if
4377/// one found. Note that this is O'2 algorithm. But it will be called as the
4378/// last type comparison in a ?-exp of ObjC pointer types before a
4379/// warning is issued. So, its invokation is extremely rare.
4380QualType ASTContext::areCommonBaseCompatible(
4381                                          const ObjCObjectPointerType *LHSOPT,
4382                                          const ObjCObjectPointerType *RHSOPT) {
4383  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4384  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4385  if (!LHS || !RHS)
4386    return QualType();
4387
4388  while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4389    QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4390    LHS = LHSTy->getAs<ObjCInterfaceType>();
4391    if (canAssignObjCInterfaces(LHS, RHS)) {
4392      llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4393      getIntersectionOfProtocols(*this,
4394                                 LHSOPT, RHSOPT, IntersectionOfProtocols);
4395      if (IntersectionOfProtocols.empty())
4396        LHSTy = getObjCObjectPointerType(LHSTy);
4397      else
4398        LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4399                                                IntersectionOfProtocols.size());
4400      return LHSTy;
4401    }
4402  }
4403
4404  return QualType();
4405}
4406
4407bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4408                                         const ObjCInterfaceType *RHS) {
4409  // Verify that the base decls are compatible: the RHS must be a subclass of
4410  // the LHS.
4411  if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4412    return false;
4413
4414  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
4415  // protocol qualified at all, then we are good.
4416  if (LHS->getNumProtocols() == 0)
4417    return true;
4418
4419  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
4420  // isn't a superset.
4421  if (RHS->getNumProtocols() == 0)
4422    return true;  // FIXME: should return false!
4423
4424  for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4425                                        LHSPE = LHS->qual_end();
4426       LHSPI != LHSPE; LHSPI++) {
4427    bool RHSImplementsProtocol = false;
4428
4429    // If the RHS doesn't implement the protocol on the left, the types
4430    // are incompatible.
4431    for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
4432                                          RHSPE = RHS->qual_end();
4433         RHSPI != RHSPE; RHSPI++) {
4434      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
4435        RHSImplementsProtocol = true;
4436        break;
4437      }
4438    }
4439    // FIXME: For better diagnostics, consider passing back the protocol name.
4440    if (!RHSImplementsProtocol)
4441      return false;
4442  }
4443  // The RHS implements all protocols listed on the LHS.
4444  return true;
4445}
4446
4447bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4448  // get the "pointed to" types
4449  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4450  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
4451
4452  if (!LHSOPT || !RHSOPT)
4453    return false;
4454
4455  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4456         canAssignObjCInterfaces(RHSOPT, LHSOPT);
4457}
4458
4459/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
4460/// both shall have the identically qualified version of a compatible type.
4461/// C99 6.2.7p1: Two types have compatible types if their types are the
4462/// same. See 6.7.[2,3,5] for additional rules.
4463bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4464  if (getLangOptions().CPlusPlus)
4465    return hasSameType(LHS, RHS);
4466
4467  return !mergeTypes(LHS, RHS).isNull();
4468}
4469
4470QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
4471  const FunctionType *lbase = lhs->getAs<FunctionType>();
4472  const FunctionType *rbase = rhs->getAs<FunctionType>();
4473  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4474  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
4475  bool allLTypes = true;
4476  bool allRTypes = true;
4477
4478  // Check return type
4479  QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4480  if (retType.isNull()) return QualType();
4481  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4482    allLTypes = false;
4483  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4484    allRTypes = false;
4485  // FIXME: double check this
4486  bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4487  if (NoReturn != lbase->getNoReturnAttr())
4488    allLTypes = false;
4489  if (NoReturn != rbase->getNoReturnAttr())
4490    allRTypes = false;
4491  CallingConv lcc = lbase->getCallConv();
4492  CallingConv rcc = rbase->getCallConv();
4493  // Compatible functions must have compatible calling conventions
4494  if (!isSameCallConv(lcc, rcc))
4495    return QualType();
4496
4497  if (lproto && rproto) { // two C99 style function prototypes
4498    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4499           "C++ shouldn't be here");
4500    unsigned lproto_nargs = lproto->getNumArgs();
4501    unsigned rproto_nargs = rproto->getNumArgs();
4502
4503    // Compatible functions must have the same number of arguments
4504    if (lproto_nargs != rproto_nargs)
4505      return QualType();
4506
4507    // Variadic and non-variadic functions aren't compatible
4508    if (lproto->isVariadic() != rproto->isVariadic())
4509      return QualType();
4510
4511    if (lproto->getTypeQuals() != rproto->getTypeQuals())
4512      return QualType();
4513
4514    // Check argument compatibility
4515    llvm::SmallVector<QualType, 10> types;
4516    for (unsigned i = 0; i < lproto_nargs; i++) {
4517      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4518      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4519      QualType argtype = mergeTypes(largtype, rargtype);
4520      if (argtype.isNull()) return QualType();
4521      types.push_back(argtype);
4522      if (getCanonicalType(argtype) != getCanonicalType(largtype))
4523        allLTypes = false;
4524      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4525        allRTypes = false;
4526    }
4527    if (allLTypes) return lhs;
4528    if (allRTypes) return rhs;
4529    return getFunctionType(retType, types.begin(), types.size(),
4530                           lproto->isVariadic(), lproto->getTypeQuals(),
4531                           false, false, 0, 0, NoReturn, lcc);
4532  }
4533
4534  if (lproto) allRTypes = false;
4535  if (rproto) allLTypes = false;
4536
4537  const FunctionProtoType *proto = lproto ? lproto : rproto;
4538  if (proto) {
4539    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
4540    if (proto->isVariadic()) return QualType();
4541    // Check that the types are compatible with the types that
4542    // would result from default argument promotions (C99 6.7.5.3p15).
4543    // The only types actually affected are promotable integer
4544    // types and floats, which would be passed as a different
4545    // type depending on whether the prototype is visible.
4546    unsigned proto_nargs = proto->getNumArgs();
4547    for (unsigned i = 0; i < proto_nargs; ++i) {
4548      QualType argTy = proto->getArgType(i);
4549
4550      // Look at the promotion type of enum types, since that is the type used
4551      // to pass enum values.
4552      if (const EnumType *Enum = argTy->getAs<EnumType>())
4553        argTy = Enum->getDecl()->getPromotionType();
4554
4555      if (argTy->isPromotableIntegerType() ||
4556          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4557        return QualType();
4558    }
4559
4560    if (allLTypes) return lhs;
4561    if (allRTypes) return rhs;
4562    return getFunctionType(retType, proto->arg_type_begin(),
4563                           proto->getNumArgs(), proto->isVariadic(),
4564                           proto->getTypeQuals(),
4565                           false, false, 0, 0, NoReturn, lcc);
4566  }
4567
4568  if (allLTypes) return lhs;
4569  if (allRTypes) return rhs;
4570  return getFunctionNoProtoType(retType, NoReturn, lcc);
4571}
4572
4573QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
4574  // C++ [expr]: If an expression initially has the type "reference to T", the
4575  // type is adjusted to "T" prior to any further analysis, the expression
4576  // designates the object or function denoted by the reference, and the
4577  // expression is an lvalue unless the reference is an rvalue reference and
4578  // the expression is a function call (possibly inside parentheses).
4579  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4580  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4581
4582  QualType LHSCan = getCanonicalType(LHS),
4583           RHSCan = getCanonicalType(RHS);
4584
4585  // If two types are identical, they are compatible.
4586  if (LHSCan == RHSCan)
4587    return LHS;
4588
4589  // If the qualifiers are different, the types aren't compatible... mostly.
4590  Qualifiers LQuals = LHSCan.getLocalQualifiers();
4591  Qualifiers RQuals = RHSCan.getLocalQualifiers();
4592  if (LQuals != RQuals) {
4593    // If any of these qualifiers are different, we have a type
4594    // mismatch.
4595    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4596        LQuals.getAddressSpace() != RQuals.getAddressSpace())
4597      return QualType();
4598
4599    // Exactly one GC qualifier difference is allowed: __strong is
4600    // okay if the other type has no GC qualifier but is an Objective
4601    // C object pointer (i.e. implicitly strong by default).  We fix
4602    // this by pretending that the unqualified type was actually
4603    // qualified __strong.
4604    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4605    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4606    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4607
4608    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4609      return QualType();
4610
4611    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4612      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4613    }
4614    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4615      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4616    }
4617    return QualType();
4618  }
4619
4620  // Okay, qualifiers are equal.
4621
4622  Type::TypeClass LHSClass = LHSCan->getTypeClass();
4623  Type::TypeClass RHSClass = RHSCan->getTypeClass();
4624
4625  // We want to consider the two function types to be the same for these
4626  // comparisons, just force one to the other.
4627  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4628  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
4629
4630  // Same as above for arrays
4631  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4632    LHSClass = Type::ConstantArray;
4633  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4634    RHSClass = Type::ConstantArray;
4635
4636  // Canonicalize ExtVector -> Vector.
4637  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4638  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
4639
4640  // If the canonical type classes don't match.
4641  if (LHSClass != RHSClass) {
4642    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
4643    // a signed integer type, or an unsigned integer type.
4644    // Compatibility is based on the underlying type, not the promotion
4645    // type.
4646    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
4647      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4648        return RHS;
4649    }
4650    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
4651      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4652        return LHS;
4653    }
4654
4655    return QualType();
4656  }
4657
4658  // The canonical type classes match.
4659  switch (LHSClass) {
4660#define TYPE(Class, Base)
4661#define ABSTRACT_TYPE(Class, Base)
4662#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4663#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4664#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4665#include "clang/AST/TypeNodes.def"
4666    assert(false && "Non-canonical and dependent types shouldn't get here");
4667    return QualType();
4668
4669  case Type::LValueReference:
4670  case Type::RValueReference:
4671  case Type::MemberPointer:
4672    assert(false && "C++ should never be in mergeTypes");
4673    return QualType();
4674
4675  case Type::IncompleteArray:
4676  case Type::VariableArray:
4677  case Type::FunctionProto:
4678  case Type::ExtVector:
4679    assert(false && "Types are eliminated above");
4680    return QualType();
4681
4682  case Type::Pointer:
4683  {
4684    // Merge two pointer types, while trying to preserve typedef info
4685    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4686    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
4687    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4688    if (ResultType.isNull()) return QualType();
4689    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4690      return LHS;
4691    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4692      return RHS;
4693    return getPointerType(ResultType);
4694  }
4695  case Type::BlockPointer:
4696  {
4697    // Merge two block pointer types, while trying to preserve typedef info
4698    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4699    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
4700    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4701    if (ResultType.isNull()) return QualType();
4702    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4703      return LHS;
4704    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4705      return RHS;
4706    return getBlockPointerType(ResultType);
4707  }
4708  case Type::ConstantArray:
4709  {
4710    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4711    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4712    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4713      return QualType();
4714
4715    QualType LHSElem = getAsArrayType(LHS)->getElementType();
4716    QualType RHSElem = getAsArrayType(RHS)->getElementType();
4717    QualType ResultType = mergeTypes(LHSElem, RHSElem);
4718    if (ResultType.isNull()) return QualType();
4719    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4720      return LHS;
4721    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4722      return RHS;
4723    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4724                                          ArrayType::ArraySizeModifier(), 0);
4725    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4726                                          ArrayType::ArraySizeModifier(), 0);
4727    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4728    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
4729    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4730      return LHS;
4731    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4732      return RHS;
4733    if (LVAT) {
4734      // FIXME: This isn't correct! But tricky to implement because
4735      // the array's size has to be the size of LHS, but the type
4736      // has to be different.
4737      return LHS;
4738    }
4739    if (RVAT) {
4740      // FIXME: This isn't correct! But tricky to implement because
4741      // the array's size has to be the size of RHS, but the type
4742      // has to be different.
4743      return RHS;
4744    }
4745    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4746    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
4747    return getIncompleteArrayType(ResultType,
4748                                  ArrayType::ArraySizeModifier(), 0);
4749  }
4750  case Type::FunctionNoProto:
4751    return mergeFunctionTypes(LHS, RHS);
4752  case Type::Record:
4753  case Type::Enum:
4754    return QualType();
4755  case Type::Builtin:
4756    // Only exactly equal builtin types are compatible, which is tested above.
4757    return QualType();
4758  case Type::Complex:
4759    // Distinct complex types are incompatible.
4760    return QualType();
4761  case Type::Vector:
4762    // FIXME: The merged type should be an ExtVector!
4763    if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
4764      return LHS;
4765    return QualType();
4766  case Type::ObjCInterface: {
4767    // Check if the interfaces are assignment compatible.
4768    // FIXME: This should be type compatibility, e.g. whether
4769    // "LHS x; RHS x;" at global scope is legal.
4770    const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4771    const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
4772    if (LHSIface && RHSIface &&
4773        canAssignObjCInterfaces(LHSIface, RHSIface))
4774      return LHS;
4775
4776    return QualType();
4777  }
4778  case Type::ObjCObjectPointer: {
4779    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4780                                RHS->getAs<ObjCObjectPointerType>()))
4781      return LHS;
4782
4783    return QualType();
4784  }
4785  }
4786
4787  return QualType();
4788}
4789
4790//===----------------------------------------------------------------------===//
4791//                         Integer Predicates
4792//===----------------------------------------------------------------------===//
4793
4794unsigned ASTContext::getIntWidth(QualType T) {
4795  if (T->isBooleanType())
4796    return 1;
4797  if (EnumType *ET = dyn_cast<EnumType>(T))
4798    T = ET->getDecl()->getIntegerType();
4799  // For builtin types, just use the standard type sizing method
4800  return (unsigned)getTypeSize(T);
4801}
4802
4803QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4804  assert(T->isSignedIntegerType() && "Unexpected type");
4805
4806  // Turn <4 x signed int> -> <4 x unsigned int>
4807  if (const VectorType *VTy = T->getAs<VectorType>())
4808    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4809             VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
4810
4811  // For enums, we return the unsigned version of the base type.
4812  if (const EnumType *ETy = T->getAs<EnumType>())
4813    T = ETy->getDecl()->getIntegerType();
4814
4815  const BuiltinType *BTy = T->getAs<BuiltinType>();
4816  assert(BTy && "Unexpected signed integer type");
4817  switch (BTy->getKind()) {
4818  case BuiltinType::Char_S:
4819  case BuiltinType::SChar:
4820    return UnsignedCharTy;
4821  case BuiltinType::Short:
4822    return UnsignedShortTy;
4823  case BuiltinType::Int:
4824    return UnsignedIntTy;
4825  case BuiltinType::Long:
4826    return UnsignedLongTy;
4827  case BuiltinType::LongLong:
4828    return UnsignedLongLongTy;
4829  case BuiltinType::Int128:
4830    return UnsignedInt128Ty;
4831  default:
4832    assert(0 && "Unexpected signed integer type");
4833    return QualType();
4834  }
4835}
4836
4837ExternalASTSource::~ExternalASTSource() { }
4838
4839void ExternalASTSource::PrintStats() { }
4840
4841
4842//===----------------------------------------------------------------------===//
4843//                          Builtin Type Computation
4844//===----------------------------------------------------------------------===//
4845
4846/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4847/// pointer over the consumed characters.  This returns the resultant type.
4848static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
4849                                  ASTContext::GetBuiltinTypeError &Error,
4850                                  bool AllowTypeModifiers = true) {
4851  // Modifiers.
4852  int HowLong = 0;
4853  bool Signed = false, Unsigned = false;
4854
4855  // Read the modifiers first.
4856  bool Done = false;
4857  while (!Done) {
4858    switch (*Str++) {
4859    default: Done = true; --Str; break;
4860    case 'S':
4861      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4862      assert(!Signed && "Can't use 'S' modifier multiple times!");
4863      Signed = true;
4864      break;
4865    case 'U':
4866      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4867      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4868      Unsigned = true;
4869      break;
4870    case 'L':
4871      assert(HowLong <= 2 && "Can't have LLLL modifier");
4872      ++HowLong;
4873      break;
4874    }
4875  }
4876
4877  QualType Type;
4878
4879  // Read the base type.
4880  switch (*Str++) {
4881  default: assert(0 && "Unknown builtin type letter!");
4882  case 'v':
4883    assert(HowLong == 0 && !Signed && !Unsigned &&
4884           "Bad modifiers used with 'v'!");
4885    Type = Context.VoidTy;
4886    break;
4887  case 'f':
4888    assert(HowLong == 0 && !Signed && !Unsigned &&
4889           "Bad modifiers used with 'f'!");
4890    Type = Context.FloatTy;
4891    break;
4892  case 'd':
4893    assert(HowLong < 2 && !Signed && !Unsigned &&
4894           "Bad modifiers used with 'd'!");
4895    if (HowLong)
4896      Type = Context.LongDoubleTy;
4897    else
4898      Type = Context.DoubleTy;
4899    break;
4900  case 's':
4901    assert(HowLong == 0 && "Bad modifiers used with 's'!");
4902    if (Unsigned)
4903      Type = Context.UnsignedShortTy;
4904    else
4905      Type = Context.ShortTy;
4906    break;
4907  case 'i':
4908    if (HowLong == 3)
4909      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4910    else if (HowLong == 2)
4911      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4912    else if (HowLong == 1)
4913      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4914    else
4915      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4916    break;
4917  case 'c':
4918    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4919    if (Signed)
4920      Type = Context.SignedCharTy;
4921    else if (Unsigned)
4922      Type = Context.UnsignedCharTy;
4923    else
4924      Type = Context.CharTy;
4925    break;
4926  case 'b': // boolean
4927    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4928    Type = Context.BoolTy;
4929    break;
4930  case 'z':  // size_t.
4931    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4932    Type = Context.getSizeType();
4933    break;
4934  case 'F':
4935    Type = Context.getCFConstantStringType();
4936    break;
4937  case 'a':
4938    Type = Context.getBuiltinVaListType();
4939    assert(!Type.isNull() && "builtin va list type not initialized!");
4940    break;
4941  case 'A':
4942    // This is a "reference" to a va_list; however, what exactly
4943    // this means depends on how va_list is defined. There are two
4944    // different kinds of va_list: ones passed by value, and ones
4945    // passed by reference.  An example of a by-value va_list is
4946    // x86, where va_list is a char*. An example of by-ref va_list
4947    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4948    // we want this argument to be a char*&; for x86-64, we want
4949    // it to be a __va_list_tag*.
4950    Type = Context.getBuiltinVaListType();
4951    assert(!Type.isNull() && "builtin va list type not initialized!");
4952    if (Type->isArrayType()) {
4953      Type = Context.getArrayDecayedType(Type);
4954    } else {
4955      Type = Context.getLValueReferenceType(Type);
4956    }
4957    break;
4958  case 'V': {
4959    char *End;
4960    unsigned NumElements = strtoul(Str, &End, 10);
4961    assert(End != Str && "Missing vector size");
4962
4963    Str = End;
4964
4965    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4966    // FIXME: Don't know what to do about AltiVec.
4967    Type = Context.getVectorType(ElementType, NumElements, false, false);
4968    break;
4969  }
4970  case 'X': {
4971    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4972    Type = Context.getComplexType(ElementType);
4973    break;
4974  }
4975  case 'P':
4976    Type = Context.getFILEType();
4977    if (Type.isNull()) {
4978      Error = ASTContext::GE_Missing_stdio;
4979      return QualType();
4980    }
4981    break;
4982  case 'J':
4983    if (Signed)
4984      Type = Context.getsigjmp_bufType();
4985    else
4986      Type = Context.getjmp_bufType();
4987
4988    if (Type.isNull()) {
4989      Error = ASTContext::GE_Missing_setjmp;
4990      return QualType();
4991    }
4992    break;
4993  }
4994
4995  if (!AllowTypeModifiers)
4996    return Type;
4997
4998  Done = false;
4999  while (!Done) {
5000    switch (*Str++) {
5001      default: Done = true; --Str; break;
5002      case '*':
5003        Type = Context.getPointerType(Type);
5004        break;
5005      case '&':
5006        Type = Context.getLValueReferenceType(Type);
5007        break;
5008      // FIXME: There's no way to have a built-in with an rvalue ref arg.
5009      case 'C':
5010        Type = Type.withConst();
5011        break;
5012      case 'D':
5013        Type = Context.getVolatileType(Type);
5014        break;
5015    }
5016  }
5017
5018  return Type;
5019}
5020
5021/// GetBuiltinType - Return the type for the specified builtin.
5022QualType ASTContext::GetBuiltinType(unsigned id,
5023                                    GetBuiltinTypeError &Error) {
5024  const char *TypeStr = BuiltinInfo.GetTypeString(id);
5025
5026  llvm::SmallVector<QualType, 8> ArgTypes;
5027
5028  Error = GE_None;
5029  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5030  if (Error != GE_None)
5031    return QualType();
5032  while (TypeStr[0] && TypeStr[0] != '.') {
5033    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5034    if (Error != GE_None)
5035      return QualType();
5036
5037    // Do array -> pointer decay.  The builtin should use the decayed type.
5038    if (Ty->isArrayType())
5039      Ty = getArrayDecayedType(Ty);
5040
5041    ArgTypes.push_back(Ty);
5042  }
5043
5044  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5045         "'.' should only occur at end of builtin type list!");
5046
5047  // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5048  if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5049    return getFunctionNoProtoType(ResType);
5050
5051  // FIXME: Should we create noreturn types?
5052  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
5053                         TypeStr[0] == '.', 0, false, false, 0, 0,
5054                         false, CC_Default);
5055}
5056
5057QualType
5058ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5059  // Perform the usual unary conversions. We do this early so that
5060  // integral promotions to "int" can allow us to exit early, in the
5061  // lhs == rhs check. Also, for conversion purposes, we ignore any
5062  // qualifiers.  For example, "const float" and "float" are
5063  // equivalent.
5064  if (lhs->isPromotableIntegerType())
5065    lhs = getPromotedIntegerType(lhs);
5066  else
5067    lhs = lhs.getUnqualifiedType();
5068  if (rhs->isPromotableIntegerType())
5069    rhs = getPromotedIntegerType(rhs);
5070  else
5071    rhs = rhs.getUnqualifiedType();
5072
5073  // If both types are identical, no conversion is needed.
5074  if (lhs == rhs)
5075    return lhs;
5076
5077  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5078  // The caller can deal with this (e.g. pointer + int).
5079  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5080    return lhs;
5081
5082  // At this point, we have two different arithmetic types.
5083
5084  // Handle complex types first (C99 6.3.1.8p1).
5085  if (lhs->isComplexType() || rhs->isComplexType()) {
5086    // if we have an integer operand, the result is the complex type.
5087    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
5088      // convert the rhs to the lhs complex type.
5089      return lhs;
5090    }
5091    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
5092      // convert the lhs to the rhs complex type.
5093      return rhs;
5094    }
5095    // This handles complex/complex, complex/float, or float/complex.
5096    // When both operands are complex, the shorter operand is converted to the
5097    // type of the longer, and that is the type of the result. This corresponds
5098    // to what is done when combining two real floating-point operands.
5099    // The fun begins when size promotion occur across type domains.
5100    // From H&S 6.3.4: When one operand is complex and the other is a real
5101    // floating-point type, the less precise type is converted, within it's
5102    // real or complex domain, to the precision of the other type. For example,
5103    // when combining a "long double" with a "double _Complex", the
5104    // "double _Complex" is promoted to "long double _Complex".
5105    int result = getFloatingTypeOrder(lhs, rhs);
5106
5107    if (result > 0) { // The left side is bigger, convert rhs.
5108      rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
5109    } else if (result < 0) { // The right side is bigger, convert lhs.
5110      lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
5111    }
5112    // At this point, lhs and rhs have the same rank/size. Now, make sure the
5113    // domains match. This is a requirement for our implementation, C99
5114    // does not require this promotion.
5115    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5116      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5117        return rhs;
5118      } else { // handle "_Complex double, double".
5119        return lhs;
5120      }
5121    }
5122    return lhs; // The domain/size match exactly.
5123  }
5124  // Now handle "real" floating types (i.e. float, double, long double).
5125  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5126    // if we have an integer operand, the result is the real floating type.
5127    if (rhs->isIntegerType()) {
5128      // convert rhs to the lhs floating point type.
5129      return lhs;
5130    }
5131    if (rhs->isComplexIntegerType()) {
5132      // convert rhs to the complex floating point type.
5133      return getComplexType(lhs);
5134    }
5135    if (lhs->isIntegerType()) {
5136      // convert lhs to the rhs floating point type.
5137      return rhs;
5138    }
5139    if (lhs->isComplexIntegerType()) {
5140      // convert lhs to the complex floating point type.
5141      return getComplexType(rhs);
5142    }
5143    // We have two real floating types, float/complex combos were handled above.
5144    // Convert the smaller operand to the bigger result.
5145    int result = getFloatingTypeOrder(lhs, rhs);
5146    if (result > 0) // convert the rhs
5147      return lhs;
5148    assert(result < 0 && "illegal float comparison");
5149    return rhs;   // convert the lhs
5150  }
5151  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5152    // Handle GCC complex int extension.
5153    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5154    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5155
5156    if (lhsComplexInt && rhsComplexInt) {
5157      if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
5158                              rhsComplexInt->getElementType()) >= 0)
5159        return lhs; // convert the rhs
5160      return rhs;
5161    } else if (lhsComplexInt && rhs->isIntegerType()) {
5162      // convert the rhs to the lhs complex type.
5163      return lhs;
5164    } else if (rhsComplexInt && lhs->isIntegerType()) {
5165      // convert the lhs to the rhs complex type.
5166      return rhs;
5167    }
5168  }
5169  // Finally, we have two differing integer types.
5170  // The rules for this case are in C99 6.3.1.8
5171  int compare = getIntegerTypeOrder(lhs, rhs);
5172  bool lhsSigned = lhs->isSignedIntegerType(),
5173       rhsSigned = rhs->isSignedIntegerType();
5174  QualType destType;
5175  if (lhsSigned == rhsSigned) {
5176    // Same signedness; use the higher-ranked type
5177    destType = compare >= 0 ? lhs : rhs;
5178  } else if (compare != (lhsSigned ? 1 : -1)) {
5179    // The unsigned type has greater than or equal rank to the
5180    // signed type, so use the unsigned type
5181    destType = lhsSigned ? rhs : lhs;
5182  } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5183    // The two types are different widths; if we are here, that
5184    // means the signed type is larger than the unsigned type, so
5185    // use the signed type.
5186    destType = lhsSigned ? lhs : rhs;
5187  } else {
5188    // The signed type is higher-ranked than the unsigned type,
5189    // but isn't actually any bigger (like unsigned int and long
5190    // on most 32-bit systems).  Use the unsigned type corresponding
5191    // to the signed type.
5192    destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5193  }
5194  return destType;
5195}
5196