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