blob: 00a7987a2b249386b4947625413d811f6fe05f82 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000021#include "clang/AST/ExternalASTSource.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000024#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000026#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000027#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000028#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/Support/raw_ostream.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000030#include "RecordLayoutBuilder.h"
31
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
34enum FloatingRank {
35 FloatRank, DoubleRank, LongDoubleRank
36};
37
Chris Lattner61710852008-10-05 17:34:18 +000038ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +000039 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +000040 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +000041 Builtin::Context &builtins,
Mike Stump1eb44332009-09-09 15:08:12 +000042 bool FreeMem, unsigned size_reserve) :
43 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +000044 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +000045 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Douglas Gregorc6fbbed2010-03-19 22:13:20 +000046 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000047 Idents(idents), Selectors(sels),
John McCall0c01d182010-03-24 05:22:00 +000048 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts),
49 LastSDM(0, 0) {
David Chisnall0f436562009-08-17 16:35:33 +000050 ObjCIdRedefinitionType = QualType();
51 ObjCClassRedefinitionType = QualType();
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +000052 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +000053 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +000054 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +000055 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +000056}
57
Reid Spencer5f016e22007-07-11 17:01:13 +000058ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +000059 // Release the DenseMaps associated with DeclContext objects.
60 // FIXME: Is this the ideal solution?
61 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +000062
63 // Release all of the memory associated with overridden C++ methods.
64 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
65 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
66 OM != OMEnd; ++OM)
67 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +000068
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000069 if (FreeMemory) {
70 // Deallocate all the types.
71 while (!Types.empty()) {
72 Types.back()->Destroy(*this);
73 Types.pop_back();
74 }
Eli Friedmanb26153c2008-05-27 03:08:09 +000075
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000076 for (llvm::FoldingSet<ExtQuals>::iterator
77 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
78 // Increment in loop to prevent using deallocated memory.
John McCall0953e762009-09-24 19:53:00 +000079 Deallocate(&*I++);
Nuno Lopesb74668e2008-12-17 22:30:25 +000080 }
Nuno Lopesb74668e2008-12-17 22:30:25 +000081
Ted Kremenek503524a2010-03-08 20:56:29 +000082 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
83 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
84 // Increment in loop to prevent using deallocated memory.
85 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
86 R->Destroy(*this);
87 }
Ted Kremenekbbfd68d2009-12-23 21:13:52 +000088
Ted Kremenek503524a2010-03-08 20:56:29 +000089 for (llvm::DenseMap<const ObjCContainerDecl*,
90 const ASTRecordLayout*>::iterator
91 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
92 // Increment in loop to prevent using deallocated memory.
93 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
94 R->Destroy(*this);
95 }
Nuno Lopesb74668e2008-12-17 22:30:25 +000096 }
97
Douglas Gregorab452ba2009-03-26 23:50:42 +000098 // Destroy nested-name-specifiers.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +000099 for (llvm::FoldingSet<NestedNameSpecifier>::iterator
100 NNS = NestedNameSpecifiers.begin(),
Mike Stump1eb44332009-09-09 15:08:12 +0000101 NNSEnd = NestedNameSpecifiers.end();
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000102 NNS != NNSEnd; ) {
103 // Increment in loop to prevent using deallocated memory.
Douglas Gregor1ae0afa2009-03-27 23:54:10 +0000104 (*NNS++).Destroy(*this);
Ted Kremenekbbfd68d2009-12-23 21:13:52 +0000105 }
Douglas Gregorab452ba2009-03-26 23:50:42 +0000106
107 if (GlobalNestedNameSpecifier)
108 GlobalNestedNameSpecifier->Destroy(*this);
109
Eli Friedmanb26153c2008-05-27 03:08:09 +0000110 TUDecl->Destroy(*this);
Reid Spencer5f016e22007-07-11 17:01:13 +0000111}
112
Mike Stump1eb44332009-09-09 15:08:12 +0000113void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000114ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
115 ExternalSource.reset(Source.take());
116}
117
Reid Spencer5f016e22007-07-11 17:01:13 +0000118void ASTContext::PrintStats() const {
119 fprintf(stderr, "*** AST Context Stats:\n");
120 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000121
Douglas Gregordbe833d2009-05-26 14:40:08 +0000122 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000123#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000124#define ABSTRACT_TYPE(Name, Parent)
125#include "clang/AST/TypeNodes.def"
126 0 // Extra
127 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000128
Reid Spencer5f016e22007-07-11 17:01:13 +0000129 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
130 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000131 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 }
133
Douglas Gregordbe833d2009-05-26 14:40:08 +0000134 unsigned Idx = 0;
135 unsigned TotalBytes = 0;
136#define TYPE(Name, Parent) \
137 if (counts[Idx]) \
138 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
139 TotalBytes += counts[Idx] * sizeof(Name##Type); \
140 ++Idx;
141#define ABSTRACT_TYPE(Name, Parent)
142#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Douglas Gregordbe833d2009-05-26 14:40:08 +0000144 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor2cf26342009-04-09 22:27:44 +0000145
146 if (ExternalSource.get()) {
147 fprintf(stderr, "\n");
148 ExternalSource->PrintStats();
149 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000150}
151
152
John McCalle27ec8a2009-10-23 23:03:21 +0000153void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000154 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000155 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000156 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000157}
158
Reid Spencer5f016e22007-07-11 17:01:13 +0000159void ASTContext::InitBuiltinTypes() {
160 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000161
Reid Spencer5f016e22007-07-11 17:01:13 +0000162 // C99 6.2.5p19.
163 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Reid Spencer5f016e22007-07-11 17:01:13 +0000165 // C99 6.2.5p2.
166 InitBuiltinType(BoolTy, BuiltinType::Bool);
167 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000168 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 InitBuiltinType(CharTy, BuiltinType::Char_S);
170 else
171 InitBuiltinType(CharTy, BuiltinType::Char_U);
172 // C99 6.2.5p4.
173 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
174 InitBuiltinType(ShortTy, BuiltinType::Short);
175 InitBuiltinType(IntTy, BuiltinType::Int);
176 InitBuiltinType(LongTy, BuiltinType::Long);
177 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000178
Reid Spencer5f016e22007-07-11 17:01:13 +0000179 // C99 6.2.5p6.
180 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
181 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
182 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
183 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
184 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 // C99 6.2.5p10.
187 InitBuiltinType(FloatTy, BuiltinType::Float);
188 InitBuiltinType(DoubleTy, BuiltinType::Double);
189 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000190
Chris Lattner2df9ced2009-04-30 02:43:43 +0000191 // GNU extension, 128-bit integers.
192 InitBuiltinType(Int128Ty, BuiltinType::Int128);
193 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
194
Chris Lattner3a250322009-02-26 23:43:47 +0000195 if (LangOpts.CPlusPlus) // C++ 3.9.1p5
196 InitBuiltinType(WCharTy, BuiltinType::WChar);
197 else // C99
198 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000199
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000200 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
201 InitBuiltinType(Char16Ty, BuiltinType::Char16);
202 else // C99
203 Char16Ty = getFromTargetType(Target.getChar16Type());
204
205 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
206 InitBuiltinType(Char32Ty, BuiltinType::Char32);
207 else // C99
208 Char32Ty = getFromTargetType(Target.getChar32Type());
209
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000210 // Placeholder type for functions.
Douglas Gregor898574e2008-12-05 23:32:09 +0000211 InitBuiltinType(OverloadTy, BuiltinType::Overload);
212
213 // Placeholder type for type-dependent expressions whose type is
214 // completely unknown. No code should ever check a type against
215 // DependentTy and users should never see it; however, it is here to
216 // help diagnose failures to properly check for type-dependent
217 // expressions.
218 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000219
Mike Stump1eb44332009-09-09 15:08:12 +0000220 // Placeholder type for C++0x auto declarations whose real type has
Anders Carlssone89d1592009-06-26 18:41:36 +0000221 // not yet been deduced.
222 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
Mike Stump1eb44332009-09-09 15:08:12 +0000223
Reid Spencer5f016e22007-07-11 17:01:13 +0000224 // C99 6.2.5p11.
225 FloatComplexTy = getComplexType(FloatTy);
226 DoubleComplexTy = getComplexType(DoubleTy);
227 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000228
Steve Naroff7e219e42007-10-15 14:41:52 +0000229 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Steve Naroffde2e22d2009-07-15 18:40:39 +0000231 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
232 ObjCIdTypedefType = QualType();
233 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000234 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000235
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000236 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000237 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
238 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000239 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000240
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000241 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000243 // void * type
244 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000245
246 // nullptr type (C++0x 2.14.7)
247 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000248}
249
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000250MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000251ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000252 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000253 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000254 = InstantiatedFromStaticDataMember.find(Var);
255 if (Pos == InstantiatedFromStaticDataMember.end())
256 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Douglas Gregor7caa6822009-07-24 20:34:43 +0000258 return Pos->second;
259}
260
Mike Stump1eb44332009-09-09 15:08:12 +0000261void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000262ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
263 TemplateSpecializationKind TSK) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000264 assert(Inst->isStaticDataMember() && "Not a static data member");
265 assert(Tmpl->isStaticDataMember() && "Not a static data member");
266 assert(!InstantiatedFromStaticDataMember[Inst] &&
267 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000268 InstantiatedFromStaticDataMember[Inst]
269 = new (*this) MemberSpecializationInfo(Tmpl, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000270}
271
John McCall7ba107a2009-11-18 02:36:19 +0000272NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000273ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000274 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000275 = InstantiatedFromUsingDecl.find(UUD);
276 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000277 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Anders Carlsson0d8df782009-08-29 19:37:28 +0000279 return Pos->second;
280}
281
282void
John McCalled976492009-12-04 22:46:56 +0000283ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
284 assert((isa<UsingDecl>(Pattern) ||
285 isa<UnresolvedUsingValueDecl>(Pattern) ||
286 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
287 "pattern decl is not a using decl");
288 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
289 InstantiatedFromUsingDecl[Inst] = Pattern;
290}
291
292UsingShadowDecl *
293ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
294 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
295 = InstantiatedFromUsingShadowDecl.find(Inst);
296 if (Pos == InstantiatedFromUsingShadowDecl.end())
297 return 0;
298
299 return Pos->second;
300}
301
302void
303ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
304 UsingShadowDecl *Pattern) {
305 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
306 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000307}
308
Anders Carlssond8b285f2009-09-01 04:26:58 +0000309FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
310 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
311 = InstantiatedFromUnnamedFieldDecl.find(Field);
312 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
313 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Anders Carlssond8b285f2009-09-01 04:26:58 +0000315 return Pos->second;
316}
317
318void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
319 FieldDecl *Tmpl) {
320 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
321 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
322 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
323 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Anders Carlssond8b285f2009-09-01 04:26:58 +0000325 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
326}
327
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000328CXXMethodVector::iterator CXXMethodVector::begin() const {
329 if ((Storage & 0x01) == 0)
330 return reinterpret_cast<iterator>(&Storage);
331
332 vector_type *Vec = reinterpret_cast<vector_type *>(Storage & ~0x01);
333 return &Vec->front();
334}
335
336CXXMethodVector::iterator CXXMethodVector::end() const {
337 if ((Storage & 0x01) == 0) {
338 if (Storage == 0)
339 return reinterpret_cast<iterator>(&Storage);
340
341 return reinterpret_cast<iterator>(&Storage) + 1;
342 }
343
344 vector_type *Vec = reinterpret_cast<vector_type *>(Storage & ~0x01);
345 return &Vec->front() + Vec->size();
346}
347
348void CXXMethodVector::push_back(const CXXMethodDecl *Method) {
349 if (Storage == 0) {
350 // 0 -> 1 element.
351 Storage = reinterpret_cast<uintptr_t>(Method);
352 return;
353 }
354
355 vector_type *Vec;
356 if ((Storage & 0x01) == 0) {
357 // 1 -> 2 elements. Allocate a new vector and push the element into that
358 // vector.
359 Vec = new vector_type;
360 Vec->push_back(reinterpret_cast<const CXXMethodDecl *>(Storage));
361 Storage = reinterpret_cast<uintptr_t>(Vec) | 0x01;
362 } else
363 Vec = reinterpret_cast<vector_type *>(Storage & ~0x01);
364
365 // Add the new method to the vector.
366 Vec->push_back(Method);
367}
368
369void CXXMethodVector::Destroy() {
370 if (Storage & 0x01)
371 delete reinterpret_cast<vector_type *>(Storage & ~0x01);
372
373 Storage = 0;
374}
375
376
377ASTContext::overridden_cxx_method_iterator
378ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
379 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
380 = OverriddenMethods.find(Method);
381 if (Pos == OverriddenMethods.end())
382 return 0;
383
384 return Pos->second.begin();
385}
386
387ASTContext::overridden_cxx_method_iterator
388ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
389 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
390 = OverriddenMethods.find(Method);
391 if (Pos == OverriddenMethods.end())
392 return 0;
393
394 return Pos->second.end();
395}
396
397void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
398 const CXXMethodDecl *Overridden) {
399 OverriddenMethods[Method].push_back(Overridden);
400}
401
Douglas Gregor2e222532009-07-02 17:08:52 +0000402namespace {
Mike Stump1eb44332009-09-09 15:08:12 +0000403 class BeforeInTranslationUnit
Douglas Gregor2e222532009-07-02 17:08:52 +0000404 : std::binary_function<SourceRange, SourceRange, bool> {
405 SourceManager *SourceMgr;
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Douglas Gregor2e222532009-07-02 17:08:52 +0000407 public:
408 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Douglas Gregor2e222532009-07-02 17:08:52 +0000410 bool operator()(SourceRange X, SourceRange Y) {
411 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
412 }
413 };
414}
415
Chris Lattner464175b2007-07-18 17:52:12 +0000416//===----------------------------------------------------------------------===//
417// Type Sizing and Analysis
418//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000419
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000420/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
421/// scalar floating point type.
422const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000423 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000424 assert(BT && "Not a floating point type!");
425 switch (BT->getKind()) {
426 default: assert(0 && "Not a floating point type!");
427 case BuiltinType::Float: return Target.getFloatFormat();
428 case BuiltinType::Double: return Target.getDoubleFormat();
429 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
430 }
431}
432
Ken Dyck8b752f12010-01-27 17:10:57 +0000433/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000434/// specified decl. Note that bitfields do not have a valid alignment, so
435/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000436/// If @p RefAsPointee, references are treated like their underlying type
437/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000438CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000439 unsigned Align = Target.getCharWidth();
440
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000441 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000442 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000443
Chris Lattneraf707ab2009-01-24 21:53:27 +0000444 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
445 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000446 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000447 if (RefAsPointee)
448 T = RT->getPointeeType();
449 else
450 T = getPointerType(RT->getPointeeType());
451 }
452 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000453 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000454 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
455 T = cast<ArrayType>(T)->getElementType();
456
457 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
458 }
Charles Davis05f62472010-02-23 04:52:00 +0000459 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
460 // In the case of a field in a packed struct, we want the minimum
461 // of the alignment of the field and the alignment of the struct.
462 Align = std::min(Align,
463 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
464 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000465 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000466
Ken Dyck8b752f12010-01-27 17:10:57 +0000467 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000468}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000469
Chris Lattnera7674d82007-07-13 22:13:22 +0000470/// getTypeSize - Return the size of the specified type, in bits. This method
471/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000472///
473/// FIXME: Pointers into different addr spaces could have different sizes and
474/// alignment requirements: getPointerInfo should take an AddrSpace, this
475/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000476std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000477ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000478 uint64_t Width=0;
479 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000480 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000481#define TYPE(Class, Base)
482#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000483#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000484#define DEPENDENT_TYPE(Class, Base) case Type::Class:
485#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000486 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000487 break;
488
Chris Lattner692233e2007-07-13 22:27:08 +0000489 case Type::FunctionNoProto:
490 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000491 // GCC extension: alignof(function) = 32 bits
492 Width = 0;
493 Align = 32;
494 break;
495
Douglas Gregor72564e72009-02-26 23:50:07 +0000496 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000497 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000498 Width = 0;
499 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
500 break;
501
Steve Narofffb22d962007-08-30 01:06:46 +0000502 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000503 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Chris Lattner98be4942008-03-05 18:54:05 +0000505 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000506 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000507 Align = EltInfo.second;
508 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000509 }
Nate Begeman213541a2008-04-18 23:10:10 +0000510 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000511 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000512 const VectorType *VT = cast<VectorType>(T);
513 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
514 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000515 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000516 // If the alignment is not a power of 2, round up to the next power of 2.
517 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000518 if (VT->getNumElements() & (VT->getNumElements()-1)) {
519 Align = llvm::NextPowerOf2(Align);
520 Width = llvm::RoundUpToAlignment(Width, Align);
521 }
Chris Lattner030d8842007-07-19 22:06:24 +0000522 break;
523 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000524
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000525 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000526 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000527 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000528 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000529 // GCC extension: alignof(void) = 8 bits.
530 Width = 0;
531 Align = 8;
532 break;
533
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000534 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000535 Width = Target.getBoolWidth();
536 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000537 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000538 case BuiltinType::Char_S:
539 case BuiltinType::Char_U:
540 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000541 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000542 Width = Target.getCharWidth();
543 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000544 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000545 case BuiltinType::WChar:
546 Width = Target.getWCharWidth();
547 Align = Target.getWCharAlign();
548 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000549 case BuiltinType::Char16:
550 Width = Target.getChar16Width();
551 Align = Target.getChar16Align();
552 break;
553 case BuiltinType::Char32:
554 Width = Target.getChar32Width();
555 Align = Target.getChar32Align();
556 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000557 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000558 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000559 Width = Target.getShortWidth();
560 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000561 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000562 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000563 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000564 Width = Target.getIntWidth();
565 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000566 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000567 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000568 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000569 Width = Target.getLongWidth();
570 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000571 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000572 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000573 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000574 Width = Target.getLongLongWidth();
575 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000576 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000577 case BuiltinType::Int128:
578 case BuiltinType::UInt128:
579 Width = 128;
580 Align = 128; // int128_t is 128-bit aligned on all targets.
581 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000582 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000583 Width = Target.getFloatWidth();
584 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000585 break;
586 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000587 Width = Target.getDoubleWidth();
588 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000589 break;
590 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000591 Width = Target.getLongDoubleWidth();
592 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000593 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000594 case BuiltinType::NullPtr:
595 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
596 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000597 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000598 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000599 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000600 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000601 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000602 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000603 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000604 case Type::BlockPointer: {
605 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
606 Width = Target.getPointerWidth(AS);
607 Align = Target.getPointerAlign(AS);
608 break;
609 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000610 case Type::LValueReference:
611 case Type::RValueReference: {
612 // alignof and sizeof should never enter this code path here, so we go
613 // the pointer route.
614 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
615 Width = Target.getPointerWidth(AS);
616 Align = Target.getPointerAlign(AS);
617 break;
618 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000619 case Type::Pointer: {
620 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000621 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000622 Align = Target.getPointerAlign(AS);
623 break;
624 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000625 case Type::MemberPointer: {
Sebastian Redlf30208a2009-01-24 21:16:55 +0000626 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000627 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000628 getTypeInfo(getPointerDiffType());
629 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000630 if (Pointee->isFunctionType())
631 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000632 Align = PtrDiffInfo.second;
633 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000634 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000635 case Type::Complex: {
636 // Complex types have the same alignment as their elements, but twice the
637 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000638 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000639 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000640 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000641 Align = EltInfo.second;
642 break;
643 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000644 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000645 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000646 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
647 Width = Layout.getSize();
648 Align = Layout.getAlignment();
649 break;
650 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000651 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000652 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000653 const TagType *TT = cast<TagType>(T);
654
655 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000656 Width = 1;
657 Align = 1;
658 break;
659 }
Mike Stump1eb44332009-09-09 15:08:12 +0000660
Daniel Dunbar1d751182008-11-08 05:48:37 +0000661 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000662 return getTypeInfo(ET->getDecl()->getIntegerType());
663
Daniel Dunbar1d751182008-11-08 05:48:37 +0000664 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000665 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
666 Width = Layout.getSize();
667 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000668 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000669 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000670
Chris Lattner9fcfe922009-10-22 05:17:15 +0000671 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000672 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
673 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000674
Chris Lattner9fcfe922009-10-22 05:17:15 +0000675 case Type::Elaborated:
676 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
677 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000678
Douglas Gregor18857642009-04-30 17:32:17 +0000679 case Type::Typedef: {
680 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000681 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000682 Align = std::max(Aligned->getMaxAlignment(),
683 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000684 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
685 } else
686 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000687 break;
Chris Lattner71763312008-04-06 22:05:18 +0000688 }
Douglas Gregor18857642009-04-30 17:32:17 +0000689
690 case Type::TypeOfExpr:
691 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
692 .getTypePtr());
693
694 case Type::TypeOf:
695 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
696
Anders Carlsson395b4752009-06-24 19:06:50 +0000697 case Type::Decltype:
698 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
699 .getTypePtr());
700
Douglas Gregor18857642009-04-30 17:32:17 +0000701 case Type::QualifiedName:
702 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000703
John McCall3cb0ebd2010-03-10 03:28:59 +0000704 case Type::InjectedClassName:
705 return getTypeInfo(cast<InjectedClassNameType>(T)
706 ->getUnderlyingType().getTypePtr());
707
Douglas Gregor18857642009-04-30 17:32:17 +0000708 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000709 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000710 "Cannot request the size of a dependent type");
711 // FIXME: this is likely to be wrong once we support template
712 // aliases, since a template alias could refer to a typedef that
713 // has an __aligned__ attribute on it.
714 return getTypeInfo(getCanonicalType(T));
715 }
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Chris Lattner464175b2007-07-18 17:52:12 +0000717 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000718 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000719}
720
Ken Dyckbdc601b2009-12-22 14:23:30 +0000721/// getTypeSizeInChars - Return the size of the specified type, in characters.
722/// This method does not work on incomplete types.
723CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000724 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000725}
726CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000727 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000728}
729
Ken Dyck16e20cc2010-01-26 17:25:18 +0000730/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000731/// characters. This method does not work on incomplete types.
732CharUnits ASTContext::getTypeAlignInChars(QualType T) {
733 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
734}
735CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
736 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
737}
738
Chris Lattner34ebde42009-01-27 18:08:34 +0000739/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
740/// type for the current target in bits. This can be different than the ABI
741/// alignment in cases where it is beneficial for performance to overalign
742/// a data type.
743unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
744 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000745
746 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000747 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000748 T = CT->getElementType().getTypePtr();
749 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
750 T->isSpecificBuiltinType(BuiltinType::LongLong))
751 return std::max(ABIAlign, (unsigned)getTypeSize(T));
752
Chris Lattner34ebde42009-01-27 18:08:34 +0000753 return ABIAlign;
754}
755
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000756static void CollectLocalObjCIvars(ASTContext *Ctx,
757 const ObjCInterfaceDecl *OI,
758 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000759 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
760 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000761 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000762 if (!IVDecl->isInvalidDecl())
763 Fields.push_back(cast<FieldDecl>(IVDecl));
764 }
765}
766
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000767void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
768 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
769 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
770 CollectObjCIvars(SuperClass, Fields);
771 CollectLocalObjCIvars(this, OI, Fields);
772}
773
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000774/// ShallowCollectObjCIvars -
775/// Collect all ivars, including those synthesized, in the current class.
776///
777void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000778 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000779 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
780 E = OI->ivar_end(); I != E; ++I) {
781 Ivars.push_back(*I);
782 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000783
784 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000785}
786
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000787/// CollectNonClassIvars -
788/// This routine collects all other ivars which are not declared in the class.
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000789/// This includes synthesized ivars (via @synthesize) and those in
790// class's @implementation.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000791///
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000792void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000793 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000794 // Find ivars declared in class extension.
795 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
796 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
797 E = CDecl->ivar_end(); I != E; ++I) {
798 Ivars.push_back(*I);
799 }
800 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000801
Ted Kremenek7d2aa112010-03-11 19:44:54 +0000802 // Also add any ivar defined in this class's implementation. This
803 // includes synthesized ivars.
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000804 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
805 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
806 E = ImplDecl->ivar_end(); I != E; ++I)
807 Ivars.push_back(*I);
808 }
Fariborz Jahanian98200742009-05-12 18:14:29 +0000809}
810
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000811/// CollectInheritedProtocols - Collect all protocols in current class and
812/// those inherited by it.
813void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000814 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000815 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
816 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
817 PE = OI->protocol_end(); P != PE; ++P) {
818 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000819 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000820 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000821 PE = Proto->protocol_end(); P != PE; ++P) {
822 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000823 CollectInheritedProtocols(*P, Protocols);
824 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +0000825 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000826
827 // Categories of this Interface.
828 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
829 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
830 CollectInheritedProtocols(CDeclChain, Protocols);
831 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
832 while (SD) {
833 CollectInheritedProtocols(SD, Protocols);
834 SD = SD->getSuperClass();
835 }
836 return;
837 }
838 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
839 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
840 PE = OC->protocol_end(); P != PE; ++P) {
841 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000842 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000843 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
844 PE = Proto->protocol_end(); P != PE; ++P)
845 CollectInheritedProtocols(*P, Protocols);
846 }
847 return;
848 }
849 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
850 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
851 PE = OP->protocol_end(); P != PE; ++P) {
852 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +0000853 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +0000854 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
855 PE = Proto->protocol_end(); P != PE; ++P)
856 CollectInheritedProtocols(*P, Protocols);
857 }
858 return;
859 }
860}
861
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000862unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
863 unsigned count = 0;
864 // Count ivars declared in class extension.
865 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
866 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
867 E = CDecl->ivar_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000868 ++count;
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000869 }
870 }
871
872 // Count ivar defined in this class's implementation. This
873 // includes synthesized ivars.
874 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
875 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
876 E = ImplDecl->ivar_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000877 ++count;
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000878 return count;
879}
880
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000881/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
882ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
883 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
884 I = ObjCImpls.find(D);
885 if (I != ObjCImpls.end())
886 return cast<ObjCImplementationDecl>(I->second);
887 return 0;
888}
889/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
890ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
891 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
892 I = ObjCImpls.find(D);
893 if (I != ObjCImpls.end())
894 return cast<ObjCCategoryImplDecl>(I->second);
895 return 0;
896}
897
898/// \brief Set the implementation of ObjCInterfaceDecl.
899void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
900 ObjCImplementationDecl *ImplD) {
901 assert(IFaceD && ImplD && "Passed null params");
902 ObjCImpls[IFaceD] = ImplD;
903}
904/// \brief Set the implementation of ObjCCategoryDecl.
905void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
906 ObjCCategoryImplDecl *ImplD) {
907 assert(CatD && ImplD && "Passed null params");
908 ObjCImpls[CatD] = ImplD;
909}
910
John McCalla93c9342009-12-07 02:54:59 +0000911/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000912///
John McCalla93c9342009-12-07 02:54:59 +0000913/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000914/// the TypeLoc wrappers.
915///
916/// \param T the type that will be the basis for type source info. This type
917/// should refer to how the declarator was written in source code, not to
918/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +0000919TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +0000920 unsigned DataSize) {
921 if (!DataSize)
922 DataSize = TypeLoc::getFullDataSizeForType(T);
923 else
924 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +0000925 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +0000926
John McCalla93c9342009-12-07 02:54:59 +0000927 TypeSourceInfo *TInfo =
928 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
929 new (TInfo) TypeSourceInfo(T);
930 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +0000931}
932
John McCalla93c9342009-12-07 02:54:59 +0000933TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +0000934 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +0000935 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +0000936 DI->getTypeLoc().initialize(L);
937 return DI;
938}
939
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000940/// getInterfaceLayoutImpl - Get or compute information about the
941/// layout of the given interface.
942///
943/// \param Impl - If given, also include the layout of the interface's
944/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +0000945const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000946ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
947 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +0000948 assert(!D->isForwardDecl() && "Invalid interface decl!");
949
Devang Patel44a3dde2008-06-04 21:54:36 +0000950 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +0000951 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000952 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
953 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
954 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +0000955
Daniel Dunbar453addb2009-05-03 11:16:44 +0000956 // Add in synthesized ivar count if laying out an implementation.
957 if (Impl) {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +0000958 unsigned SynthCount = CountNonClassIvars(D);
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +0000959 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +0000960 // entry. Note we can't cache this because we simply free all
961 // entries later; however we shouldn't look up implementations
962 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000963 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +0000964 return getObjCLayout(D, 0);
965 }
966
Mike Stump1eb44332009-09-09 15:08:12 +0000967 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +0000968 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
969 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Devang Patel44a3dde2008-06-04 21:54:36 +0000971 return *NewEntry;
972}
973
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +0000974const ASTRecordLayout &
975ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
976 return getObjCLayout(D, 0);
977}
978
979const ASTRecordLayout &
980ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
981 return getObjCLayout(D->getClassInterface(), D);
982}
983
Devang Patel88a981b2007-11-01 19:11:01 +0000984/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +0000985/// specified record (struct/union/class), which indicates its size and field
986/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +0000987const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000988 D = D->getDefinition();
Ted Kremenek4b7c9832008-09-05 17:16:31 +0000989 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +0000990
Chris Lattner464175b2007-07-18 17:52:12 +0000991 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +0000992 // Note that we can't save a reference to the entry because this function
993 // is recursive.
994 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +0000995 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +0000996
Mike Stump1eb44332009-09-09 15:08:12 +0000997 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +0000998 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +0000999 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Chris Lattner5d2a6302007-07-18 18:26:58 +00001001 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001002}
1003
Anders Carlssonf53df232009-12-07 04:35:11 +00001004const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
Douglas Gregor952b0172010-02-11 01:04:33 +00001005 RD = cast<CXXRecordDecl>(RD->getDefinition());
Anders Carlssonf53df232009-12-07 04:35:11 +00001006 assert(RD && "Cannot get key function for forward declarations!");
1007
1008 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1009 if (!Entry)
1010 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1011 else
1012 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1013 "Key function changed!");
1014
1015 return Entry;
1016}
1017
Chris Lattnera7674d82007-07-13 22:13:22 +00001018//===----------------------------------------------------------------------===//
1019// Type creation/memoization methods
1020//===----------------------------------------------------------------------===//
1021
John McCall0953e762009-09-24 19:53:00 +00001022QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1023 unsigned Fast = Quals.getFastQualifiers();
1024 Quals.removeFastQualifiers();
1025
1026 // Check if we've already instantiated this type.
1027 llvm::FoldingSetNodeID ID;
1028 ExtQuals::Profile(ID, TypeNode, Quals);
1029 void *InsertPos = 0;
1030 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1031 assert(EQ->getQualifiers() == Quals);
1032 QualType T = QualType(EQ, Fast);
1033 return T;
1034 }
1035
John McCall6b304a02009-09-24 23:30:46 +00001036 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001037 ExtQualNodes.InsertNode(New, InsertPos);
1038 QualType T = QualType(New, Fast);
1039 return T;
1040}
1041
1042QualType ASTContext::getVolatileType(QualType T) {
1043 QualType CanT = getCanonicalType(T);
1044 if (CanT.isVolatileQualified()) return T;
1045
1046 QualifierCollector Quals;
1047 const Type *TypeNode = Quals.strip(T);
1048 Quals.addVolatile();
1049
1050 return getExtQualType(TypeNode, Quals);
1051}
1052
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001053QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001054 QualType CanT = getCanonicalType(T);
1055 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001056 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001057
John McCall0953e762009-09-24 19:53:00 +00001058 // If we are composing extended qualifiers together, merge together
1059 // into one ExtQuals node.
1060 QualifierCollector Quals;
1061 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001062
John McCall0953e762009-09-24 19:53:00 +00001063 // If this type already has an address space specified, it cannot get
1064 // another one.
1065 assert(!Quals.hasAddressSpace() &&
1066 "Type cannot be in multiple addr spaces!");
1067 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001068
John McCall0953e762009-09-24 19:53:00 +00001069 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001070}
1071
Chris Lattnerb7d25532009-02-18 22:53:11 +00001072QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001073 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001074 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001075 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001076 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001078 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001079 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001080 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001081 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1082 return getPointerType(ResultType);
1083 }
1084 }
Mike Stump1eb44332009-09-09 15:08:12 +00001085
John McCall0953e762009-09-24 19:53:00 +00001086 // If we are composing extended qualifiers together, merge together
1087 // into one ExtQuals node.
1088 QualifierCollector Quals;
1089 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001090
John McCall0953e762009-09-24 19:53:00 +00001091 // If this type already has an ObjCGC specified, it cannot get
1092 // another one.
1093 assert(!Quals.hasObjCGCAttr() &&
1094 "Type cannot have multiple ObjCGCs!");
1095 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001096
John McCall0953e762009-09-24 19:53:00 +00001097 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001098}
Chris Lattnera7674d82007-07-13 22:13:22 +00001099
Rafael Espindola264ba482010-03-30 20:24:48 +00001100static QualType getExtFunctionType(ASTContext& Context, QualType T,
1101 const FunctionType::ExtInfo &Info) {
John McCall0953e762009-09-24 19:53:00 +00001102 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001103 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1104 QualType Pointee = Pointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001105 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001106 if (ResultType == Pointee)
1107 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001108
1109 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001110 } else if (const BlockPointerType *BlockPointer
1111 = T->getAs<BlockPointerType>()) {
1112 QualType Pointee = BlockPointer->getPointeeType();
Rafael Espindola264ba482010-03-30 20:24:48 +00001113 ResultType = getExtFunctionType(Context, Pointee, Info);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001114 if (ResultType == Pointee)
1115 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001116
1117 ResultType = Context.getBlockPointerType(ResultType);
1118 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001119 if (F->getExtInfo() == Info)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001120 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001121
Douglas Gregor43c79c22009-12-09 00:47:37 +00001122 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001123 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001124 Info);
John McCall0953e762009-09-24 19:53:00 +00001125 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001126 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001127 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001128 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1129 FPT->getNumArgs(), FPT->isVariadic(),
1130 FPT->getTypeQuals(),
1131 FPT->hasExceptionSpec(),
1132 FPT->hasAnyExceptionSpec(),
1133 FPT->getNumExceptions(),
1134 FPT->exception_begin(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001135 Info);
John McCall0953e762009-09-24 19:53:00 +00001136 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001137 } else
1138 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001139
1140 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1141}
1142
1143QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001144 FunctionType::ExtInfo Info = getFunctionExtInfo(*T);
1145 return getExtFunctionType(*this, T,
1146 Info.withNoReturn(AddNoReturn));
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001147}
1148
1149QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001150 FunctionType::ExtInfo Info = getFunctionExtInfo(*T);
1151 return getExtFunctionType(*this, T,
1152 Info.withCallingConv(CallConv));
Mike Stump24556362009-07-25 21:26:53 +00001153}
1154
Reid Spencer5f016e22007-07-11 17:01:13 +00001155/// getComplexType - Return the uniqued reference to the type for a complex
1156/// number with the specified element type.
1157QualType ASTContext::getComplexType(QualType T) {
1158 // Unique pointers, to guarantee there is only one pointer of a particular
1159 // structure.
1160 llvm::FoldingSetNodeID ID;
1161 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Reid Spencer5f016e22007-07-11 17:01:13 +00001163 void *InsertPos = 0;
1164 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1165 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001166
Reid Spencer5f016e22007-07-11 17:01:13 +00001167 // If the pointee type isn't canonical, this won't be a canonical type either,
1168 // so fill in the canonical type field.
1169 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001170 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001171 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Reid Spencer5f016e22007-07-11 17:01:13 +00001173 // Get the new insert position for the node we care about.
1174 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001175 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001176 }
John McCall6b304a02009-09-24 23:30:46 +00001177 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001178 Types.push_back(New);
1179 ComplexTypes.InsertNode(New, InsertPos);
1180 return QualType(New, 0);
1181}
1182
Reid Spencer5f016e22007-07-11 17:01:13 +00001183/// getPointerType - Return the uniqued reference to the type for a pointer to
1184/// the specified type.
1185QualType ASTContext::getPointerType(QualType T) {
1186 // Unique pointers, to guarantee there is only one pointer of a particular
1187 // structure.
1188 llvm::FoldingSetNodeID ID;
1189 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Reid Spencer5f016e22007-07-11 17:01:13 +00001191 void *InsertPos = 0;
1192 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1193 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 // If the pointee type isn't canonical, this won't be a canonical type either,
1196 // so fill in the canonical type field.
1197 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001198 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001199 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Reid Spencer5f016e22007-07-11 17:01:13 +00001201 // Get the new insert position for the node we care about.
1202 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001203 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001204 }
John McCall6b304a02009-09-24 23:30:46 +00001205 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001206 Types.push_back(New);
1207 PointerTypes.InsertNode(New, InsertPos);
1208 return QualType(New, 0);
1209}
1210
Mike Stump1eb44332009-09-09 15:08:12 +00001211/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001212/// a pointer to the specified block.
1213QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001214 assert(T->isFunctionType() && "block of function types only");
1215 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001216 // structure.
1217 llvm::FoldingSetNodeID ID;
1218 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Steve Naroff5618bd42008-08-27 16:04:49 +00001220 void *InsertPos = 0;
1221 if (BlockPointerType *PT =
1222 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1223 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001224
1225 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001226 // type either so fill in the canonical type field.
1227 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001228 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001229 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Steve Naroff5618bd42008-08-27 16:04:49 +00001231 // Get the new insert position for the node we care about.
1232 BlockPointerType *NewIP =
1233 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001234 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001235 }
John McCall6b304a02009-09-24 23:30:46 +00001236 BlockPointerType *New
1237 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001238 Types.push_back(New);
1239 BlockPointerTypes.InsertNode(New, InsertPos);
1240 return QualType(New, 0);
1241}
1242
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001243/// getLValueReferenceType - Return the uniqued reference to the type for an
1244/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001245QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001246 // Unique pointers, to guarantee there is only one pointer of a particular
1247 // structure.
1248 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001249 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001250
1251 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001252 if (LValueReferenceType *RT =
1253 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001254 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001255
John McCall54e14c42009-10-22 22:37:11 +00001256 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1257
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 // If the referencee type isn't canonical, this won't be a canonical type
1259 // either, so fill in the canonical type field.
1260 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001261 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1262 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1263 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001264
Reid Spencer5f016e22007-07-11 17:01:13 +00001265 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001266 LValueReferenceType *NewIP =
1267 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001268 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001269 }
1270
John McCall6b304a02009-09-24 23:30:46 +00001271 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001272 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1273 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001275 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001276
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001277 return QualType(New, 0);
1278}
1279
1280/// getRValueReferenceType - Return the uniqued reference to the type for an
1281/// rvalue reference to the specified type.
1282QualType ASTContext::getRValueReferenceType(QualType T) {
1283 // Unique pointers, to guarantee there is only one pointer of a particular
1284 // structure.
1285 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001286 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001287
1288 void *InsertPos = 0;
1289 if (RValueReferenceType *RT =
1290 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1291 return QualType(RT, 0);
1292
John McCall54e14c42009-10-22 22:37:11 +00001293 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1294
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001295 // If the referencee type isn't canonical, this won't be a canonical type
1296 // either, so fill in the canonical type field.
1297 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001298 if (InnerRef || !T.isCanonical()) {
1299 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1300 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001301
1302 // Get the new insert position for the node we care about.
1303 RValueReferenceType *NewIP =
1304 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1305 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1306 }
1307
John McCall6b304a02009-09-24 23:30:46 +00001308 RValueReferenceType *New
1309 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001310 Types.push_back(New);
1311 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001312 return QualType(New, 0);
1313}
1314
Sebastian Redlf30208a2009-01-24 21:16:55 +00001315/// getMemberPointerType - Return the uniqued reference to the type for a
1316/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001317QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001318 // Unique pointers, to guarantee there is only one pointer of a particular
1319 // structure.
1320 llvm::FoldingSetNodeID ID;
1321 MemberPointerType::Profile(ID, T, Cls);
1322
1323 void *InsertPos = 0;
1324 if (MemberPointerType *PT =
1325 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1326 return QualType(PT, 0);
1327
1328 // If the pointee or class type isn't canonical, this won't be a canonical
1329 // type either, so fill in the canonical type field.
1330 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001331 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001332 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1333
1334 // Get the new insert position for the node we care about.
1335 MemberPointerType *NewIP =
1336 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1337 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1338 }
John McCall6b304a02009-09-24 23:30:46 +00001339 MemberPointerType *New
1340 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001341 Types.push_back(New);
1342 MemberPointerTypes.InsertNode(New, InsertPos);
1343 return QualType(New, 0);
1344}
1345
Mike Stump1eb44332009-09-09 15:08:12 +00001346/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001347/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001348QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001349 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001350 ArrayType::ArraySizeModifier ASM,
1351 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001352 assert((EltTy->isDependentType() ||
1353 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001354 "Constant array of VLAs is illegal!");
1355
Chris Lattner38aeec72009-05-13 04:12:56 +00001356 // Convert the array size into a canonical width matching the pointer size for
1357 // the target.
1358 llvm::APInt ArySize(ArySizeIn);
1359 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001362 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001363
Reid Spencer5f016e22007-07-11 17:01:13 +00001364 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001365 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001366 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001367 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001368
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 // If the element type isn't canonical, this won't be a canonical type either,
1370 // so fill in the canonical type field.
1371 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001372 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001373 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001374 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001375 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001376 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001377 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001378 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001379 }
Mike Stump1eb44332009-09-09 15:08:12 +00001380
John McCall6b304a02009-09-24 23:30:46 +00001381 ConstantArrayType *New = new(*this,TypeAlignment)
1382 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001383 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001384 Types.push_back(New);
1385 return QualType(New, 0);
1386}
1387
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001388/// getVariableArrayType - Returns a non-unique reference to the type for a
1389/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001390QualType ASTContext::getVariableArrayType(QualType EltTy,
1391 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001392 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001393 unsigned EltTypeQuals,
1394 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001395 // Since we don't unique expressions, it isn't possible to unique VLA's
1396 // that have an expression provided for their size.
1397
John McCall6b304a02009-09-24 23:30:46 +00001398 VariableArrayType *New = new(*this, TypeAlignment)
1399 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001400
1401 VariableArrayTypes.push_back(New);
1402 Types.push_back(New);
1403 return QualType(New, 0);
1404}
1405
Douglas Gregor898574e2008-12-05 23:32:09 +00001406/// getDependentSizedArrayType - Returns a non-unique reference to
1407/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001408/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001409QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1410 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001411 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001412 unsigned EltTypeQuals,
1413 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001414 assert((!NumElts || NumElts->isTypeDependent() ||
1415 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001416 "Size must be type- or value-dependent!");
1417
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001418 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001419 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001420 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001421
1422 if (NumElts) {
1423 // Dependently-sized array types that do not have a specified
1424 // number of elements will have their sizes deduced from an
1425 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001426 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1427 EltTypeQuals, NumElts);
1428
1429 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1430 }
1431
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001432 DependentSizedArrayType *New;
1433 if (Canon) {
1434 // We already have a canonical version of this array type; use it as
1435 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001436 New = new (*this, TypeAlignment)
1437 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1438 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001439 } else {
1440 QualType CanonEltTy = getCanonicalType(EltTy);
1441 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001442 New = new (*this, TypeAlignment)
1443 DependentSizedArrayType(*this, EltTy, QualType(),
1444 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001445
Douglas Gregor789b1f62010-02-04 18:10:26 +00001446 if (NumElts) {
1447 DependentSizedArrayType *CanonCheck
1448 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1449 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1450 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001451 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001452 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001453 } else {
1454 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1455 ASM, EltTypeQuals,
1456 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001457 New = new (*this, TypeAlignment)
1458 DependentSizedArrayType(*this, EltTy, Canon,
1459 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001460 }
1461 }
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Douglas Gregor898574e2008-12-05 23:32:09 +00001463 Types.push_back(New);
1464 return QualType(New, 0);
1465}
1466
Eli Friedmanc5773c42008-02-15 18:16:39 +00001467QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1468 ArrayType::ArraySizeModifier ASM,
1469 unsigned EltTypeQuals) {
1470 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001471 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001472
1473 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001474 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001475 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1476 return QualType(ATP, 0);
1477
1478 // If the element type isn't canonical, this won't be a canonical type
1479 // either, so fill in the canonical type field.
1480 QualType Canonical;
1481
John McCall467b27b2009-10-22 20:10:53 +00001482 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001483 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001484 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001485
1486 // Get the new insert position for the node we care about.
1487 IncompleteArrayType *NewIP =
1488 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001489 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001490 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001491
John McCall6b304a02009-09-24 23:30:46 +00001492 IncompleteArrayType *New = new (*this, TypeAlignment)
1493 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001494
1495 IncompleteArrayTypes.InsertNode(New, InsertPos);
1496 Types.push_back(New);
1497 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001498}
1499
Steve Naroff73322922007-07-18 18:00:27 +00001500/// getVectorType - Return the unique reference to a vector type of
1501/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001502QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1503 bool IsAltiVec, bool IsPixel) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001504 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Chris Lattnerf52ab252008-04-06 22:59:24 +00001506 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001507 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Reid Spencer5f016e22007-07-11 17:01:13 +00001509 // Check if we've already instantiated a vector of this type.
1510 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001511 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1512 IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001513 void *InsertPos = 0;
1514 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1515 return QualType(VTP, 0);
1516
1517 // If the element type isn't canonical, this won't be a canonical type either,
1518 // so fill in the canonical type field.
1519 QualType Canonical;
John Thompson82287d12010-02-05 00:12:22 +00001520 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1521 Canonical = getVectorType(getCanonicalType(vecType),
1522 NumElts, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001523
Reid Spencer5f016e22007-07-11 17:01:13 +00001524 // Get the new insert position for the node we care about.
1525 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001526 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001527 }
John McCall6b304a02009-09-24 23:30:46 +00001528 VectorType *New = new (*this, TypeAlignment)
John Thompson82287d12010-02-05 00:12:22 +00001529 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001530 VectorTypes.InsertNode(New, InsertPos);
1531 Types.push_back(New);
1532 return QualType(New, 0);
1533}
1534
Nate Begeman213541a2008-04-18 23:10:10 +00001535/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001536/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001537QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001538 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Chris Lattnerf52ab252008-04-06 22:59:24 +00001540 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001541 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Steve Naroff73322922007-07-18 18:00:27 +00001543 // Check if we've already instantiated a vector of this type.
1544 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001545 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff73322922007-07-18 18:00:27 +00001546 void *InsertPos = 0;
1547 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1548 return QualType(VTP, 0);
1549
1550 // If the element type isn't canonical, this won't be a canonical type either,
1551 // so fill in the canonical type field.
1552 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001553 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001554 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Steve Naroff73322922007-07-18 18:00:27 +00001556 // Get the new insert position for the node we care about.
1557 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001558 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001559 }
John McCall6b304a02009-09-24 23:30:46 +00001560 ExtVectorType *New = new (*this, TypeAlignment)
1561 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001562 VectorTypes.InsertNode(New, InsertPos);
1563 Types.push_back(New);
1564 return QualType(New, 0);
1565}
1566
Mike Stump1eb44332009-09-09 15:08:12 +00001567QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001568 Expr *SizeExpr,
1569 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001570 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001571 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001572 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001573
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001574 void *InsertPos = 0;
1575 DependentSizedExtVectorType *Canon
1576 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1577 DependentSizedExtVectorType *New;
1578 if (Canon) {
1579 // We already have a canonical version of this array type; use it as
1580 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001581 New = new (*this, TypeAlignment)
1582 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1583 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001584 } else {
1585 QualType CanonVecTy = getCanonicalType(vecType);
1586 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001587 New = new (*this, TypeAlignment)
1588 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1589 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001590
1591 DependentSizedExtVectorType *CanonCheck
1592 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1593 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1594 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001595 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1596 } else {
1597 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1598 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001599 New = new (*this, TypeAlignment)
1600 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001601 }
1602 }
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001604 Types.push_back(New);
1605 return QualType(New, 0);
1606}
1607
Douglas Gregor72564e72009-02-26 23:50:07 +00001608/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001609///
Rafael Espindola264ba482010-03-30 20:24:48 +00001610QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1611 const FunctionType::ExtInfo &Info) {
1612 const CallingConv CallConv = Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001613 // Unique functions, to guarantee there is only one function of a particular
1614 // structure.
1615 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001616 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Reid Spencer5f016e22007-07-11 17:01:13 +00001618 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001619 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001620 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001621 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Reid Spencer5f016e22007-07-11 17:01:13 +00001623 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001624 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001625 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001626 Canonical =
1627 getFunctionNoProtoType(getCanonicalType(ResultTy),
1628 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001631 FunctionNoProtoType *NewIP =
1632 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001633 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001634 }
Mike Stump1eb44332009-09-09 15:08:12 +00001635
John McCall6b304a02009-09-24 23:30:46 +00001636 FunctionNoProtoType *New = new (*this, TypeAlignment)
Rafael Espindola264ba482010-03-30 20:24:48 +00001637 FunctionNoProtoType(ResultTy, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001638 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001639 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001640 return QualType(New, 0);
1641}
1642
1643/// getFunctionType - Return a normal function type with a typed argument
1644/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001645QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001646 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001647 unsigned TypeQuals, bool hasExceptionSpec,
1648 bool hasAnyExceptionSpec, unsigned NumExs,
Rafael Espindola264ba482010-03-30 20:24:48 +00001649 const QualType *ExArray,
1650 const FunctionType::ExtInfo &Info) {
1651 const CallingConv CallConv= Info.getCC();
Reid Spencer5f016e22007-07-11 17:01:13 +00001652 // Unique functions, to guarantee there is only one function of a particular
1653 // structure.
1654 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001655 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001656 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001657 NumExs, ExArray, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001658
1659 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001660 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001661 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001662 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001663
1664 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001665 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001667 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001668 isCanonical = false;
1669
1670 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001671 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001672 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001673 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001674 llvm::SmallVector<QualType, 16> CanonicalArgs;
1675 CanonicalArgs.reserve(NumArgs);
1676 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001677 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001678
Chris Lattnerf52ab252008-04-06 22:59:24 +00001679 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001680 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001681 isVariadic, TypeQuals, false,
Rafael Espindola264ba482010-03-30 20:24:48 +00001682 false, 0, 0,
1683 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Sebastian Redl465226e2009-05-27 22:11:52 +00001684
Reid Spencer5f016e22007-07-11 17:01:13 +00001685 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001686 FunctionProtoType *NewIP =
1687 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001688 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001690
Douglas Gregor72564e72009-02-26 23:50:07 +00001691 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001692 // for two variable size arrays (for parameter and exception types) at the
1693 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001694 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001695 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1696 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001697 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001698 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001699 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Rafael Espindola264ba482010-03-30 20:24:48 +00001700 ExArray, NumExs, Canonical, Info);
Reid Spencer5f016e22007-07-11 17:01:13 +00001701 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001702 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001703 return QualType(FTP, 0);
1704}
1705
John McCall3cb0ebd2010-03-10 03:28:59 +00001706#ifndef NDEBUG
1707static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1708 if (!isa<CXXRecordDecl>(D)) return false;
1709 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1710 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1711 return true;
1712 if (RD->getDescribedClassTemplate() &&
1713 !isa<ClassTemplateSpecializationDecl>(RD))
1714 return true;
1715 return false;
1716}
1717#endif
1718
1719/// getInjectedClassNameType - Return the unique reference to the
1720/// injected class name type for the specified templated declaration.
1721QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1722 QualType TST) {
1723 assert(NeedsInjectedClassNameType(Decl));
1724 if (Decl->TypeForDecl) {
1725 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1726 } else if (CXXRecordDecl *PrevDecl
1727 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1728 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1729 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1730 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1731 } else {
1732 Decl->TypeForDecl = new (*this, TypeAlignment)
1733 InjectedClassNameType(Decl, TST, TST->getCanonicalTypeInternal());
1734 Types.push_back(Decl->TypeForDecl);
1735 }
1736 return QualType(Decl->TypeForDecl, 0);
1737}
1738
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001739/// getTypeDeclType - Return the unique reference to the type for the
1740/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001741QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001742 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001743 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001744
John McCall19c85762010-02-16 03:57:14 +00001745 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001746 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001747
1748 if (const ObjCInterfaceDecl *ObjCInterface
Mike Stump9fdbab32009-07-31 02:02:20 +00001749 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001750 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001751
John McCallbecb8d52010-03-10 06:48:02 +00001752 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1753 "Template type parameter types are always available.");
1754
John McCall19c85762010-02-16 03:57:14 +00001755 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001756 assert(!Record->getPreviousDeclaration() &&
1757 "struct/union has previous declaration");
1758 assert(!NeedsInjectedClassNameType(Record));
1759 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001760 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001761 assert(!Enum->getPreviousDeclaration() &&
1762 "enum has previous declaration");
1763 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001764 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001765 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1766 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001767 } else
John McCallbecb8d52010-03-10 06:48:02 +00001768 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001769
John McCallbecb8d52010-03-10 06:48:02 +00001770 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001771 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001772}
1773
Reid Spencer5f016e22007-07-11 17:01:13 +00001774/// getTypedefType - Return the unique reference to the type for the
1775/// specified typename decl.
John McCall19c85762010-02-16 03:57:14 +00001776QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001777 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Chris Lattnerf52ab252008-04-06 22:59:24 +00001779 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001780 Decl->TypeForDecl = new(*this, TypeAlignment)
1781 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 Types.push_back(Decl->TypeForDecl);
1783 return QualType(Decl->TypeForDecl, 0);
1784}
1785
John McCall49a832b2009-10-18 09:09:24 +00001786/// \brief Retrieve a substitution-result type.
1787QualType
1788ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1789 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00001790 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00001791 && "replacement types must always be canonical");
1792
1793 llvm::FoldingSetNodeID ID;
1794 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1795 void *InsertPos = 0;
1796 SubstTemplateTypeParmType *SubstParm
1797 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1798
1799 if (!SubstParm) {
1800 SubstParm = new (*this, TypeAlignment)
1801 SubstTemplateTypeParmType(Parm, Replacement);
1802 Types.push_back(SubstParm);
1803 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1804 }
1805
1806 return QualType(SubstParm, 0);
1807}
1808
Douglas Gregorfab9d672009-02-05 23:33:38 +00001809/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00001810/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001811/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00001812QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001813 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00001814 IdentifierInfo *Name) {
1815 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001816 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001817 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001818 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00001819 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1820
1821 if (TypeParm)
1822 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001824 if (Name) {
1825 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00001826 TypeParm = new (*this, TypeAlignment)
1827 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001828
1829 TemplateTypeParmType *TypeCheck
1830 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1831 assert(!TypeCheck && "Template type parameter canonical type broken");
1832 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00001833 } else
John McCall6b304a02009-09-24 23:30:46 +00001834 TypeParm = new (*this, TypeAlignment)
1835 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00001836
1837 Types.push_back(TypeParm);
1838 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1839
1840 return QualType(TypeParm, 0);
1841}
1842
John McCall3cb0ebd2010-03-10 03:28:59 +00001843TypeSourceInfo *
1844ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1845 SourceLocation NameLoc,
1846 const TemplateArgumentListInfo &Args,
1847 QualType CanonType) {
1848 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1849
1850 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1851 TemplateSpecializationTypeLoc TL
1852 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1853 TL.setTemplateNameLoc(NameLoc);
1854 TL.setLAngleLoc(Args.getLAngleLoc());
1855 TL.setRAngleLoc(Args.getRAngleLoc());
1856 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1857 TL.setArgLocInfo(i, Args[i].getLocInfo());
1858 return DI;
1859}
1860
Mike Stump1eb44332009-09-09 15:08:12 +00001861QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00001862ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00001863 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00001864 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00001865 unsigned NumArgs = Args.size();
1866
John McCall833ca992009-10-29 08:12:44 +00001867 llvm::SmallVector<TemplateArgument, 4> ArgVec;
1868 ArgVec.reserve(NumArgs);
1869 for (unsigned i = 0; i != NumArgs; ++i)
1870 ArgVec.push_back(Args[i].getArgument());
1871
1872 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
1873}
1874
1875QualType
1876ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001877 const TemplateArgument *Args,
1878 unsigned NumArgs,
1879 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001880 if (!Canon.isNull())
1881 Canon = getCanonicalType(Canon);
1882 else {
1883 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001884 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1885 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1886 CanonArgs.reserve(NumArgs);
1887 for (unsigned I = 0; I != NumArgs; ++I)
1888 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1889
1890 // Determine whether this canonical template specialization type already
1891 // exists.
1892 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001893 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00001894 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001895
1896 void *InsertPos = 0;
1897 TemplateSpecializationType *Spec
1898 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Douglas Gregor1275ae02009-07-28 23:00:59 +00001900 if (!Spec) {
1901 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00001902 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00001903 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001904 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001905 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00001906 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00001907 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001908 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001909 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00001910 }
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Douglas Gregorb88e8882009-07-30 17:40:51 +00001912 if (Canon.isNull())
1913 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001914 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00001915 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00001916 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00001917
Douglas Gregor1275ae02009-07-28 23:00:59 +00001918 // Allocate the (non-canonical) template specialization type, but don't
1919 // try to unique it: these types typically have location information that
1920 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00001921 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00001922 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00001923 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00001924 TemplateSpecializationType *Spec
1925 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00001926 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Douglas Gregor55f6b142009-02-09 18:46:07 +00001928 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00001929 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001930}
1931
Mike Stump1eb44332009-09-09 15:08:12 +00001932QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00001933ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00001934 QualType NamedType) {
1935 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001936 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001937
1938 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001939 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00001940 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1941 if (T)
1942 return QualType(T, 0);
1943
Douglas Gregor789b1f62010-02-04 18:10:26 +00001944 QualType Canon = NamedType;
1945 if (!Canon.isCanonical()) {
1946 Canon = getCanonicalType(NamedType);
1947 QualifiedNameType *CheckT
1948 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1949 assert(!CheckT && "Qualified name canonical type broken");
1950 (void)CheckT;
1951 }
1952
1953 T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001954 Types.push_back(T);
1955 QualifiedNameTypes.InsertNode(T, InsertPos);
1956 return QualType(T, 0);
1957}
1958
Mike Stump1eb44332009-09-09 15:08:12 +00001959QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00001960 const IdentifierInfo *Name,
1961 QualType Canon) {
1962 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1963
1964 if (Canon.isNull()) {
1965 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1966 if (CanonNNS != NNS)
1967 Canon = getTypenameType(CanonNNS, Name);
1968 }
1969
1970 llvm::FoldingSetNodeID ID;
1971 TypenameType::Profile(ID, NNS, Name);
1972
1973 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001974 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00001975 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1976 if (T)
1977 return QualType(T, 0);
1978
1979 T = new (*this) TypenameType(NNS, Name, Canon);
1980 Types.push_back(T);
1981 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001982 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00001983}
1984
Mike Stump1eb44332009-09-09 15:08:12 +00001985QualType
1986ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00001987 const TemplateSpecializationType *TemplateId,
1988 QualType Canon) {
1989 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1990
Douglas Gregor789b1f62010-02-04 18:10:26 +00001991 llvm::FoldingSetNodeID ID;
1992 TypenameType::Profile(ID, NNS, TemplateId);
1993
1994 void *InsertPos = 0;
1995 TypenameType *T
1996 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1997 if (T)
1998 return QualType(T, 0);
1999
Douglas Gregor17343172009-04-01 00:28:59 +00002000 if (Canon.isNull()) {
2001 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2002 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2003 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2004 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00002005 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00002006 assert(CanonTemplateId &&
2007 "Canonical type must also be a template specialization type");
2008 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2009 }
Douglas Gregor789b1f62010-02-04 18:10:26 +00002010
2011 TypenameType *CheckT
2012 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2013 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregor17343172009-04-01 00:28:59 +00002014 }
2015
Douglas Gregor17343172009-04-01 00:28:59 +00002016 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2017 Types.push_back(T);
2018 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002019 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002020}
2021
John McCall7da24312009-09-05 00:15:47 +00002022QualType
2023ASTContext::getElaboratedType(QualType UnderlyingType,
2024 ElaboratedType::TagKind Tag) {
2025 llvm::FoldingSetNodeID ID;
2026 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00002027
John McCall7da24312009-09-05 00:15:47 +00002028 void *InsertPos = 0;
2029 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2030 if (T)
2031 return QualType(T, 0);
2032
Douglas Gregor789b1f62010-02-04 18:10:26 +00002033 QualType Canon = UnderlyingType;
2034 if (!Canon.isCanonical()) {
2035 Canon = getCanonicalType(Canon);
2036 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2037 assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2038 }
John McCall7da24312009-09-05 00:15:47 +00002039
2040 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2041 Types.push_back(T);
2042 ElaboratedTypes.InsertNode(T, InsertPos);
2043 return QualType(T, 0);
2044}
2045
Chris Lattner88cb27a2008-04-07 04:56:42 +00002046/// CmpProtocolNames - Comparison predicate for sorting protocols
2047/// alphabetically.
2048static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2049 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002050 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002051}
2052
John McCall54e14c42009-10-22 22:37:11 +00002053static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2054 unsigned NumProtocols) {
2055 if (NumProtocols == 0) return true;
2056
2057 for (unsigned i = 1; i != NumProtocols; ++i)
2058 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2059 return false;
2060 return true;
2061}
2062
2063static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002064 unsigned &NumProtocols) {
2065 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Chris Lattner88cb27a2008-04-07 04:56:42 +00002067 // Sort protocols, keyed by name.
2068 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2069
2070 // Remove duplicates.
2071 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2072 NumProtocols = ProtocolsEnd-Protocols;
2073}
2074
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002075/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2076/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002077QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002078 ObjCProtocolDecl **Protocols,
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002079 unsigned NumProtocols,
2080 unsigned Quals) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002081 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002082 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002083 Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002084
2085 void *InsertPos = 0;
2086 if (ObjCObjectPointerType *QT =
2087 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002088 return getQualifiedType(QualType(QT, 0), Qs);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002089
John McCall54e14c42009-10-22 22:37:11 +00002090 // Sort the protocol list alphabetically to canonicalize it.
2091 QualType Canonical;
2092 if (!InterfaceT.isCanonical() ||
2093 !areSortedAndUniqued(Protocols, NumProtocols)) {
2094 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2095 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2096 unsigned UniqueCount = NumProtocols;
2097
2098 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2099 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2100
2101 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2102 &Sorted[0], UniqueCount);
2103 } else {
2104 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2105 Protocols, NumProtocols);
2106 }
2107
2108 // Regenerate InsertPos.
2109 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2110 }
2111
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002112 // No match.
2113 unsigned Size = sizeof(ObjCObjectPointerType)
2114 + NumProtocols * sizeof(ObjCProtocolDecl *);
2115 void *Mem = Allocate(Size, TypeAlignment);
2116 ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2117 InterfaceT,
2118 Protocols,
2119 NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002121 Types.push_back(QType);
2122 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002123 return getQualifiedType(QualType(QType, 0), Qs);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002124}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002125
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002126/// getObjCInterfaceType - Return the unique reference to the type for the
2127/// specified ObjC interface decl. The list of protocols is optional.
2128QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002129 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002130 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002131 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002133 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002134 if (ObjCInterfaceType *QT =
2135 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002136 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002137
John McCall54e14c42009-10-22 22:37:11 +00002138 // Sort the protocol list alphabetically to canonicalize it.
2139 QualType Canonical;
2140 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2141 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2142 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2143
2144 unsigned UniqueCount = NumProtocols;
2145 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2146
2147 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2148
2149 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2150 }
2151
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002152 unsigned Size = sizeof(ObjCInterfaceType)
2153 + NumProtocols * sizeof(ObjCProtocolDecl *);
2154 void *Mem = Allocate(Size, TypeAlignment);
2155 ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2156 const_cast<ObjCInterfaceDecl*>(Decl),
2157 Protocols,
2158 NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002159
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002160 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002161 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002162 return QualType(QType, 0);
2163}
2164
Douglas Gregor72564e72009-02-26 23:50:07 +00002165/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2166/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002167/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002168/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002169/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002170QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002171 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002172 if (tofExpr->isTypeDependent()) {
2173 llvm::FoldingSetNodeID ID;
2174 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002175
Douglas Gregorb1975722009-07-30 23:18:24 +00002176 void *InsertPos = 0;
2177 DependentTypeOfExprType *Canon
2178 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2179 if (Canon) {
2180 // We already have a "canonical" version of an identical, dependent
2181 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002182 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002183 QualType((TypeOfExprType*)Canon, 0));
2184 }
2185 else {
2186 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002187 Canon
2188 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002189 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2190 toe = Canon;
2191 }
2192 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002193 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002194 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002195 }
Steve Naroff9752f252007-08-01 18:02:17 +00002196 Types.push_back(toe);
2197 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002198}
2199
Steve Naroff9752f252007-08-01 18:02:17 +00002200/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2201/// TypeOfType AST's. The only motivation to unique these nodes would be
2202/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002203/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002204/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002205QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002206 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002207 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002208 Types.push_back(tot);
2209 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002210}
2211
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002212/// getDecltypeForExpr - Given an expr, will return the decltype for that
2213/// expression, according to the rules in C++0x [dcl.type.simple]p4
2214static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002215 if (e->isTypeDependent())
2216 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002218 // If e is an id expression or a class member access, decltype(e) is defined
2219 // as the type of the entity named by e.
2220 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2221 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2222 return VD->getType();
2223 }
2224 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2225 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2226 return FD->getType();
2227 }
2228 // If e is a function call or an invocation of an overloaded operator,
2229 // (parentheses around e are ignored), decltype(e) is defined as the
2230 // return type of that function.
2231 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2232 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002233
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002234 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002235
2236 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002237 // defined as T&, otherwise decltype(e) is defined as T.
2238 if (e->isLvalue(Context) == Expr::LV_Valid)
2239 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002241 return T;
2242}
2243
Anders Carlsson395b4752009-06-24 19:06:50 +00002244/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2245/// DecltypeType AST's. The only motivation to unique these nodes would be
2246/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002247/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002248/// on canonical type's (which are always unique).
2249QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002250 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002251 if (e->isTypeDependent()) {
2252 llvm::FoldingSetNodeID ID;
2253 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002254
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002255 void *InsertPos = 0;
2256 DependentDecltypeType *Canon
2257 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2258 if (Canon) {
2259 // We already have a "canonical" version of an equivalent, dependent
2260 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002261 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002262 QualType((DecltypeType*)Canon, 0));
2263 }
2264 else {
2265 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002266 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002267 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2268 dt = Canon;
2269 }
2270 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002271 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002272 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002273 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002274 Types.push_back(dt);
2275 return QualType(dt, 0);
2276}
2277
Reid Spencer5f016e22007-07-11 17:01:13 +00002278/// getTagDeclType - Return the unique reference to the type for the
2279/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002280QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002281 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002282 // FIXME: What is the design on getTagDeclType when it requires casting
2283 // away const? mutable?
2284 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002285}
2286
Mike Stump1eb44332009-09-09 15:08:12 +00002287/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2288/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2289/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002290CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002291 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002292}
2293
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002294/// getSignedWCharType - Return the type of "signed wchar_t".
2295/// Used when in C++, as a GCC extension.
2296QualType ASTContext::getSignedWCharType() const {
2297 // FIXME: derive from "Target" ?
2298 return WCharTy;
2299}
2300
2301/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2302/// Used when in C++, as a GCC extension.
2303QualType ASTContext::getUnsignedWCharType() const {
2304 // FIXME: derive from "Target" ?
2305 return UnsignedIntTy;
2306}
2307
Chris Lattner8b9023b2007-07-13 03:05:23 +00002308/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2309/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2310QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002311 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002312}
2313
Chris Lattnere6327742008-04-02 05:18:44 +00002314//===----------------------------------------------------------------------===//
2315// Type Operators
2316//===----------------------------------------------------------------------===//
2317
John McCall54e14c42009-10-22 22:37:11 +00002318CanQualType ASTContext::getCanonicalParamType(QualType T) {
2319 // Push qualifiers into arrays, and then discard any remaining
2320 // qualifiers.
2321 T = getCanonicalType(T);
2322 const Type *Ty = T.getTypePtr();
2323
2324 QualType Result;
2325 if (isa<ArrayType>(Ty)) {
2326 Result = getArrayDecayedType(QualType(Ty,0));
2327 } else if (isa<FunctionType>(Ty)) {
2328 Result = getPointerType(QualType(Ty, 0));
2329 } else {
2330 Result = QualType(Ty, 0);
2331 }
2332
2333 return CanQualType::CreateUnsafe(Result);
2334}
2335
Chris Lattner77c96472008-04-06 22:41:35 +00002336/// getCanonicalType - Return the canonical (structural) type corresponding to
2337/// the specified potentially non-canonical type. The non-canonical version
2338/// of a type may have many "decorated" versions of types. Decorators can
2339/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2340/// to be free of any of these, allowing two canonical types to be compared
2341/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002342CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002343 QualifierCollector Quals;
2344 const Type *Ptr = Quals.strip(T);
2345 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002346
John McCall0953e762009-09-24 19:53:00 +00002347 // The canonical internal type will be the canonical type *except*
2348 // that we push type qualifiers down through array types.
2349
2350 // If there are no new qualifiers to push down, stop here.
2351 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002352 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002353
John McCall0953e762009-09-24 19:53:00 +00002354 // If the type qualifiers are on an array type, get the canonical
2355 // type of the array with the qualifiers applied to the element
2356 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002357 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2358 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002359 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002360
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002361 // Get the canonical version of the element with the extra qualifiers on it.
2362 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002363 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002364 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002366 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002367 return CanQualType::CreateUnsafe(
2368 getConstantArrayType(NewEltTy, CAT->getSize(),
2369 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002370 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002371 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002372 return CanQualType::CreateUnsafe(
2373 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002374 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002375
Douglas Gregor898574e2008-12-05 23:32:09 +00002376 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002377 return CanQualType::CreateUnsafe(
2378 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002379 DSAT->getSizeExpr() ?
2380 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002381 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002382 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002383 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002384
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002385 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002386 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002387 VAT->getSizeExpr() ?
2388 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002389 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002390 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002391 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002392}
2393
Chandler Carruth28e318c2009-12-29 07:16:59 +00002394QualType ASTContext::getUnqualifiedArrayType(QualType T,
2395 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002396 Quals = T.getQualifiers();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002397 if (!isa<ArrayType>(T)) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002398 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002399 }
2400
Chandler Carruth28e318c2009-12-29 07:16:59 +00002401 const ArrayType *AT = cast<ArrayType>(T);
2402 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002403 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002404 if (Elt == UnqualElt)
2405 return T;
2406
2407 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2408 return getConstantArrayType(UnqualElt, CAT->getSize(),
2409 CAT->getSizeModifier(), 0);
2410 }
2411
2412 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2413 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2414 }
2415
2416 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2417 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2418 DSAT->getSizeModifier(), 0,
2419 SourceRange());
2420}
2421
John McCall80ad16f2009-11-24 18:42:40 +00002422DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2423 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2424 return TD->getDeclName();
2425
2426 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2427 if (DTN->isIdentifier()) {
2428 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2429 } else {
2430 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2431 }
2432 }
2433
John McCall0bd6feb2009-12-02 08:04:21 +00002434 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2435 assert(Storage);
2436 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002437}
2438
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002439TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2440 // If this template name refers to a template, the canonical
2441 // template name merely stores the template itself.
2442 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002443 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002444
John McCall0bd6feb2009-12-02 08:04:21 +00002445 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002446
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002447 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2448 assert(DTN && "Non-dependent template names must refer to template decls.");
2449 return DTN->CanonicalTemplateName;
2450}
2451
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002452bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2453 X = getCanonicalTemplateName(X);
2454 Y = getCanonicalTemplateName(Y);
2455 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2456}
2457
Mike Stump1eb44332009-09-09 15:08:12 +00002458TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002459ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2460 switch (Arg.getKind()) {
2461 case TemplateArgument::Null:
2462 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002463
Douglas Gregor1275ae02009-07-28 23:00:59 +00002464 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002465 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002466
Douglas Gregor1275ae02009-07-28 23:00:59 +00002467 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002468 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002469
Douglas Gregor788cd062009-11-11 01:00:40 +00002470 case TemplateArgument::Template:
2471 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2472
Douglas Gregor1275ae02009-07-28 23:00:59 +00002473 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002474 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002475 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002476
Douglas Gregor1275ae02009-07-28 23:00:59 +00002477 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002478 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002479
Douglas Gregor1275ae02009-07-28 23:00:59 +00002480 case TemplateArgument::Pack: {
2481 // FIXME: Allocate in ASTContext
2482 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2483 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002484 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002485 AEnd = Arg.pack_end();
2486 A != AEnd; (void)++A, ++Idx)
2487 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002488
Douglas Gregor1275ae02009-07-28 23:00:59 +00002489 TemplateArgument Result;
2490 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2491 return Result;
2492 }
2493 }
2494
2495 // Silence GCC warning
2496 assert(false && "Unhandled template argument kind");
2497 return TemplateArgument();
2498}
2499
Douglas Gregord57959a2009-03-27 23:10:48 +00002500NestedNameSpecifier *
2501ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002502 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002503 return 0;
2504
2505 switch (NNS->getKind()) {
2506 case NestedNameSpecifier::Identifier:
2507 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002508 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002509 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2510 NNS->getAsIdentifier());
2511
2512 case NestedNameSpecifier::Namespace:
2513 // A namespace is canonical; build a nested-name-specifier with
2514 // this namespace and no prefix.
2515 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2516
2517 case NestedNameSpecifier::TypeSpec:
2518 case NestedNameSpecifier::TypeSpecWithTemplate: {
2519 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002520 return NestedNameSpecifier::Create(*this, 0,
2521 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002522 T.getTypePtr());
2523 }
2524
2525 case NestedNameSpecifier::Global:
2526 // The global specifier is canonical and unique.
2527 return NNS;
2528 }
2529
2530 // Required to silence a GCC warning
2531 return 0;
2532}
2533
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002534
2535const ArrayType *ASTContext::getAsArrayType(QualType T) {
2536 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002537 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002538 // Handle the common positive case fast.
2539 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2540 return AT;
2541 }
Mike Stump1eb44332009-09-09 15:08:12 +00002542
John McCall0953e762009-09-24 19:53:00 +00002543 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002544 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002545 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002546 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002547
John McCall0953e762009-09-24 19:53:00 +00002548 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002549 // implements C99 6.7.3p8: "If the specification of an array type includes
2550 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002551
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002552 // If we get here, we either have type qualifiers on the type, or we have
2553 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002554 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002555
John McCall0953e762009-09-24 19:53:00 +00002556 QualifierCollector Qs;
2557 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002558
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002559 // If we have a simple case, just return now.
2560 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002561 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002562 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002563
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002564 // Otherwise, we have an array and we have qualifiers on it. Push the
2565 // qualifiers into the array element type and return a new array type.
2566 // Get the canonical version of the element with the extra qualifiers on it.
2567 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002568 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002569
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002570 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2571 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2572 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002573 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002574 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2575 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2576 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002577 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002578
Mike Stump1eb44332009-09-09 15:08:12 +00002579 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002580 = dyn_cast<DependentSizedArrayType>(ATy))
2581 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002582 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002583 DSAT->getSizeExpr() ?
2584 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002585 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002586 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002587 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002588
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002589 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002590 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002591 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002592 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002593 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002594 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002595 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002596}
2597
2598
Chris Lattnere6327742008-04-02 05:18:44 +00002599/// getArrayDecayedType - Return the properly qualified result of decaying the
2600/// specified array type to a pointer. This operation is non-trivial when
2601/// handling typedefs etc. The canonical type of "T" must be an array type,
2602/// this returns a pointer to a properly qualified element of the array.
2603///
2604/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2605QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002606 // Get the element type with 'getAsArrayType' so that we don't lose any
2607 // typedefs in the element type of the array. This also handles propagation
2608 // of type qualifiers from the array type into the element type if present
2609 // (C99 6.7.3p8).
2610 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2611 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002612
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002613 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002614
2615 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002616 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002617}
2618
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002619QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002620 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002621 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002622 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002623 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2624 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002625 } else {
John McCall0953e762009-09-24 19:53:00 +00002626 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002627 }
2628 }
2629}
2630
Anders Carlssonfbbce492009-09-25 01:23:32 +00002631QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2632 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002633
Anders Carlssonfbbce492009-09-25 01:23:32 +00002634 if (const ArrayType *AT = getAsArrayType(ElemTy))
2635 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002636
Anders Carlsson6183a992008-12-21 03:44:36 +00002637 return ElemTy;
2638}
2639
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002640/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002641uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002642ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2643 uint64_t ElementCount = 1;
2644 do {
2645 ElementCount *= CA->getSize().getZExtValue();
2646 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2647 } while (CA);
2648 return ElementCount;
2649}
2650
Reid Spencer5f016e22007-07-11 17:01:13 +00002651/// getFloatingRank - Return a relative rank for floating point types.
2652/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002653static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002654 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002655 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002656
John McCall183700f2009-09-21 23:43:11 +00002657 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2658 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002659 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002660 case BuiltinType::Float: return FloatRank;
2661 case BuiltinType::Double: return DoubleRank;
2662 case BuiltinType::LongDouble: return LongDoubleRank;
2663 }
2664}
2665
Mike Stump1eb44332009-09-09 15:08:12 +00002666/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2667/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002668/// 'typeDomain' is a real floating point or complex type.
2669/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002670QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2671 QualType Domain) const {
2672 FloatingRank EltRank = getFloatingRank(Size);
2673 if (Domain->isComplexType()) {
2674 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002675 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002676 case FloatRank: return FloatComplexTy;
2677 case DoubleRank: return DoubleComplexTy;
2678 case LongDoubleRank: return LongDoubleComplexTy;
2679 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002680 }
Chris Lattner1361b112008-04-06 23:58:54 +00002681
2682 assert(Domain->isRealFloatingType() && "Unknown domain!");
2683 switch (EltRank) {
2684 default: assert(0 && "getFloatingRank(): illegal value for rank");
2685 case FloatRank: return FloatTy;
2686 case DoubleRank: return DoubleTy;
2687 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002688 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002689}
2690
Chris Lattner7cfeb082008-04-06 23:55:33 +00002691/// getFloatingTypeOrder - Compare the rank of the two specified floating
2692/// point types, ignoring the domain of the type (i.e. 'double' ==
2693/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002694/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002695int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2696 FloatingRank LHSR = getFloatingRank(LHS);
2697 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002698
Chris Lattnera75cea32008-04-06 23:38:49 +00002699 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002700 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002701 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002702 return 1;
2703 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002704}
2705
Chris Lattnerf52ab252008-04-06 22:59:24 +00002706/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2707/// routine will assert if passed a built-in type that isn't an integer or enum,
2708/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002709unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002710 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002711 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002712 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002713
Eli Friedmana3426752009-07-05 23:44:27 +00002714 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2715 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2716
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002717 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2718 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2719
2720 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2721 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2722
Chris Lattnerf52ab252008-04-06 22:59:24 +00002723 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002724 default: assert(0 && "getIntegerRank(): not a built-in integer");
2725 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002726 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002727 case BuiltinType::Char_S:
2728 case BuiltinType::Char_U:
2729 case BuiltinType::SChar:
2730 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002731 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002732 case BuiltinType::Short:
2733 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002734 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002735 case BuiltinType::Int:
2736 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002737 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002738 case BuiltinType::Long:
2739 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002740 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002741 case BuiltinType::LongLong:
2742 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002743 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002744 case BuiltinType::Int128:
2745 case BuiltinType::UInt128:
2746 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002747 }
2748}
2749
Eli Friedman04e83572009-08-20 04:21:42 +00002750/// \brief Whether this is a promotable bitfield reference according
2751/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2752///
2753/// \returns the type this bit-field will promote to, or NULL if no
2754/// promotion occurs.
2755QualType ASTContext::isPromotableBitField(Expr *E) {
2756 FieldDecl *Field = E->getBitField();
2757 if (!Field)
2758 return QualType();
2759
2760 QualType FT = Field->getType();
2761
2762 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2763 uint64_t BitWidth = BitWidthAP.getZExtValue();
2764 uint64_t IntSize = getTypeSize(IntTy);
2765 // GCC extension compatibility: if the bit-field size is less than or equal
2766 // to the size of int, it gets promoted no matter what its type is.
2767 // For instance, unsigned long bf : 4 gets promoted to signed int.
2768 if (BitWidth < IntSize)
2769 return IntTy;
2770
2771 if (BitWidth == IntSize)
2772 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2773
2774 // Types bigger than int are not subject to promotions, and therefore act
2775 // like the base type.
2776 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2777 // is ridiculous.
2778 return QualType();
2779}
2780
Eli Friedmana95d7572009-08-19 07:44:53 +00002781/// getPromotedIntegerType - Returns the type that Promotable will
2782/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2783/// integer type.
2784QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2785 assert(!Promotable.isNull());
2786 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00002787 if (const EnumType *ET = Promotable->getAs<EnumType>())
2788 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00002789 if (Promotable->isSignedIntegerType())
2790 return IntTy;
2791 uint64_t PromotableSize = getTypeSize(Promotable);
2792 uint64_t IntSize = getTypeSize(IntTy);
2793 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2794 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2795}
2796
Mike Stump1eb44332009-09-09 15:08:12 +00002797/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00002798/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002799/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002800int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002801 Type *LHSC = getCanonicalType(LHS).getTypePtr();
2802 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00002803 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002804
Chris Lattnerf52ab252008-04-06 22:59:24 +00002805 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2806 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002807
Chris Lattner7cfeb082008-04-06 23:55:33 +00002808 unsigned LHSRank = getIntegerRank(LHSC);
2809 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00002810
Chris Lattner7cfeb082008-04-06 23:55:33 +00002811 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
2812 if (LHSRank == RHSRank) return 0;
2813 return LHSRank > RHSRank ? 1 : -1;
2814 }
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Chris Lattner7cfeb082008-04-06 23:55:33 +00002816 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2817 if (LHSUnsigned) {
2818 // If the unsigned [LHS] type is larger, return it.
2819 if (LHSRank >= RHSRank)
2820 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00002821
Chris Lattner7cfeb082008-04-06 23:55:33 +00002822 // If the signed type can represent all values of the unsigned type, it
2823 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002824 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002825 return -1;
2826 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00002827
Chris Lattner7cfeb082008-04-06 23:55:33 +00002828 // If the unsigned [RHS] type is larger, return it.
2829 if (RHSRank >= LHSRank)
2830 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00002831
Chris Lattner7cfeb082008-04-06 23:55:33 +00002832 // If the signed type can represent all values of the unsigned type, it
2833 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00002834 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00002835 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002836}
Anders Carlsson71993dd2007-08-17 05:31:46 +00002837
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002838static RecordDecl *
2839CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2840 SourceLocation L, IdentifierInfo *Id) {
2841 if (Ctx.getLangOptions().CPlusPlus)
2842 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2843 else
2844 return RecordDecl::Create(Ctx, TK, DC, L, Id);
2845}
2846
Mike Stump1eb44332009-09-09 15:08:12 +00002847// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00002848QualType ASTContext::getCFConstantStringType() {
2849 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00002850 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002851 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2852 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00002853 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002854
Anders Carlssonf06273f2007-11-19 00:25:30 +00002855 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002856
Anders Carlsson71993dd2007-08-17 05:31:46 +00002857 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00002858 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00002859 // int flags;
2860 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00002861 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00002862 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00002863 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002864 FieldTypes[3] = LongTy;
2865
Anders Carlsson71993dd2007-08-17 05:31:46 +00002866 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002867 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002868 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002869 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002870 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002871 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002872 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002873 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002874 }
2875
Douglas Gregor838db382010-02-11 01:19:42 +00002876 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00002877 }
Mike Stump1eb44332009-09-09 15:08:12 +00002878
Anders Carlsson71993dd2007-08-17 05:31:46 +00002879 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00002880}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00002881
Douglas Gregor319ac892009-04-23 22:29:11 +00002882void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002883 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00002884 assert(Rec && "Invalid CFConstantStringType");
2885 CFConstantStringTypeDecl = Rec->getDecl();
2886}
2887
Mike Stump1eb44332009-09-09 15:08:12 +00002888QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002889 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00002890 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002891 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2892 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00002893 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002894
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002895 QualType FieldTypes[] = {
2896 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00002897 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002898 getPointerType(UnsignedLongTy),
2899 getConstantArrayType(UnsignedLongTy,
2900 llvm::APInt(32, 5), ArrayType::Normal, 0)
2901 };
Mike Stump1eb44332009-09-09 15:08:12 +00002902
Douglas Gregor44b43212008-12-11 16:49:14 +00002903 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002904 FieldDecl *Field = FieldDecl::Create(*this,
2905 ObjCFastEnumerationStateTypeDecl,
2906 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00002907 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00002908 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002909 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002910 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00002911 }
Mike Stump1eb44332009-09-09 15:08:12 +00002912
Douglas Gregor838db382010-02-11 01:19:42 +00002913 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002914 }
Mike Stump1eb44332009-09-09 15:08:12 +00002915
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00002916 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2917}
2918
Mike Stumpadaaad32009-10-20 02:12:22 +00002919QualType ASTContext::getBlockDescriptorType() {
2920 if (BlockDescriptorType)
2921 return getTagDeclType(BlockDescriptorType);
2922
2923 RecordDecl *T;
2924 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002925 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2926 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00002927 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00002928
2929 QualType FieldTypes[] = {
2930 UnsignedLongTy,
2931 UnsignedLongTy,
2932 };
2933
2934 const char *FieldNames[] = {
2935 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00002936 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00002937 };
2938
2939 for (size_t i = 0; i < 2; ++i) {
2940 FieldDecl *Field = FieldDecl::Create(*this,
2941 T,
2942 SourceLocation(),
2943 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00002944 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00002945 /*BitWidth=*/0,
2946 /*Mutable=*/false);
2947 T->addDecl(Field);
2948 }
2949
Douglas Gregor838db382010-02-11 01:19:42 +00002950 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00002951
2952 BlockDescriptorType = T;
2953
2954 return getTagDeclType(BlockDescriptorType);
2955}
2956
2957void ASTContext::setBlockDescriptorType(QualType T) {
2958 const RecordType *Rec = T->getAs<RecordType>();
2959 assert(Rec && "Invalid BlockDescriptorType");
2960 BlockDescriptorType = Rec->getDecl();
2961}
2962
Mike Stump083c25e2009-10-22 00:49:09 +00002963QualType ASTContext::getBlockDescriptorExtendedType() {
2964 if (BlockDescriptorExtendedType)
2965 return getTagDeclType(BlockDescriptorExtendedType);
2966
2967 RecordDecl *T;
2968 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00002969 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2970 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00002971 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00002972
2973 QualType FieldTypes[] = {
2974 UnsignedLongTy,
2975 UnsignedLongTy,
2976 getPointerType(VoidPtrTy),
2977 getPointerType(VoidPtrTy)
2978 };
2979
2980 const char *FieldNames[] = {
2981 "reserved",
2982 "Size",
2983 "CopyFuncPtr",
2984 "DestroyFuncPtr"
2985 };
2986
2987 for (size_t i = 0; i < 4; ++i) {
2988 FieldDecl *Field = FieldDecl::Create(*this,
2989 T,
2990 SourceLocation(),
2991 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00002992 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00002993 /*BitWidth=*/0,
2994 /*Mutable=*/false);
2995 T->addDecl(Field);
2996 }
2997
Douglas Gregor838db382010-02-11 01:19:42 +00002998 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00002999
3000 BlockDescriptorExtendedType = T;
3001
3002 return getTagDeclType(BlockDescriptorExtendedType);
3003}
3004
3005void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3006 const RecordType *Rec = T->getAs<RecordType>();
3007 assert(Rec && "Invalid BlockDescriptorType");
3008 BlockDescriptorExtendedType = Rec->getDecl();
3009}
3010
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003011bool ASTContext::BlockRequiresCopying(QualType Ty) {
3012 if (Ty->isBlockPointerType())
3013 return true;
3014 if (isObjCNSObjectType(Ty))
3015 return true;
3016 if (Ty->isObjCObjectPointerType())
3017 return true;
3018 return false;
3019}
3020
3021QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3022 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003023 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003024 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003025 // unsigned int __flags;
3026 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003027 // void *__copy_helper; // as needed
3028 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003029 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003030 // } *
3031
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003032 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3033
3034 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003035 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003036 llvm::SmallString<36> Name;
3037 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3038 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003039 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003040 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3041 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003042 T->startDefinition();
3043 QualType Int32Ty = IntTy;
3044 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3045 QualType FieldTypes[] = {
3046 getPointerType(VoidPtrTy),
3047 getPointerType(getTagDeclType(T)),
3048 Int32Ty,
3049 Int32Ty,
3050 getPointerType(VoidPtrTy),
3051 getPointerType(VoidPtrTy),
3052 Ty
3053 };
3054
3055 const char *FieldNames[] = {
3056 "__isa",
3057 "__forwarding",
3058 "__flags",
3059 "__size",
3060 "__copy_helper",
3061 "__destroy_helper",
3062 DeclName,
3063 };
3064
3065 for (size_t i = 0; i < 7; ++i) {
3066 if (!HasCopyAndDispose && i >=4 && i <= 5)
3067 continue;
3068 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3069 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003070 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003071 /*BitWidth=*/0, /*Mutable=*/false);
3072 T->addDecl(Field);
3073 }
3074
Douglas Gregor838db382010-02-11 01:19:42 +00003075 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003076
3077 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003078}
3079
3080
3081QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003082 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003083 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003084 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003085 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003086 llvm::SmallString<36> Name;
3087 llvm::raw_svector_ostream(Name) << "__block_literal_"
3088 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003089 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003090 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3091 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003092 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003093 QualType FieldTypes[] = {
3094 getPointerType(VoidPtrTy),
3095 IntTy,
3096 IntTy,
3097 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003098 (BlockHasCopyDispose ?
3099 getPointerType(getBlockDescriptorExtendedType()) :
3100 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003101 };
3102
3103 const char *FieldNames[] = {
3104 "__isa",
3105 "__flags",
3106 "__reserved",
3107 "__FuncPtr",
3108 "__descriptor"
3109 };
3110
3111 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003112 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003113 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003114 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003115 /*BitWidth=*/0, /*Mutable=*/false);
3116 T->addDecl(Field);
3117 }
3118
3119 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3120 const Expr *E = BlockDeclRefDecls[i];
3121 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3122 clang::IdentifierInfo *Name = 0;
3123 if (BDRE) {
3124 const ValueDecl *D = BDRE->getDecl();
3125 Name = &Idents.get(D->getName());
3126 }
3127 QualType FieldType = E->getType();
3128
3129 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003130 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3131 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003132
3133 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00003134 Name, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003135 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003136 T->addDecl(Field);
3137 }
3138
Douglas Gregor838db382010-02-11 01:19:42 +00003139 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003140
3141 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003142}
3143
Douglas Gregor319ac892009-04-23 22:29:11 +00003144void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003145 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003146 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3147 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3148}
3149
Anders Carlssone8c49532007-10-29 06:33:42 +00003150// This returns true if a type has been typedefed to BOOL:
3151// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003152static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003153 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003154 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3155 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003156
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003157 return false;
3158}
3159
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003160/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003161/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003162CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003163 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003164
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003165 // Make all integer and enum types at least as large as an int
Ken Dyck199c3d62010-01-11 17:06:35 +00003166 if (sz.isPositive() && type->isIntegralType())
3167 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003168 // Treat arrays as pointers, since that's how they're passed in.
3169 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003170 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003171 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003172}
3173
3174static inline
3175std::string charUnitsToString(const CharUnits &CU) {
3176 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003177}
3178
David Chisnall5e530af2009-11-17 19:33:30 +00003179/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3180/// declaration.
3181void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3182 std::string& S) {
3183 const BlockDecl *Decl = Expr->getBlockDecl();
3184 QualType BlockTy =
3185 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3186 // Encode result type.
3187 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3188 // Compute size of all parameters.
3189 // Start with computing size of a pointer in number of bytes.
3190 // FIXME: There might(should) be a better way of doing this computation!
3191 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003192 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3193 CharUnits ParmOffset = PtrSize;
David Chisnall5e530af2009-11-17 19:33:30 +00003194 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3195 E = Decl->param_end(); PI != E; ++PI) {
3196 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003197 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003198 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003199 ParmOffset += sz;
3200 }
3201 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003202 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003203 // Block pointer and offset.
3204 S += "@?0";
3205 ParmOffset = PtrSize;
3206
3207 // Argument types.
3208 ParmOffset = PtrSize;
3209 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3210 Decl->param_end(); PI != E; ++PI) {
3211 ParmVarDecl *PVDecl = *PI;
3212 QualType PType = PVDecl->getOriginalType();
3213 if (const ArrayType *AT =
3214 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3215 // Use array's original type only if it has known number of
3216 // elements.
3217 if (!isa<ConstantArrayType>(AT))
3218 PType = PVDecl->getType();
3219 } else if (PType->isFunctionType())
3220 PType = PVDecl->getType();
3221 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003222 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003223 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003224 }
3225}
3226
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003227/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003228/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003229void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003230 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003231 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003232 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003233 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003234 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003235 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003236 // Compute size of all parameters.
3237 // Start with computing size of a pointer in number of bytes.
3238 // FIXME: There might(should) be a better way of doing this computation!
3239 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003240 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003241 // The first two arguments (self and _cmd) are pointers; account for
3242 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003243 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003244 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3245 E = Decl->param_end(); PI != E; ++PI) {
3246 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003247 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003248 assert (sz.isPositive() &&
3249 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003250 ParmOffset += sz;
3251 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003252 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003253 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003254 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003255
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003256 // Argument types.
3257 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003258 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3259 E = Decl->param_end(); PI != E; ++PI) {
3260 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003261 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003262 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003263 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3264 // Use array's original type only if it has known number of
3265 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003266 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003267 PType = PVDecl->getType();
3268 } else if (PType->isFunctionType())
3269 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003270 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003271 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003272 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003273 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003274 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003275 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003276 }
3277}
3278
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003279/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003280/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003281/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3282/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003283/// Property attributes are stored as a comma-delimited C string. The simple
3284/// attributes readonly and bycopy are encoded as single characters. The
3285/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3286/// encoded as single characters, followed by an identifier. Property types
3287/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003288/// these attributes are defined by the following enumeration:
3289/// @code
3290/// enum PropertyAttributes {
3291/// kPropertyReadOnly = 'R', // property is read-only.
3292/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3293/// kPropertyByref = '&', // property is a reference to the value last assigned
3294/// kPropertyDynamic = 'D', // property is dynamic
3295/// kPropertyGetter = 'G', // followed by getter selector name
3296/// kPropertySetter = 'S', // followed by setter selector name
3297/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3298/// kPropertyType = 't' // followed by old-style type encoding.
3299/// kPropertyWeak = 'W' // 'weak' property
3300/// kPropertyStrong = 'P' // property GC'able
3301/// kPropertyNonAtomic = 'N' // property non-atomic
3302/// };
3303/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003304void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003305 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003306 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003307 // Collect information from the property implementation decl(s).
3308 bool Dynamic = false;
3309 ObjCPropertyImplDecl *SynthesizePID = 0;
3310
3311 // FIXME: Duplicated code due to poor abstraction.
3312 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003313 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003314 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3315 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003316 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003317 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003318 ObjCPropertyImplDecl *PID = *i;
3319 if (PID->getPropertyDecl() == PD) {
3320 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3321 Dynamic = true;
3322 } else {
3323 SynthesizePID = PID;
3324 }
3325 }
3326 }
3327 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003328 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003329 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003330 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003331 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003332 ObjCPropertyImplDecl *PID = *i;
3333 if (PID->getPropertyDecl() == PD) {
3334 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3335 Dynamic = true;
3336 } else {
3337 SynthesizePID = PID;
3338 }
3339 }
Mike Stump1eb44332009-09-09 15:08:12 +00003340 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003341 }
3342 }
3343
3344 // FIXME: This is not very efficient.
3345 S = "T";
3346
3347 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003348 // GCC has some special rules regarding encoding of properties which
3349 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003350 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003351 true /* outermost type */,
3352 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003353
3354 if (PD->isReadOnly()) {
3355 S += ",R";
3356 } else {
3357 switch (PD->getSetterKind()) {
3358 case ObjCPropertyDecl::Assign: break;
3359 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003360 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003361 }
3362 }
3363
3364 // It really isn't clear at all what this means, since properties
3365 // are "dynamic by default".
3366 if (Dynamic)
3367 S += ",D";
3368
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003369 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3370 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003371
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003372 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3373 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003374 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003375 }
3376
3377 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3378 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003379 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003380 }
3381
3382 if (SynthesizePID) {
3383 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3384 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003385 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003386 }
3387
3388 // FIXME: OBJCGC: weak & strong
3389}
3390
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003391/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003392/// Another legacy compatibility encoding: 32-bit longs are encoded as
3393/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003394/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3395///
3396void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003397 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003398 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003399 if (BT->getKind() == BuiltinType::ULong &&
3400 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003401 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003402 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003403 if (BT->getKind() == BuiltinType::Long &&
3404 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003405 PointeeTy = IntTy;
3406 }
3407 }
3408}
3409
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003410void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003411 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003412 // We follow the behavior of gcc, expanding structures which are
3413 // directly pointed to, and expanding embedded structures. Note that
3414 // these rules are sufficient to prevent recursive encoding of the
3415 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003416 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003417 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003418}
3419
Mike Stump1eb44332009-09-09 15:08:12 +00003420static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003421 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003422 const Expr *E = FD->getBitWidth();
3423 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3424 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003425 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003426 S += 'b';
3427 S += llvm::utostr(N);
3428}
3429
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003430// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003431void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3432 bool ExpandPointedToStructures,
3433 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003434 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003435 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003436 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003437 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003438 if (FD && FD->isBitField())
3439 return EncodeBitField(this, S, FD);
3440 char encoding;
3441 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003442 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003443 case BuiltinType::Void: encoding = 'v'; break;
3444 case BuiltinType::Bool: encoding = 'B'; break;
3445 case BuiltinType::Char_U:
3446 case BuiltinType::UChar: encoding = 'C'; break;
3447 case BuiltinType::UShort: encoding = 'S'; break;
3448 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003449 case BuiltinType::ULong:
3450 encoding =
3451 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003452 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003453 case BuiltinType::UInt128: encoding = 'T'; break;
3454 case BuiltinType::ULongLong: encoding = 'Q'; break;
3455 case BuiltinType::Char_S:
3456 case BuiltinType::SChar: encoding = 'c'; break;
3457 case BuiltinType::Short: encoding = 's'; break;
3458 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003459 case BuiltinType::Long:
3460 encoding =
3461 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003462 break;
3463 case BuiltinType::LongLong: encoding = 'q'; break;
3464 case BuiltinType::Int128: encoding = 't'; break;
3465 case BuiltinType::Float: encoding = 'f'; break;
3466 case BuiltinType::Double: encoding = 'd'; break;
3467 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003468 }
Mike Stump1eb44332009-09-09 15:08:12 +00003469
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003470 S += encoding;
3471 return;
3472 }
Mike Stump1eb44332009-09-09 15:08:12 +00003473
John McCall183700f2009-09-21 23:43:11 +00003474 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003475 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003476 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003477 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003478 return;
3479 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003480
Ted Kremenek6217b802009-07-29 21:53:49 +00003481 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003482 if (PT->isObjCSelType()) {
3483 S += ':';
3484 return;
3485 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003486 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003487
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003488 bool isReadOnly = false;
3489 // For historical/compatibility reasons, the read-only qualifier of the
3490 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3491 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003492 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003493 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003494 if (OutermostType && T.isConstQualified()) {
3495 isReadOnly = true;
3496 S += 'r';
3497 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003498 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003499 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003500 while (P->getAs<PointerType>())
3501 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003502 if (P.isConstQualified()) {
3503 isReadOnly = true;
3504 S += 'r';
3505 }
3506 }
3507 if (isReadOnly) {
3508 // Another legacy compatibility encoding. Some ObjC qualifier and type
3509 // combinations need to be rearranged.
3510 // Rewrite "in const" from "nr" to "rn"
3511 const char * s = S.c_str();
3512 int len = S.length();
3513 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3514 std::string replace = "rn";
3515 S.replace(S.end()-2, S.end(), replace);
3516 }
3517 }
Mike Stump1eb44332009-09-09 15:08:12 +00003518
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003519 if (PointeeTy->isCharType()) {
3520 // char pointer types should be encoded as '*' unless it is a
3521 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003522 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003523 S += '*';
3524 return;
3525 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003526 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003527 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3528 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3529 S += '#';
3530 return;
3531 }
3532 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3533 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3534 S += '@';
3535 return;
3536 }
3537 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003538 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003539 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003540 getLegacyIntegralTypeEncoding(PointeeTy);
3541
Mike Stump1eb44332009-09-09 15:08:12 +00003542 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003543 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003544 return;
3545 }
Mike Stump1eb44332009-09-09 15:08:12 +00003546
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003547 if (const ArrayType *AT =
3548 // Ignore type qualifiers etc.
3549 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003550 if (isa<IncompleteArrayType>(AT)) {
3551 // Incomplete arrays are encoded as a pointer to the array element.
3552 S += '^';
3553
Mike Stump1eb44332009-09-09 15:08:12 +00003554 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003555 false, ExpandStructures, FD);
3556 } else {
3557 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003558
Anders Carlsson559a8332009-02-22 01:38:57 +00003559 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3560 S += llvm::utostr(CAT->getSize().getZExtValue());
3561 else {
3562 //Variable length arrays are encoded as a regular array with 0 elements.
3563 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3564 S += '0';
3565 }
Mike Stump1eb44332009-09-09 15:08:12 +00003566
3567 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003568 false, ExpandStructures, FD);
3569 S += ']';
3570 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003571 return;
3572 }
Mike Stump1eb44332009-09-09 15:08:12 +00003573
John McCall183700f2009-09-21 23:43:11 +00003574 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003575 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003576 return;
3577 }
Mike Stump1eb44332009-09-09 15:08:12 +00003578
Ted Kremenek6217b802009-07-29 21:53:49 +00003579 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003580 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003581 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003582 // Anonymous structures print as '?'
3583 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3584 S += II->getName();
3585 } else {
3586 S += '?';
3587 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003588 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003589 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003590 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3591 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003592 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003593 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003594 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003595 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003596 S += '"';
3597 }
Mike Stump1eb44332009-09-09 15:08:12 +00003598
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003599 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003600 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003601 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003602 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003603 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003604 QualType qt = Field->getType();
3605 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003606 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003607 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003608 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003609 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003610 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003611 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003612 return;
3613 }
Mike Stump1eb44332009-09-09 15:08:12 +00003614
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003615 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003616 if (FD && FD->isBitField())
3617 EncodeBitField(this, S, FD);
3618 else
3619 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003620 return;
3621 }
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003623 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003624 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003625 return;
3626 }
Mike Stump1eb44332009-09-09 15:08:12 +00003627
John McCall0953e762009-09-24 19:53:00 +00003628 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003629 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003630 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003631 S += '{';
3632 const IdentifierInfo *II = OI->getIdentifier();
3633 S += II->getName();
3634 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003635 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003636 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003637 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003638 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003639 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003640 RecFields[i]);
3641 else
Mike Stump1eb44332009-09-09 15:08:12 +00003642 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003643 FD);
3644 }
3645 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003646 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003647 }
Mike Stump1eb44332009-09-09 15:08:12 +00003648
John McCall183700f2009-09-21 23:43:11 +00003649 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003650 if (OPT->isObjCIdType()) {
3651 S += '@';
3652 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003653 }
Mike Stump1eb44332009-09-09 15:08:12 +00003654
Steve Naroff27d20a22009-10-28 22:03:49 +00003655 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3656 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3657 // Since this is a binary compatibility issue, need to consult with runtime
3658 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003659 S += '#';
3660 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003661 }
Mike Stump1eb44332009-09-09 15:08:12 +00003662
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003663 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003664 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003665 ExpandPointedToStructures,
3666 ExpandStructures, FD);
3667 if (FD || EncodingProperty) {
3668 // Note that we do extended encoding of protocol qualifer list
3669 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003670 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003671 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3672 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003673 S += '<';
3674 S += (*I)->getNameAsString();
3675 S += '>';
3676 }
3677 S += '"';
3678 }
3679 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003680 }
Mike Stump1eb44332009-09-09 15:08:12 +00003681
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003682 QualType PointeeTy = OPT->getPointeeType();
3683 if (!EncodingProperty &&
3684 isa<TypedefType>(PointeeTy.getTypePtr())) {
3685 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003686 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003687 // {...};
3688 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003689 getObjCEncodingForTypeImpl(PointeeTy, S,
3690 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003691 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003692 return;
3693 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003694
3695 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003696 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003697 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003698 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003699 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3700 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003701 S += '<';
3702 S += (*I)->getNameAsString();
3703 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003704 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003705 S += '"';
3706 }
3707 return;
3708 }
Mike Stump1eb44332009-09-09 15:08:12 +00003709
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003710 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003711}
3712
Mike Stump1eb44332009-09-09 15:08:12 +00003713void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003714 std::string& S) const {
3715 if (QT & Decl::OBJC_TQ_In)
3716 S += 'n';
3717 if (QT & Decl::OBJC_TQ_Inout)
3718 S += 'N';
3719 if (QT & Decl::OBJC_TQ_Out)
3720 S += 'o';
3721 if (QT & Decl::OBJC_TQ_Bycopy)
3722 S += 'O';
3723 if (QT & Decl::OBJC_TQ_Byref)
3724 S += 'R';
3725 if (QT & Decl::OBJC_TQ_Oneway)
3726 S += 'V';
3727}
3728
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003729void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003730 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003731
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003732 BuiltinVaListType = T;
3733}
3734
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003735void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003736 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003737}
3738
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003739void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003740 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003741}
3742
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003743void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003744 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003745}
3746
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003747void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003748 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003749}
3750
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003751void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003752 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003753 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003754
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003755 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003756}
3757
John McCall0bd6feb2009-12-02 08:04:21 +00003758/// \brief Retrieve the template name that corresponds to a non-empty
3759/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003760TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3761 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003762 unsigned size = End - Begin;
3763 assert(size > 1 && "set is not overloaded!");
3764
3765 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3766 size * sizeof(FunctionTemplateDecl*));
3767 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3768
3769 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00003770 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00003771 NamedDecl *D = *I;
3772 assert(isa<FunctionTemplateDecl>(D) ||
3773 (isa<UsingShadowDecl>(D) &&
3774 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3775 *Storage++ = D;
3776 }
3777
3778 return TemplateName(OT);
3779}
3780
Douglas Gregor7532dc62009-03-30 22:58:21 +00003781/// \brief Retrieve the template name that represents a qualified
3782/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00003783TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003784 bool TemplateKeyword,
3785 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00003786 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00003787 llvm::FoldingSetNodeID ID;
3788 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3789
3790 void *InsertPos = 0;
3791 QualifiedTemplateName *QTN =
3792 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3793 if (!QTN) {
3794 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3795 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3796 }
3797
3798 return TemplateName(QTN);
3799}
3800
3801/// \brief Retrieve the template name that represents a dependent
3802/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00003803TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003804 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00003805 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00003806 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00003807
3808 llvm::FoldingSetNodeID ID;
3809 DependentTemplateName::Profile(ID, NNS, Name);
3810
3811 void *InsertPos = 0;
3812 DependentTemplateName *QTN =
3813 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3814
3815 if (QTN)
3816 return TemplateName(QTN);
3817
3818 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3819 if (CanonNNS == NNS) {
3820 QTN = new (*this,4) DependentTemplateName(NNS, Name);
3821 } else {
3822 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3823 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003824 DependentTemplateName *CheckQTN =
3825 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3826 assert(!CheckQTN && "Dependent type name canonicalization broken");
3827 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00003828 }
3829
3830 DependentTemplateNames.InsertNode(QTN, InsertPos);
3831 return TemplateName(QTN);
3832}
3833
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003834/// \brief Retrieve the template name that represents a dependent
3835/// template name such as \c MetaFun::template operator+.
3836TemplateName
3837ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3838 OverloadedOperatorKind Operator) {
3839 assert((!NNS || NNS->isDependent()) &&
3840 "Nested name specifier must be dependent");
3841
3842 llvm::FoldingSetNodeID ID;
3843 DependentTemplateName::Profile(ID, NNS, Operator);
3844
3845 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00003846 DependentTemplateName *QTN
3847 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003848
3849 if (QTN)
3850 return TemplateName(QTN);
3851
3852 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3853 if (CanonNNS == NNS) {
3854 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3855 } else {
3856 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3857 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00003858
3859 DependentTemplateName *CheckQTN
3860 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3861 assert(!CheckQTN && "Dependent template name canonicalization broken");
3862 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00003863 }
3864
3865 DependentTemplateNames.InsertNode(QTN, InsertPos);
3866 return TemplateName(QTN);
3867}
3868
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003869/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00003870/// TargetInfo, produce the corresponding type. The unsigned @p Type
3871/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00003872CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003873 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00003874 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003875 case TargetInfo::SignedShort: return ShortTy;
3876 case TargetInfo::UnsignedShort: return UnsignedShortTy;
3877 case TargetInfo::SignedInt: return IntTy;
3878 case TargetInfo::UnsignedInt: return UnsignedIntTy;
3879 case TargetInfo::SignedLong: return LongTy;
3880 case TargetInfo::UnsignedLong: return UnsignedLongTy;
3881 case TargetInfo::SignedLongLong: return LongLongTy;
3882 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3883 }
3884
3885 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00003886 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00003887}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00003888
3889//===----------------------------------------------------------------------===//
3890// Type Predicates.
3891//===----------------------------------------------------------------------===//
3892
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003893/// isObjCNSObjectType - Return true if this is an NSObject object using
3894/// NSObject attribute on a c-style pointer type.
3895/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00003896/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003897///
3898bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3899 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3900 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003901 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003902 return true;
3903 }
Mike Stump1eb44332009-09-09 15:08:12 +00003904 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00003905}
3906
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003907/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3908/// garbage collection attribute.
3909///
John McCall0953e762009-09-24 19:53:00 +00003910Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3911 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003912 if (getLangOptions().ObjC1 &&
3913 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00003914 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003915 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00003916 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003917 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00003918 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00003919 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003920 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003921 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003922 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00003923 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00003924 // Non-pointers have none gc'able attribute regardless of the attribute
3925 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00003926 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00003927 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003928 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00003929 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00003930}
3931
Chris Lattner6ac46a42008-04-07 06:51:04 +00003932//===----------------------------------------------------------------------===//
3933// Type Compatibility Testing
3934//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00003935
Mike Stump1eb44332009-09-09 15:08:12 +00003936/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00003937/// compatible.
3938static bool areCompatVectorTypes(const VectorType *LHS,
3939 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00003940 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00003941 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00003942 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00003943}
3944
Steve Naroff4084c302009-07-23 01:01:38 +00003945//===----------------------------------------------------------------------===//
3946// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3947//===----------------------------------------------------------------------===//
3948
3949/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3950/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003951bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3952 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00003953 if (lProto == rProto)
3954 return true;
3955 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3956 E = rProto->protocol_end(); PI != E; ++PI)
3957 if (ProtocolCompatibleWithProtocol(lProto, *PI))
3958 return true;
3959 return false;
3960}
3961
Steve Naroff4084c302009-07-23 01:01:38 +00003962/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3963/// return true if lhs's protocols conform to rhs's protocol; false
3964/// otherwise.
3965bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3966 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3967 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3968 return false;
3969}
3970
3971/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3972/// ObjCQualifiedIDType.
3973bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3974 bool compare) {
3975 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00003976 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003977 lhs->isObjCIdType() || lhs->isObjCClassType())
3978 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003979 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00003980 rhs->isObjCIdType() || rhs->isObjCClassType())
3981 return true;
3982
3983 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00003984 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003985
Steve Naroff4084c302009-07-23 01:01:38 +00003986 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003987
Steve Naroff4084c302009-07-23 01:01:38 +00003988 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003989 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00003990 // make sure we check the class hierarchy.
3991 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
3992 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
3993 E = lhsQID->qual_end(); I != E; ++I) {
3994 // when comparing an id<P> on lhs with a static type on rhs,
3995 // see if static class implements all of id's protocols, directly or
3996 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00003997 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00003998 return false;
3999 }
4000 }
4001 // If there are no qualifiers and no interface, we have an 'id'.
4002 return true;
4003 }
Mike Stump1eb44332009-09-09 15:08:12 +00004004 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004005 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4006 E = lhsQID->qual_end(); I != E; ++I) {
4007 ObjCProtocolDecl *lhsProto = *I;
4008 bool match = false;
4009
4010 // when comparing an id<P> on lhs with a static type on rhs,
4011 // see if static class implements all of id's protocols, directly or
4012 // through its super class and categories.
4013 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4014 E = rhsOPT->qual_end(); J != E; ++J) {
4015 ObjCProtocolDecl *rhsProto = *J;
4016 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4017 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4018 match = true;
4019 break;
4020 }
4021 }
Mike Stump1eb44332009-09-09 15:08:12 +00004022 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004023 // make sure we check the class hierarchy.
4024 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4025 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4026 E = lhsQID->qual_end(); I != E; ++I) {
4027 // when comparing an id<P> on lhs with a static type on rhs,
4028 // see if static class implements all of id's protocols, directly or
4029 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004030 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004031 match = true;
4032 break;
4033 }
4034 }
4035 }
4036 if (!match)
4037 return false;
4038 }
Mike Stump1eb44332009-09-09 15:08:12 +00004039
Steve Naroff4084c302009-07-23 01:01:38 +00004040 return true;
4041 }
Mike Stump1eb44332009-09-09 15:08:12 +00004042
Steve Naroff4084c302009-07-23 01:01:38 +00004043 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4044 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4045
Mike Stump1eb44332009-09-09 15:08:12 +00004046 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004047 lhs->getAsObjCInterfacePointerType()) {
4048 if (lhsOPT->qual_empty()) {
4049 bool match = false;
4050 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4051 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4052 E = rhsQID->qual_end(); I != E; ++I) {
4053 // when comparing an id<P> on lhs with a static type on rhs,
4054 // see if static class implements all of id's protocols, directly or
4055 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004056 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004057 match = true;
4058 break;
4059 }
4060 }
4061 if (!match)
4062 return false;
4063 }
4064 return true;
4065 }
Mike Stump1eb44332009-09-09 15:08:12 +00004066 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004067 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4068 E = lhsOPT->qual_end(); I != E; ++I) {
4069 ObjCProtocolDecl *lhsProto = *I;
4070 bool match = false;
4071
4072 // when comparing an id<P> on lhs with a static type on rhs,
4073 // see if static class implements all of id's protocols, directly or
4074 // through its super class and categories.
4075 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4076 E = rhsQID->qual_end(); J != E; ++J) {
4077 ObjCProtocolDecl *rhsProto = *J;
4078 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4079 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4080 match = true;
4081 break;
4082 }
4083 }
4084 if (!match)
4085 return false;
4086 }
4087 return true;
4088 }
4089 return false;
4090}
4091
Eli Friedman3d815e72008-08-22 00:56:42 +00004092/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004093/// compatible for assignment from RHS to LHS. This handles validation of any
4094/// protocol qualifiers on the LHS or RHS.
4095///
Steve Naroff14108da2009-07-10 23:34:53 +00004096bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4097 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004098 // If either type represents the built-in 'id' or 'Class' types, return true.
4099 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004100 return true;
4101
Steve Naroff4084c302009-07-23 01:01:38 +00004102 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004103 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4104 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004105 false);
4106
Steve Naroff14108da2009-07-10 23:34:53 +00004107 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4108 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004109 if (LHS && RHS) // We have 2 user-defined types.
4110 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004111
Steve Naroff4084c302009-07-23 01:01:38 +00004112 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004113}
4114
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004115/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4116/// for providing type-safty for objective-c pointers used to pass/return
4117/// arguments in block literals. When passed as arguments, passing 'A*' where
4118/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4119/// not OK. For the return type, the opposite is not OK.
4120bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4121 const ObjCObjectPointerType *LHSOPT,
4122 const ObjCObjectPointerType *RHSOPT) {
4123 if (RHSOPT->isObjCBuiltinType())
4124 return true;
4125
4126 if (LHSOPT->isObjCBuiltinType()) {
4127 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4128 }
4129
4130 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
4131 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4132 QualType(RHSOPT,0),
4133 false);
4134
4135 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4136 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4137 if (LHS && RHS) { // We have 2 user-defined types.
4138 if (LHS != RHS) {
4139 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4140 return false;
4141 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4142 return true;
4143 }
4144 else
4145 return true;
4146 }
4147 return false;
4148}
4149
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004150/// getIntersectionOfProtocols - This routine finds the intersection of set
4151/// of protocols inherited from two distinct objective-c pointer objects.
4152/// It is used to build composite qualifier list of the composite type of
4153/// the conditional expression involving two objective-c pointer objects.
4154static
4155void getIntersectionOfProtocols(ASTContext &Context,
4156 const ObjCObjectPointerType *LHSOPT,
4157 const ObjCObjectPointerType *RHSOPT,
4158 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4159
4160 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4161 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4162
4163 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4164 unsigned LHSNumProtocols = LHS->getNumProtocols();
4165 if (LHSNumProtocols > 0)
4166 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4167 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004168 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4169 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004170 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4171 LHSInheritedProtocols.end());
4172 }
4173
4174 unsigned RHSNumProtocols = RHS->getNumProtocols();
4175 if (RHSNumProtocols > 0) {
4176 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4177 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4178 if (InheritedProtocolSet.count(RHSProtocols[i]))
4179 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4180 }
4181 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004182 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004183 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004184 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4185 RHSInheritedProtocols.begin(),
4186 E = RHSInheritedProtocols.end(); I != E; ++I)
4187 if (InheritedProtocolSet.count((*I)))
4188 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004189 }
4190}
4191
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004192/// areCommonBaseCompatible - Returns common base class of the two classes if
4193/// one found. Note that this is O'2 algorithm. But it will be called as the
4194/// last type comparison in a ?-exp of ObjC pointer types before a
4195/// warning is issued. So, its invokation is extremely rare.
4196QualType ASTContext::areCommonBaseCompatible(
4197 const ObjCObjectPointerType *LHSOPT,
4198 const ObjCObjectPointerType *RHSOPT) {
4199 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4200 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4201 if (!LHS || !RHS)
4202 return QualType();
4203
4204 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4205 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4206 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004207 if (canAssignObjCInterfaces(LHS, RHS)) {
4208 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4209 getIntersectionOfProtocols(*this,
4210 LHSOPT, RHSOPT, IntersectionOfProtocols);
4211 if (IntersectionOfProtocols.empty())
4212 LHSTy = getObjCObjectPointerType(LHSTy);
4213 else
4214 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4215 IntersectionOfProtocols.size());
4216 return LHSTy;
4217 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004218 }
4219
4220 return QualType();
4221}
4222
Eli Friedman3d815e72008-08-22 00:56:42 +00004223bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4224 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004225 // Verify that the base decls are compatible: the RHS must be a subclass of
4226 // the LHS.
4227 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4228 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004229
Chris Lattner6ac46a42008-04-07 06:51:04 +00004230 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4231 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004232 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004233 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004234
Chris Lattner6ac46a42008-04-07 06:51:04 +00004235 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4236 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004237 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004238 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004239
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004240 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4241 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004242 LHSPI != LHSPE; LHSPI++) {
4243 bool RHSImplementsProtocol = false;
4244
4245 // If the RHS doesn't implement the protocol on the left, the types
4246 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004247 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004248 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004249 RHSPI != RHSPE; RHSPI++) {
4250 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004251 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004252 break;
4253 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004254 }
4255 // FIXME: For better diagnostics, consider passing back the protocol name.
4256 if (!RHSImplementsProtocol)
4257 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004258 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004259 // The RHS implements all protocols listed on the LHS.
4260 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004261}
4262
Steve Naroff389bf462009-02-12 17:52:19 +00004263bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4264 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004265 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4266 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004267
Steve Naroff14108da2009-07-10 23:34:53 +00004268 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004269 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004270
4271 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4272 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004273}
4274
Mike Stump1eb44332009-09-09 15:08:12 +00004275/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004276/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004277/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004278/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004279bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004280 if (getLangOptions().CPlusPlus)
4281 return hasSameType(LHS, RHS);
4282
Eli Friedman3d815e72008-08-22 00:56:42 +00004283 return !mergeTypes(LHS, RHS).isNull();
4284}
4285
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004286bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4287 return !mergeTypes(LHS, RHS, true).isNull();
4288}
4289
4290QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4291 bool OfBlockPointer) {
John McCall183700f2009-09-21 23:43:11 +00004292 const FunctionType *lbase = lhs->getAs<FunctionType>();
4293 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004294 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4295 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004296 bool allLTypes = true;
4297 bool allRTypes = true;
4298
4299 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004300 QualType retType;
4301 if (OfBlockPointer)
4302 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4303 else
4304 retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman3d815e72008-08-22 00:56:42 +00004305 if (retType.isNull()) return QualType();
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004306 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004307 allLTypes = false;
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004308 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004309 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004310 // FIXME: double check this
Rafael Espindola264ba482010-03-30 20:24:48 +00004311 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4312 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
4313 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4314 if (NoReturn != lbaseInfo.getNoReturn())
Mike Stump24556362009-07-25 21:26:53 +00004315 allLTypes = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00004316 if (NoReturn != rbaseInfo.getNoReturn())
Mike Stump24556362009-07-25 21:26:53 +00004317 allRTypes = false;
Rafael Espindola264ba482010-03-30 20:24:48 +00004318 CallingConv lcc = lbaseInfo.getCC();
4319 CallingConv rcc = rbaseInfo.getCC();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004320 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004321 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004322 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004323
Eli Friedman3d815e72008-08-22 00:56:42 +00004324 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004325 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4326 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004327 unsigned lproto_nargs = lproto->getNumArgs();
4328 unsigned rproto_nargs = rproto->getNumArgs();
4329
4330 // Compatible functions must have the same number of arguments
4331 if (lproto_nargs != rproto_nargs)
4332 return QualType();
4333
4334 // Variadic and non-variadic functions aren't compatible
4335 if (lproto->isVariadic() != rproto->isVariadic())
4336 return QualType();
4337
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004338 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4339 return QualType();
4340
Eli Friedman3d815e72008-08-22 00:56:42 +00004341 // Check argument compatibility
4342 llvm::SmallVector<QualType, 10> types;
4343 for (unsigned i = 0; i < lproto_nargs; i++) {
4344 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4345 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004346 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
Eli Friedman3d815e72008-08-22 00:56:42 +00004347 if (argtype.isNull()) return QualType();
4348 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004349 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4350 allLTypes = false;
4351 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4352 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004353 }
4354 if (allLTypes) return lhs;
4355 if (allRTypes) return rhs;
4356 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004357 lproto->isVariadic(), lproto->getTypeQuals(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004358 false, false, 0, 0,
4359 FunctionType::ExtInfo(NoReturn, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004360 }
4361
4362 if (lproto) allRTypes = false;
4363 if (rproto) allLTypes = false;
4364
Douglas Gregor72564e72009-02-26 23:50:07 +00004365 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004366 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004367 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004368 if (proto->isVariadic()) return QualType();
4369 // Check that the types are compatible with the types that
4370 // would result from default argument promotions (C99 6.7.5.3p15).
4371 // The only types actually affected are promotable integer
4372 // types and floats, which would be passed as a different
4373 // type depending on whether the prototype is visible.
4374 unsigned proto_nargs = proto->getNumArgs();
4375 for (unsigned i = 0; i < proto_nargs; ++i) {
4376 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004377
4378 // Look at the promotion type of enum types, since that is the type used
4379 // to pass enum values.
4380 if (const EnumType *Enum = argTy->getAs<EnumType>())
4381 argTy = Enum->getDecl()->getPromotionType();
4382
Eli Friedman3d815e72008-08-22 00:56:42 +00004383 if (argTy->isPromotableIntegerType() ||
4384 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4385 return QualType();
4386 }
4387
4388 if (allLTypes) return lhs;
4389 if (allRTypes) return rhs;
4390 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004391 proto->getNumArgs(), proto->isVariadic(),
Rafael Espindola264ba482010-03-30 20:24:48 +00004392 proto->getTypeQuals(),
4393 false, false, 0, 0,
4394 FunctionType::ExtInfo(NoReturn, lcc));
Eli Friedman3d815e72008-08-22 00:56:42 +00004395 }
4396
4397 if (allLTypes) return lhs;
4398 if (allRTypes) return rhs;
Rafael Espindola264ba482010-03-30 20:24:48 +00004399 FunctionType::ExtInfo Info(NoReturn, lcc);
4400 return getFunctionNoProtoType(retType, Info);
Eli Friedman3d815e72008-08-22 00:56:42 +00004401}
4402
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004403QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4404 bool OfBlockPointer) {
Bill Wendling43d69752007-12-03 07:33:35 +00004405 // C++ [expr]: If an expression initially has the type "reference to T", the
4406 // type is adjusted to "T" prior to any further analysis, the expression
4407 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004408 // expression is an lvalue unless the reference is an rvalue reference and
4409 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004410 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4411 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4412
Eli Friedman3d815e72008-08-22 00:56:42 +00004413 QualType LHSCan = getCanonicalType(LHS),
4414 RHSCan = getCanonicalType(RHS);
4415
4416 // If two types are identical, they are compatible.
4417 if (LHSCan == RHSCan)
4418 return LHS;
4419
John McCall0953e762009-09-24 19:53:00 +00004420 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004421 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4422 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004423 if (LQuals != RQuals) {
4424 // If any of these qualifiers are different, we have a type
4425 // mismatch.
4426 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4427 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4428 return QualType();
4429
4430 // Exactly one GC qualifier difference is allowed: __strong is
4431 // okay if the other type has no GC qualifier but is an Objective
4432 // C object pointer (i.e. implicitly strong by default). We fix
4433 // this by pretending that the unqualified type was actually
4434 // qualified __strong.
4435 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4436 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4437 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4438
4439 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4440 return QualType();
4441
4442 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4443 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4444 }
4445 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4446 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4447 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004448 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004449 }
4450
4451 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004452
Eli Friedman852d63b2009-06-01 01:22:52 +00004453 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4454 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004455
Chris Lattner1adb8832008-01-14 05:45:46 +00004456 // We want to consider the two function types to be the same for these
4457 // comparisons, just force one to the other.
4458 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4459 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004460
4461 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004462 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4463 LHSClass = Type::ConstantArray;
4464 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4465 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004466
Nate Begeman213541a2008-04-18 23:10:10 +00004467 // Canonicalize ExtVector -> Vector.
4468 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4469 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004470
Chris Lattnera36a61f2008-04-07 05:43:21 +00004471 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004472 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004473 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004474 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004475 // Compatibility is based on the underlying type, not the promotion
4476 // type.
John McCall183700f2009-09-21 23:43:11 +00004477 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004478 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4479 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004480 }
John McCall183700f2009-09-21 23:43:11 +00004481 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004482 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4483 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004484 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004485
Eli Friedman3d815e72008-08-22 00:56:42 +00004486 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004487 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004488
Steve Naroff4a746782008-01-09 22:43:08 +00004489 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004490 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004491#define TYPE(Class, Base)
4492#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004493#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004494#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4495#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4496#include "clang/AST/TypeNodes.def"
4497 assert(false && "Non-canonical and dependent types shouldn't get here");
4498 return QualType();
4499
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004500 case Type::LValueReference:
4501 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004502 case Type::MemberPointer:
4503 assert(false && "C++ should never be in mergeTypes");
4504 return QualType();
4505
4506 case Type::IncompleteArray:
4507 case Type::VariableArray:
4508 case Type::FunctionProto:
4509 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004510 assert(false && "Types are eliminated above");
4511 return QualType();
4512
Chris Lattner1adb8832008-01-14 05:45:46 +00004513 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004514 {
4515 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004516 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4517 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004518 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4519 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004520 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004521 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004522 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004523 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004524 return getPointerType(ResultType);
4525 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004526 case Type::BlockPointer:
4527 {
4528 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004529 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4530 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004531 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
Steve Naroffc0febd52008-12-10 17:49:55 +00004532 if (ResultType.isNull()) return QualType();
4533 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4534 return LHS;
4535 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4536 return RHS;
4537 return getBlockPointerType(ResultType);
4538 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004539 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004540 {
4541 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4542 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4543 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4544 return QualType();
4545
4546 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4547 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4548 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4549 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004550 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4551 return LHS;
4552 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4553 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004554 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4555 ArrayType::ArraySizeModifier(), 0);
4556 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4557 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004558 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4559 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004560 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4561 return LHS;
4562 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4563 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004564 if (LVAT) {
4565 // FIXME: This isn't correct! But tricky to implement because
4566 // the array's size has to be the size of LHS, but the type
4567 // has to be different.
4568 return LHS;
4569 }
4570 if (RVAT) {
4571 // FIXME: This isn't correct! But tricky to implement because
4572 // the array's size has to be the size of RHS, but the type
4573 // has to be different.
4574 return RHS;
4575 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004576 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4577 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004578 return getIncompleteArrayType(ResultType,
4579 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004580 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004581 case Type::FunctionNoProto:
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004582 return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
Douglas Gregor72564e72009-02-26 23:50:07 +00004583 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004584 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004585 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004586 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004587 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004588 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004589 case Type::Complex:
4590 // Distinct complex types are incompatible.
4591 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004592 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004593 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00004594 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4595 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004596 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004597 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004598 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004599 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004600 // FIXME: This should be type compatibility, e.g. whether
4601 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004602 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4603 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004604 if (LHSIface && RHSIface &&
4605 canAssignObjCInterfaces(LHSIface, RHSIface))
4606 return LHS;
4607
Eli Friedman3d815e72008-08-22 00:56:42 +00004608 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004609 }
Steve Naroff14108da2009-07-10 23:34:53 +00004610 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004611 if (OfBlockPointer) {
4612 if (canAssignObjCInterfacesInBlockPointer(
4613 LHS->getAs<ObjCObjectPointerType>(),
4614 RHS->getAs<ObjCObjectPointerType>()))
4615 return LHS;
4616 return QualType();
4617 }
John McCall183700f2009-09-21 23:43:11 +00004618 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4619 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004620 return LHS;
4621
Steve Naroffbc76dd02008-12-10 22:14:21 +00004622 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004623 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004624 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004625
4626 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004627}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004628
Chris Lattner5426bf62008-04-07 07:01:58 +00004629//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004630// Integer Predicates
4631//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004632
Eli Friedmanad74a752008-06-28 06:23:08 +00004633unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004634 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004635 return 1;
John McCall842aef82009-12-09 09:09:27 +00004636 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004637 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004638 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004639 return (unsigned)getTypeSize(T);
4640}
4641
4642QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4643 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004644
4645 // Turn <4 x signed int> -> <4 x unsigned int>
4646 if (const VectorType *VTy = T->getAs<VectorType>())
4647 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson82287d12010-02-05 00:12:22 +00004648 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattner6a2b9262009-10-17 20:33:28 +00004649
4650 // For enums, we return the unsigned version of the base type.
4651 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004652 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004653
4654 const BuiltinType *BTy = T->getAs<BuiltinType>();
4655 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004656 switch (BTy->getKind()) {
4657 case BuiltinType::Char_S:
4658 case BuiltinType::SChar:
4659 return UnsignedCharTy;
4660 case BuiltinType::Short:
4661 return UnsignedShortTy;
4662 case BuiltinType::Int:
4663 return UnsignedIntTy;
4664 case BuiltinType::Long:
4665 return UnsignedLongTy;
4666 case BuiltinType::LongLong:
4667 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004668 case BuiltinType::Int128:
4669 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004670 default:
4671 assert(0 && "Unexpected signed integer type");
4672 return QualType();
4673 }
4674}
4675
Douglas Gregor2cf26342009-04-09 22:27:44 +00004676ExternalASTSource::~ExternalASTSource() { }
4677
4678void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004679
4680
4681//===----------------------------------------------------------------------===//
4682// Builtin Type Computation
4683//===----------------------------------------------------------------------===//
4684
4685/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4686/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004687static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004688 ASTContext::GetBuiltinTypeError &Error,
4689 bool AllowTypeModifiers = true) {
4690 // Modifiers.
4691 int HowLong = 0;
4692 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004693
Chris Lattner86df27b2009-06-14 00:45:47 +00004694 // Read the modifiers first.
4695 bool Done = false;
4696 while (!Done) {
4697 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004698 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004699 case 'S':
4700 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4701 assert(!Signed && "Can't use 'S' modifier multiple times!");
4702 Signed = true;
4703 break;
4704 case 'U':
4705 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4706 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4707 Unsigned = true;
4708 break;
4709 case 'L':
4710 assert(HowLong <= 2 && "Can't have LLLL modifier");
4711 ++HowLong;
4712 break;
4713 }
4714 }
4715
4716 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004717
Chris Lattner86df27b2009-06-14 00:45:47 +00004718 // Read the base type.
4719 switch (*Str++) {
4720 default: assert(0 && "Unknown builtin type letter!");
4721 case 'v':
4722 assert(HowLong == 0 && !Signed && !Unsigned &&
4723 "Bad modifiers used with 'v'!");
4724 Type = Context.VoidTy;
4725 break;
4726 case 'f':
4727 assert(HowLong == 0 && !Signed && !Unsigned &&
4728 "Bad modifiers used with 'f'!");
4729 Type = Context.FloatTy;
4730 break;
4731 case 'd':
4732 assert(HowLong < 2 && !Signed && !Unsigned &&
4733 "Bad modifiers used with 'd'!");
4734 if (HowLong)
4735 Type = Context.LongDoubleTy;
4736 else
4737 Type = Context.DoubleTy;
4738 break;
4739 case 's':
4740 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4741 if (Unsigned)
4742 Type = Context.UnsignedShortTy;
4743 else
4744 Type = Context.ShortTy;
4745 break;
4746 case 'i':
4747 if (HowLong == 3)
4748 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4749 else if (HowLong == 2)
4750 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4751 else if (HowLong == 1)
4752 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4753 else
4754 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4755 break;
4756 case 'c':
4757 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4758 if (Signed)
4759 Type = Context.SignedCharTy;
4760 else if (Unsigned)
4761 Type = Context.UnsignedCharTy;
4762 else
4763 Type = Context.CharTy;
4764 break;
4765 case 'b': // boolean
4766 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4767 Type = Context.BoolTy;
4768 break;
4769 case 'z': // size_t.
4770 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4771 Type = Context.getSizeType();
4772 break;
4773 case 'F':
4774 Type = Context.getCFConstantStringType();
4775 break;
4776 case 'a':
4777 Type = Context.getBuiltinVaListType();
4778 assert(!Type.isNull() && "builtin va list type not initialized!");
4779 break;
4780 case 'A':
4781 // This is a "reference" to a va_list; however, what exactly
4782 // this means depends on how va_list is defined. There are two
4783 // different kinds of va_list: ones passed by value, and ones
4784 // passed by reference. An example of a by-value va_list is
4785 // x86, where va_list is a char*. An example of by-ref va_list
4786 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4787 // we want this argument to be a char*&; for x86-64, we want
4788 // it to be a __va_list_tag*.
4789 Type = Context.getBuiltinVaListType();
4790 assert(!Type.isNull() && "builtin va list type not initialized!");
4791 if (Type->isArrayType()) {
4792 Type = Context.getArrayDecayedType(Type);
4793 } else {
4794 Type = Context.getLValueReferenceType(Type);
4795 }
4796 break;
4797 case 'V': {
4798 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004799 unsigned NumElements = strtoul(Str, &End, 10);
4800 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004801
Chris Lattner86df27b2009-06-14 00:45:47 +00004802 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004803
Chris Lattner86df27b2009-06-14 00:45:47 +00004804 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00004805 // FIXME: Don't know what to do about AltiVec.
4806 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattner86df27b2009-06-14 00:45:47 +00004807 break;
4808 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004809 case 'X': {
4810 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4811 Type = Context.getComplexType(ElementType);
4812 break;
4813 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004814 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004815 Type = Context.getFILEType();
4816 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004817 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004818 return QualType();
4819 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004820 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004821 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004822 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004823 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004824 else
4825 Type = Context.getjmp_bufType();
4826
Mike Stumpfd612db2009-07-28 23:47:15 +00004827 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004828 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004829 return QualType();
4830 }
4831 break;
Mike Stump782fa302009-07-28 02:25:19 +00004832 }
Mike Stump1eb44332009-09-09 15:08:12 +00004833
Chris Lattner86df27b2009-06-14 00:45:47 +00004834 if (!AllowTypeModifiers)
4835 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004836
Chris Lattner86df27b2009-06-14 00:45:47 +00004837 Done = false;
4838 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00004839 switch (char c = *Str++) {
Chris Lattner86df27b2009-06-14 00:45:47 +00004840 default: Done = true; --Str; break;
4841 case '*':
Chris Lattner86df27b2009-06-14 00:45:47 +00004842 case '&':
John McCall187ab372010-03-12 04:21:28 +00004843 {
4844 // Both pointers and references can have their pointee types
4845 // qualified with an address space.
4846 char *End;
4847 unsigned AddrSpace = strtoul(Str, &End, 10);
4848 if (End != Str && AddrSpace != 0) {
4849 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
4850 Str = End;
4851 }
4852 }
4853 if (c == '*')
4854 Type = Context.getPointerType(Type);
4855 else
4856 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00004857 break;
4858 // FIXME: There's no way to have a built-in with an rvalue ref arg.
4859 case 'C':
John McCall0953e762009-09-24 19:53:00 +00004860 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00004861 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00004862 case 'D':
4863 Type = Context.getVolatileType(Type);
4864 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004865 }
4866 }
Mike Stump1eb44332009-09-09 15:08:12 +00004867
Chris Lattner86df27b2009-06-14 00:45:47 +00004868 return Type;
4869}
4870
4871/// GetBuiltinType - Return the type for the specified builtin.
4872QualType ASTContext::GetBuiltinType(unsigned id,
4873 GetBuiltinTypeError &Error) {
4874 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00004875
Chris Lattner86df27b2009-06-14 00:45:47 +00004876 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004877
Chris Lattner86df27b2009-06-14 00:45:47 +00004878 Error = GE_None;
4879 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4880 if (Error != GE_None)
4881 return QualType();
4882 while (TypeStr[0] && TypeStr[0] != '.') {
4883 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4884 if (Error != GE_None)
4885 return QualType();
4886
4887 // Do array -> pointer decay. The builtin should use the decayed type.
4888 if (Ty->isArrayType())
4889 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00004890
Chris Lattner86df27b2009-06-14 00:45:47 +00004891 ArgTypes.push_back(Ty);
4892 }
4893
4894 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4895 "'.' should only occur at end of builtin type list!");
4896
4897 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4898 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4899 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00004900
4901 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00004902 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004903 TypeStr[0] == '.', 0, false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00004904 FunctionType::ExtInfo());
Chris Lattner86df27b2009-06-14 00:45:47 +00004905}
Eli Friedmana95d7572009-08-19 07:44:53 +00004906
4907QualType
4908ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4909 // Perform the usual unary conversions. We do this early so that
4910 // integral promotions to "int" can allow us to exit early, in the
4911 // lhs == rhs check. Also, for conversion purposes, we ignore any
4912 // qualifiers. For example, "const float" and "float" are
4913 // equivalent.
4914 if (lhs->isPromotableIntegerType())
4915 lhs = getPromotedIntegerType(lhs);
4916 else
4917 lhs = lhs.getUnqualifiedType();
4918 if (rhs->isPromotableIntegerType())
4919 rhs = getPromotedIntegerType(rhs);
4920 else
4921 rhs = rhs.getUnqualifiedType();
4922
4923 // If both types are identical, no conversion is needed.
4924 if (lhs == rhs)
4925 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004926
Eli Friedmana95d7572009-08-19 07:44:53 +00004927 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4928 // The caller can deal with this (e.g. pointer + int).
4929 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4930 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00004931
4932 // At this point, we have two different arithmetic types.
4933
Eli Friedmana95d7572009-08-19 07:44:53 +00004934 // Handle complex types first (C99 6.3.1.8p1).
4935 if (lhs->isComplexType() || rhs->isComplexType()) {
4936 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00004937 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004938 // convert the rhs to the lhs complex type.
4939 return lhs;
4940 }
Mike Stump1eb44332009-09-09 15:08:12 +00004941 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004942 // convert the lhs to the rhs complex type.
4943 return rhs;
4944 }
4945 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00004946 // When both operands are complex, the shorter operand is converted to the
4947 // type of the longer, and that is the type of the result. This corresponds
4948 // to what is done when combining two real floating-point operands.
4949 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00004950 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00004951 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00004952 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00004953 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00004954 // "double _Complex" is promoted to "long double _Complex".
4955 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004956
4957 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004958 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004959 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00004960 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00004961 }
Eli Friedmana95d7572009-08-19 07:44:53 +00004962 // At this point, lhs and rhs have the same rank/size. Now, make sure the
4963 // domains match. This is a requirement for our implementation, C99
4964 // does not require this promotion.
4965 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4966 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4967 return rhs;
4968 } else { // handle "_Complex double, double".
4969 return lhs;
4970 }
4971 }
4972 return lhs; // The domain/size match exactly.
4973 }
4974 // Now handle "real" floating types (i.e. float, double, long double).
4975 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4976 // if we have an integer operand, the result is the real floating type.
4977 if (rhs->isIntegerType()) {
4978 // convert rhs to the lhs floating point type.
4979 return lhs;
4980 }
4981 if (rhs->isComplexIntegerType()) {
4982 // convert rhs to the complex floating point type.
4983 return getComplexType(lhs);
4984 }
4985 if (lhs->isIntegerType()) {
4986 // convert lhs to the rhs floating point type.
4987 return rhs;
4988 }
Mike Stump1eb44332009-09-09 15:08:12 +00004989 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00004990 // convert lhs to the complex floating point type.
4991 return getComplexType(rhs);
4992 }
4993 // We have two real floating types, float/complex combos were handled above.
4994 // Convert the smaller operand to the bigger result.
4995 int result = getFloatingTypeOrder(lhs, rhs);
4996 if (result > 0) // convert the rhs
4997 return lhs;
4998 assert(result < 0 && "illegal float comparison");
4999 return rhs; // convert the lhs
5000 }
5001 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5002 // Handle GCC complex int extension.
5003 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5004 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5005
5006 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005007 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005008 rhsComplexInt->getElementType()) >= 0)
5009 return lhs; // convert the rhs
5010 return rhs;
5011 } else if (lhsComplexInt && rhs->isIntegerType()) {
5012 // convert the rhs to the lhs complex type.
5013 return lhs;
5014 } else if (rhsComplexInt && lhs->isIntegerType()) {
5015 // convert the lhs to the rhs complex type.
5016 return rhs;
5017 }
5018 }
5019 // Finally, we have two differing integer types.
5020 // The rules for this case are in C99 6.3.1.8
5021 int compare = getIntegerTypeOrder(lhs, rhs);
5022 bool lhsSigned = lhs->isSignedIntegerType(),
5023 rhsSigned = rhs->isSignedIntegerType();
5024 QualType destType;
5025 if (lhsSigned == rhsSigned) {
5026 // Same signedness; use the higher-ranked type
5027 destType = compare >= 0 ? lhs : rhs;
5028 } else if (compare != (lhsSigned ? 1 : -1)) {
5029 // The unsigned type has greater than or equal rank to the
5030 // signed type, so use the unsigned type
5031 destType = lhsSigned ? rhs : lhs;
5032 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5033 // The two types are different widths; if we are here, that
5034 // means the signed type is larger than the unsigned type, so
5035 // use the signed type.
5036 destType = lhsSigned ? lhs : rhs;
5037 } else {
5038 // The signed type is higher-ranked than the unsigned type,
5039 // but isn't actually any bigger (like unsigned int and long
5040 // on most 32-bit systems). Use the unsigned type corresponding
5041 // to the signed type.
5042 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5043 }
5044 return destType;
5045}