blob: 26b10b58713e8b3a6f23f40038610c4dca82e43f [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),
46 SourceMgr(SM), LangOpts(LOpts),
Mike Stump1eb44332009-09-09 15:08:12 +000047 LoadedExternalComments(false), FreeMemory(FreeMem), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +000048 Idents(idents), Selectors(sels),
Mike Stump1eb44332009-09-09 15:08:12 +000049 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
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
416/// \brief Determine whether the given comment is a Doxygen-style comment.
417///
418/// \param Start the start of the comment text.
419///
420/// \param End the end of the comment text.
421///
422/// \param Member whether we want to check whether this is a member comment
423/// (which requires a < after the Doxygen-comment delimiter). Otherwise,
424/// we only return true when we find a non-member comment.
Mike Stump1eb44332009-09-09 15:08:12 +0000425static bool
426isDoxygenComment(SourceManager &SourceMgr, SourceRange Comment,
Douglas Gregor2e222532009-07-02 17:08:52 +0000427 bool Member = false) {
Mike Stump1eb44332009-09-09 15:08:12 +0000428 const char *BufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000429 = SourceMgr.getBufferData(SourceMgr.getFileID(Comment.getBegin())).first;
430 const char *Start = BufferStart + SourceMgr.getFileOffset(Comment.getBegin());
431 const char* End = BufferStart + SourceMgr.getFileOffset(Comment.getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Douglas Gregor2e222532009-07-02 17:08:52 +0000433 if (End - Start < 4)
434 return false;
435
436 assert(Start[0] == '/' && "Not a comment?");
437 if (Start[1] == '*' && !(Start[2] == '!' || Start[2] == '*'))
438 return false;
439 if (Start[1] == '/' && !(Start[2] == '!' || Start[2] == '/'))
440 return false;
441
442 return (Start[3] == '<') == Member;
443}
444
445/// \brief Retrieve the comment associated with the given declaration, if
Mike Stump1eb44332009-09-09 15:08:12 +0000446/// it has one.
Douglas Gregor2e222532009-07-02 17:08:52 +0000447const char *ASTContext::getCommentForDecl(const Decl *D) {
448 if (!D)
449 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Douglas Gregor2e222532009-07-02 17:08:52 +0000451 // Check whether we have cached a comment string for this declaration
452 // already.
Mike Stump1eb44332009-09-09 15:08:12 +0000453 llvm::DenseMap<const Decl *, std::string>::iterator Pos
Douglas Gregor2e222532009-07-02 17:08:52 +0000454 = DeclComments.find(D);
455 if (Pos != DeclComments.end())
456 return Pos->second.c_str();
457
Mike Stump1eb44332009-09-09 15:08:12 +0000458 // If we have an external AST source and have not yet loaded comments from
Douglas Gregor2e222532009-07-02 17:08:52 +0000459 // that source, do so now.
460 if (ExternalSource && !LoadedExternalComments) {
461 std::vector<SourceRange> LoadedComments;
462 ExternalSource->ReadComments(LoadedComments);
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Douglas Gregor2e222532009-07-02 17:08:52 +0000464 if (!LoadedComments.empty())
465 Comments.insert(Comments.begin(), LoadedComments.begin(),
466 LoadedComments.end());
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Douglas Gregor2e222532009-07-02 17:08:52 +0000468 LoadedExternalComments = true;
469 }
Mike Stump1eb44332009-09-09 15:08:12 +0000470
471 // If there are no comments anywhere, we won't find anything.
Douglas Gregor2e222532009-07-02 17:08:52 +0000472 if (Comments.empty())
473 return 0;
474
475 // If the declaration doesn't map directly to a location in a file, we
476 // can't find the comment.
477 SourceLocation DeclStartLoc = D->getLocStart();
478 if (DeclStartLoc.isInvalid() || !DeclStartLoc.isFileID())
479 return 0;
480
481 // Find the comment that occurs just before this declaration.
482 std::vector<SourceRange>::iterator LastComment
Mike Stump1eb44332009-09-09 15:08:12 +0000483 = std::lower_bound(Comments.begin(), Comments.end(),
Douglas Gregor2e222532009-07-02 17:08:52 +0000484 SourceRange(DeclStartLoc),
485 BeforeInTranslationUnit(&SourceMgr));
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Douglas Gregor2e222532009-07-02 17:08:52 +0000487 // Decompose the location for the start of the declaration and find the
488 // beginning of the file buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000489 std::pair<FileID, unsigned> DeclStartDecomp
Douglas Gregor2e222532009-07-02 17:08:52 +0000490 = SourceMgr.getDecomposedLoc(DeclStartLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000491 const char *FileBufferStart
Douglas Gregor2e222532009-07-02 17:08:52 +0000492 = SourceMgr.getBufferData(DeclStartDecomp.first).first;
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Douglas Gregor2e222532009-07-02 17:08:52 +0000494 // First check whether we have a comment for a member.
495 if (LastComment != Comments.end() &&
496 !isa<TagDecl>(D) && !isa<NamespaceDecl>(D) &&
497 isDoxygenComment(SourceMgr, *LastComment, true)) {
498 std::pair<FileID, unsigned> LastCommentEndDecomp
499 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
500 if (DeclStartDecomp.first == LastCommentEndDecomp.first &&
501 SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second)
Mike Stump1eb44332009-09-09 15:08:12 +0000502 == SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000503 LastCommentEndDecomp.second)) {
504 // The Doxygen member comment comes after the declaration starts and
505 // is on the same line and in the same file as the declaration. This
506 // is the comment we want.
507 std::string &Result = DeclComments[D];
Mike Stump1eb44332009-09-09 15:08:12 +0000508 Result.append(FileBufferStart +
509 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000510 FileBufferStart + LastCommentEndDecomp.second + 1);
511 return Result.c_str();
512 }
513 }
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Douglas Gregor2e222532009-07-02 17:08:52 +0000515 if (LastComment == Comments.begin())
516 return 0;
517 --LastComment;
518
519 // Decompose the end of the comment.
520 std::pair<FileID, unsigned> LastCommentEndDecomp
521 = SourceMgr.getDecomposedLoc(LastComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Douglas Gregor2e222532009-07-02 17:08:52 +0000523 // If the comment and the declaration aren't in the same file, then they
524 // aren't related.
525 if (DeclStartDecomp.first != LastCommentEndDecomp.first)
526 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Douglas Gregor2e222532009-07-02 17:08:52 +0000528 // Check that we actually have a Doxygen comment.
529 if (!isDoxygenComment(SourceMgr, *LastComment))
530 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Douglas Gregor2e222532009-07-02 17:08:52 +0000532 // Compute the starting line for the declaration and for the end of the
533 // comment (this is expensive).
Mike Stump1eb44332009-09-09 15:08:12 +0000534 unsigned DeclStartLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000535 = SourceMgr.getLineNumber(DeclStartDecomp.first, DeclStartDecomp.second);
536 unsigned CommentEndLine
Mike Stump1eb44332009-09-09 15:08:12 +0000537 = SourceMgr.getLineNumber(LastCommentEndDecomp.first,
Douglas Gregor2e222532009-07-02 17:08:52 +0000538 LastCommentEndDecomp.second);
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Douglas Gregor2e222532009-07-02 17:08:52 +0000540 // If the comment does not end on the line prior to the declaration, then
541 // the comment is not associated with the declaration at all.
542 if (CommentEndLine + 1 != DeclStartLine)
543 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Douglas Gregor2e222532009-07-02 17:08:52 +0000545 // We have a comment, but there may be more comments on the previous lines.
546 // Keep looking so long as the comments are still Doxygen comments and are
547 // still adjacent.
Mike Stump1eb44332009-09-09 15:08:12 +0000548 unsigned ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000549 = SourceMgr.getSpellingLineNumber(LastComment->getBegin()) - 1;
550 std::vector<SourceRange>::iterator FirstComment = LastComment;
551 while (FirstComment != Comments.begin()) {
552 // Look at the previous comment
553 --FirstComment;
554 std::pair<FileID, unsigned> Decomp
555 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Douglas Gregor2e222532009-07-02 17:08:52 +0000557 // If this previous comment is in a different file, we're done.
558 if (Decomp.first != DeclStartDecomp.first) {
559 ++FirstComment;
560 break;
561 }
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Douglas Gregor2e222532009-07-02 17:08:52 +0000563 // If this comment is not a Doxygen comment, we're done.
564 if (!isDoxygenComment(SourceMgr, *FirstComment)) {
565 ++FirstComment;
566 break;
567 }
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Douglas Gregor2e222532009-07-02 17:08:52 +0000569 // If the line number is not what we expected, we're done.
570 unsigned Line = SourceMgr.getLineNumber(Decomp.first, Decomp.second);
571 if (Line != ExpectedLine) {
572 ++FirstComment;
573 break;
574 }
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Douglas Gregor2e222532009-07-02 17:08:52 +0000576 // Set the next expected line number.
Mike Stump1eb44332009-09-09 15:08:12 +0000577 ExpectedLine
Douglas Gregor2e222532009-07-02 17:08:52 +0000578 = SourceMgr.getSpellingLineNumber(FirstComment->getBegin()) - 1;
579 }
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Douglas Gregor2e222532009-07-02 17:08:52 +0000581 // The iterator range [FirstComment, LastComment] contains all of the
582 // BCPL comments that, together, are associated with this declaration.
583 // Form a single comment block string for this declaration that concatenates
584 // all of these comments.
585 std::string &Result = DeclComments[D];
586 while (FirstComment != LastComment) {
587 std::pair<FileID, unsigned> DecompStart
588 = SourceMgr.getDecomposedLoc(FirstComment->getBegin());
589 std::pair<FileID, unsigned> DecompEnd
590 = SourceMgr.getDecomposedLoc(FirstComment->getEnd());
591 Result.append(FileBufferStart + DecompStart.second,
592 FileBufferStart + DecompEnd.second + 1);
593 ++FirstComment;
594 }
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Douglas Gregor2e222532009-07-02 17:08:52 +0000596 // Append the last comment line.
Mike Stump1eb44332009-09-09 15:08:12 +0000597 Result.append(FileBufferStart +
598 SourceMgr.getFileOffset(LastComment->getBegin()),
Douglas Gregor2e222532009-07-02 17:08:52 +0000599 FileBufferStart + LastCommentEndDecomp.second + 1);
600 return Result.c_str();
601}
602
Chris Lattner464175b2007-07-18 17:52:12 +0000603//===----------------------------------------------------------------------===//
604// Type Sizing and Analysis
605//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000606
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000607/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
608/// scalar floating point type.
609const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000610 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000611 assert(BT && "Not a floating point type!");
612 switch (BT->getKind()) {
613 default: assert(0 && "Not a floating point type!");
614 case BuiltinType::Float: return Target.getFloatFormat();
615 case BuiltinType::Double: return Target.getDoubleFormat();
616 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
617 }
618}
619
Ken Dyck8b752f12010-01-27 17:10:57 +0000620/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000621/// specified decl. Note that bitfields do not have a valid alignment, so
622/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000623/// If @p RefAsPointee, references are treated like their underlying type
624/// (for alignof), else they're treated like pointers (for CodeGen).
Ken Dyck8b752f12010-01-27 17:10:57 +0000625CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000626 unsigned Align = Target.getCharWidth();
627
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000628 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
Sean Huntbbd37c62009-11-21 08:43:09 +0000629 Align = std::max(Align, AA->getMaxAlignment());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000630
Chris Lattneraf707ab2009-01-24 21:53:27 +0000631 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
632 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000633 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000634 if (RefAsPointee)
635 T = RT->getPointeeType();
636 else
637 T = getPointerType(RT->getPointeeType());
638 }
639 if (!T->isIncompleteType() && !T->isFunctionType()) {
Anders Carlsson4cc2cfd2009-04-10 04:47:03 +0000640 // Incomplete or function types default to 1.
Eli Friedmandcdafb62009-02-22 02:56:25 +0000641 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
642 T = cast<ArrayType>(T)->getElementType();
643
644 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
645 }
Charles Davis05f62472010-02-23 04:52:00 +0000646 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
647 // In the case of a field in a packed struct, we want the minimum
648 // of the alignment of the field and the alignment of the struct.
649 Align = std::min(Align,
650 getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
651 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000652 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000653
Ken Dyck8b752f12010-01-27 17:10:57 +0000654 return CharUnits::fromQuantity(Align / Target.getCharWidth());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000655}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000656
Chris Lattnera7674d82007-07-13 22:13:22 +0000657/// getTypeSize - Return the size of the specified type, in bits. This method
658/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000659///
660/// FIXME: Pointers into different addr spaces could have different sizes and
661/// alignment requirements: getPointerInfo should take an AddrSpace, this
662/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000663std::pair<uint64_t, unsigned>
Daniel Dunbar1d751182008-11-08 05:48:37 +0000664ASTContext::getTypeInfo(const Type *T) {
Mike Stump5e301002009-02-27 18:32:39 +0000665 uint64_t Width=0;
666 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000667 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000668#define TYPE(Class, Base)
669#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000670#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000671#define DEPENDENT_TYPE(Class, Base) case Type::Class:
672#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000673 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000674 break;
675
Chris Lattner692233e2007-07-13 22:27:08 +0000676 case Type::FunctionNoProto:
677 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000678 // GCC extension: alignof(function) = 32 bits
679 Width = 0;
680 Align = 32;
681 break;
682
Douglas Gregor72564e72009-02-26 23:50:07 +0000683 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000684 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000685 Width = 0;
686 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
687 break;
688
Steve Narofffb22d962007-08-30 01:06:46 +0000689 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000690 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Chris Lattner98be4942008-03-05 18:54:05 +0000692 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000693 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000694 Align = EltInfo.second;
695 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000696 }
Nate Begeman213541a2008-04-18 23:10:10 +0000697 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000698 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000699 const VectorType *VT = cast<VectorType>(T);
700 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
701 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000702 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000703 // If the alignment is not a power of 2, round up to the next power of 2.
704 // This happens for non-power-of-2 length vectors.
Chris Lattner9fcfe922009-10-22 05:17:15 +0000705 if (VT->getNumElements() & (VT->getNumElements()-1)) {
706 Align = llvm::NextPowerOf2(Align);
707 Width = llvm::RoundUpToAlignment(Width, Align);
708 }
Chris Lattner030d8842007-07-19 22:06:24 +0000709 break;
710 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000711
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000712 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000713 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000714 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000715 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000716 // GCC extension: alignof(void) = 8 bits.
717 Width = 0;
718 Align = 8;
719 break;
720
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000721 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000722 Width = Target.getBoolWidth();
723 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000724 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000725 case BuiltinType::Char_S:
726 case BuiltinType::Char_U:
727 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000728 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000729 Width = Target.getCharWidth();
730 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000731 break;
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000732 case BuiltinType::WChar:
733 Width = Target.getWCharWidth();
734 Align = Target.getWCharAlign();
735 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000736 case BuiltinType::Char16:
737 Width = Target.getChar16Width();
738 Align = Target.getChar16Align();
739 break;
740 case BuiltinType::Char32:
741 Width = Target.getChar32Width();
742 Align = Target.getChar32Align();
743 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000744 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000745 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000746 Width = Target.getShortWidth();
747 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000748 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000749 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000750 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000751 Width = Target.getIntWidth();
752 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000753 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000754 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000755 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000756 Width = Target.getLongWidth();
757 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000758 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000759 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000760 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000761 Width = Target.getLongLongWidth();
762 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000763 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000764 case BuiltinType::Int128:
765 case BuiltinType::UInt128:
766 Width = 128;
767 Align = 128; // int128_t is 128-bit aligned on all targets.
768 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000769 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000770 Width = Target.getFloatWidth();
771 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000772 break;
773 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000774 Width = Target.getDoubleWidth();
775 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000776 break;
777 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000778 Width = Target.getLongDoubleWidth();
779 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000780 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000781 case BuiltinType::NullPtr:
782 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
783 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000784 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000785 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000786 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000787 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000788 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000789 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000790 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000791 case Type::BlockPointer: {
792 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
793 Width = Target.getPointerWidth(AS);
794 Align = Target.getPointerAlign(AS);
795 break;
796 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000797 case Type::LValueReference:
798 case Type::RValueReference: {
799 // alignof and sizeof should never enter this code path here, so we go
800 // the pointer route.
801 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
802 Width = Target.getPointerWidth(AS);
803 Align = Target.getPointerAlign(AS);
804 break;
805 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000806 case Type::Pointer: {
807 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
Chris Lattner5426bf62008-04-07 07:01:58 +0000808 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000809 Align = Target.getPointerAlign(AS);
810 break;
811 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000812 case Type::MemberPointer: {
Sebastian Redlf30208a2009-01-24 21:16:55 +0000813 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000814 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000815 getTypeInfo(getPointerDiffType());
816 Width = PtrDiffInfo.first;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000817 if (Pointee->isFunctionType())
818 Width *= 2;
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000819 Align = PtrDiffInfo.second;
820 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000821 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000822 case Type::Complex: {
823 // Complex types have the same alignment as their elements, but twice the
824 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000825 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000826 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000827 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000828 Align = EltInfo.second;
829 break;
830 }
Devang Patel44a3dde2008-06-04 21:54:36 +0000831 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000832 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000833 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
834 Width = Layout.getSize();
835 Align = Layout.getAlignment();
836 break;
837 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000838 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000839 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000840 const TagType *TT = cast<TagType>(T);
841
842 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000843 Width = 1;
844 Align = 1;
845 break;
846 }
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Daniel Dunbar1d751182008-11-08 05:48:37 +0000848 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000849 return getTypeInfo(ET->getDecl()->getIntegerType());
850
Daniel Dunbar1d751182008-11-08 05:48:37 +0000851 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000852 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
853 Width = Layout.getSize();
854 Align = Layout.getAlignment();
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000855 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000856 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000857
Chris Lattner9fcfe922009-10-22 05:17:15 +0000858 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000859 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
860 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000861
Chris Lattner9fcfe922009-10-22 05:17:15 +0000862 case Type::Elaborated:
863 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType()
864 .getTypePtr());
John McCall7da24312009-09-05 00:15:47 +0000865
Douglas Gregor18857642009-04-30 17:32:17 +0000866 case Type::Typedef: {
867 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000868 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
Sean Huntbbd37c62009-11-21 08:43:09 +0000869 Align = std::max(Aligned->getMaxAlignment(),
870 getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
Douglas Gregor18857642009-04-30 17:32:17 +0000871 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
872 } else
873 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Douglas Gregor7532dc62009-03-30 22:58:21 +0000874 break;
Chris Lattner71763312008-04-06 22:05:18 +0000875 }
Douglas Gregor18857642009-04-30 17:32:17 +0000876
877 case Type::TypeOfExpr:
878 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
879 .getTypePtr());
880
881 case Type::TypeOf:
882 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
883
Anders Carlsson395b4752009-06-24 19:06:50 +0000884 case Type::Decltype:
885 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
886 .getTypePtr());
887
Douglas Gregor18857642009-04-30 17:32:17 +0000888 case Type::QualifiedName:
889 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000890
John McCall3cb0ebd2010-03-10 03:28:59 +0000891 case Type::InjectedClassName:
892 return getTypeInfo(cast<InjectedClassNameType>(T)
893 ->getUnderlyingType().getTypePtr());
894
Douglas Gregor18857642009-04-30 17:32:17 +0000895 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000896 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000897 "Cannot request the size of a dependent type");
898 // FIXME: this is likely to be wrong once we support template
899 // aliases, since a template alias could refer to a typedef that
900 // has an __aligned__ attribute on it.
901 return getTypeInfo(getCanonicalType(T));
902 }
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Chris Lattner464175b2007-07-18 17:52:12 +0000904 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000905 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000906}
907
Ken Dyckbdc601b2009-12-22 14:23:30 +0000908/// getTypeSizeInChars - Return the size of the specified type, in characters.
909/// This method does not work on incomplete types.
910CharUnits ASTContext::getTypeSizeInChars(QualType T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000911 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000912}
913CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
Ken Dyck199c3d62010-01-11 17:06:35 +0000914 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
Ken Dyckbdc601b2009-12-22 14:23:30 +0000915}
916
Ken Dyck16e20cc2010-01-26 17:25:18 +0000917/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000918/// characters. This method does not work on incomplete types.
919CharUnits ASTContext::getTypeAlignInChars(QualType T) {
920 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
921}
922CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
923 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
924}
925
Chris Lattner34ebde42009-01-27 18:08:34 +0000926/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
927/// type for the current target in bits. This can be different than the ABI
928/// alignment in cases where it is beneficial for performance to overalign
929/// a data type.
930unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
931 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000932
933 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000934 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000935 T = CT->getElementType().getTypePtr();
936 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
937 T->isSpecificBuiltinType(BuiltinType::LongLong))
938 return std::max(ABIAlign, (unsigned)getTypeSize(T));
939
Chris Lattner34ebde42009-01-27 18:08:34 +0000940 return ABIAlign;
941}
942
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000943static void CollectLocalObjCIvars(ASTContext *Ctx,
944 const ObjCInterfaceDecl *OI,
945 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000946 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
947 E = OI->ivar_end(); I != E; ++I) {
Chris Lattnerf1690852009-03-31 08:48:01 +0000948 ObjCIvarDecl *IVDecl = *I;
Fariborz Jahaniana769c002008-12-17 21:40:49 +0000949 if (!IVDecl->isInvalidDecl())
950 Fields.push_back(cast<FieldDecl>(IVDecl));
951 }
952}
953
Daniel Dunbara80a0f62009-04-22 17:43:55 +0000954void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
955 llvm::SmallVectorImpl<FieldDecl*> &Fields) {
956 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
957 CollectObjCIvars(SuperClass, Fields);
958 CollectLocalObjCIvars(this, OI, Fields);
959}
960
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000961/// ShallowCollectObjCIvars -
962/// Collect all ivars, including those synthesized, in the current class.
963///
964void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000965 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000966 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
967 E = OI->ivar_end(); I != E; ++I) {
968 Ivars.push_back(*I);
969 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000970
971 CollectNonClassIvars(OI, Ivars);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000972}
973
Fariborz Jahanian98200742009-05-12 18:14:29 +0000974void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
975 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000976 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
977 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian98200742009-05-12 18:14:29 +0000978 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
979 Ivars.push_back(Ivar);
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Fariborz Jahanian98200742009-05-12 18:14:29 +0000981 // Also look into nested protocols.
982 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
983 E = PD->protocol_end(); P != E; ++P)
984 CollectProtocolSynthesizedIvars(*P, Ivars);
985}
986
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000987/// CollectNonClassIvars -
988/// This routine collects all other ivars which are not declared in the class.
989/// This includes synthesized ivars and those in class's implementation.
Fariborz Jahanian98200742009-05-12 18:14:29 +0000990///
Fariborz Jahanian11062e12010-02-19 00:31:17 +0000991void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
Fariborz Jahanian98200742009-05-12 18:14:29 +0000992 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian0e5ad252010-02-23 01:26:30 +0000993 // Find ivars declared in class extension.
994 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
995 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
996 E = CDecl->ivar_end(); I != E; ++I) {
997 Ivars.push_back(*I);
998 }
999 }
1000
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001001 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1002 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian98200742009-05-12 18:14:29 +00001003 if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
1004 Ivars.push_back(Ivar);
1005 }
1006 // Also look into interface's protocol list for properties declared
1007 // in the protocol and whose ivars are synthesized.
1008 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1009 PE = OI->protocol_end(); P != PE; ++P) {
1010 ObjCProtocolDecl *PD = (*P);
1011 CollectProtocolSynthesizedIvars(PD, Ivars);
1012 }
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001013
1014 // Also add any ivar defined in this class's implementation
1015 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
1016 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
1017 E = ImplDecl->ivar_end(); I != E; ++I)
1018 Ivars.push_back(*I);
1019 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001020}
1021
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001022/// CollectInheritedProtocols - Collect all protocols in current class and
1023/// those inherited by it.
1024void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001025 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001026 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1027 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1028 PE = OI->protocol_end(); P != PE; ++P) {
1029 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001030 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001031 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001032 PE = Proto->protocol_end(); P != PE; ++P) {
1033 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001034 CollectInheritedProtocols(*P, Protocols);
1035 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001036 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001037
1038 // Categories of this Interface.
1039 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1040 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1041 CollectInheritedProtocols(CDeclChain, Protocols);
1042 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1043 while (SD) {
1044 CollectInheritedProtocols(SD, Protocols);
1045 SD = SD->getSuperClass();
1046 }
1047 return;
1048 }
1049 if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1050 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
1051 PE = OC->protocol_end(); P != PE; ++P) {
1052 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001053 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001054 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1055 PE = Proto->protocol_end(); P != PE; ++P)
1056 CollectInheritedProtocols(*P, Protocols);
1057 }
1058 return;
1059 }
1060 if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1061 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1062 PE = OP->protocol_end(); P != PE; ++P) {
1063 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001064 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001065 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1066 PE = Proto->protocol_end(); P != PE; ++P)
1067 CollectInheritedProtocols(*P, Protocols);
1068 }
1069 return;
1070 }
1071}
1072
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001073unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
1074 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001075 for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(),
1076 E = PD->prop_end(); I != E; ++I)
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001077 if ((*I)->getPropertyIvarDecl())
1078 ++count;
1079
1080 // Also look into nested protocols.
1081 for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
1082 E = PD->protocol_end(); P != E; ++P)
1083 count += CountProtocolSynthesizedIvars(*P);
1084 return count;
1085}
1086
Mike Stump1eb44332009-09-09 15:08:12 +00001087unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001088 unsigned count = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001089 for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(),
1090 E = OI->prop_end(); I != E; ++I) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001091 if ((*I)->getPropertyIvarDecl())
1092 ++count;
1093 }
1094 // Also look into interface's protocol list for properties declared
1095 // in the protocol and whose ivars are synthesized.
1096 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
1097 PE = OI->protocol_end(); P != PE; ++P) {
1098 ObjCProtocolDecl *PD = (*P);
1099 count += CountProtocolSynthesizedIvars(PD);
1100 }
1101 return count;
1102}
1103
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001104/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1105ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1106 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1107 I = ObjCImpls.find(D);
1108 if (I != ObjCImpls.end())
1109 return cast<ObjCImplementationDecl>(I->second);
1110 return 0;
1111}
1112/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1113ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1114 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1115 I = ObjCImpls.find(D);
1116 if (I != ObjCImpls.end())
1117 return cast<ObjCCategoryImplDecl>(I->second);
1118 return 0;
1119}
1120
1121/// \brief Set the implementation of ObjCInterfaceDecl.
1122void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1123 ObjCImplementationDecl *ImplD) {
1124 assert(IFaceD && ImplD && "Passed null params");
1125 ObjCImpls[IFaceD] = ImplD;
1126}
1127/// \brief Set the implementation of ObjCCategoryDecl.
1128void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1129 ObjCCategoryImplDecl *ImplD) {
1130 assert(CatD && ImplD && "Passed null params");
1131 ObjCImpls[CatD] = ImplD;
1132}
1133
John McCalla93c9342009-12-07 02:54:59 +00001134/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001135///
John McCalla93c9342009-12-07 02:54:59 +00001136/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001137/// the TypeLoc wrappers.
1138///
1139/// \param T the type that will be the basis for type source info. This type
1140/// should refer to how the declarator was written in source code, not to
1141/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001142TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
John McCall109de5e2009-10-21 00:23:54 +00001143 unsigned DataSize) {
1144 if (!DataSize)
1145 DataSize = TypeLoc::getFullDataSizeForType(T);
1146 else
1147 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001148 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001149
John McCalla93c9342009-12-07 02:54:59 +00001150 TypeSourceInfo *TInfo =
1151 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1152 new (TInfo) TypeSourceInfo(T);
1153 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001154}
1155
John McCalla93c9342009-12-07 02:54:59 +00001156TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
John McCalla4eb74d2009-10-23 21:14:09 +00001157 SourceLocation L) {
John McCalla93c9342009-12-07 02:54:59 +00001158 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
John McCalla4eb74d2009-10-23 21:14:09 +00001159 DI->getTypeLoc().initialize(L);
1160 return DI;
1161}
1162
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001163/// getInterfaceLayoutImpl - Get or compute information about the
1164/// layout of the given interface.
1165///
1166/// \param Impl - If given, also include the layout of the interface's
1167/// implementation. This may differ by including synthesized ivars.
Devang Patel44a3dde2008-06-04 21:54:36 +00001168const ASTRecordLayout &
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001169ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
1170 const ObjCImplementationDecl *Impl) {
Daniel Dunbar532d4da2009-05-03 13:15:50 +00001171 assert(!D->isForwardDecl() && "Invalid interface decl!");
1172
Devang Patel44a3dde2008-06-04 21:54:36 +00001173 // Look up this layout, if already laid out, return what we have.
Mike Stump1eb44332009-09-09 15:08:12 +00001174 ObjCContainerDecl *Key =
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001175 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
1176 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
1177 return *Entry;
Devang Patel44a3dde2008-06-04 21:54:36 +00001178
Daniel Dunbar453addb2009-05-03 11:16:44 +00001179 // Add in synthesized ivar count if laying out an implementation.
1180 if (Impl) {
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001181 unsigned SynthCount = CountSynthesizedIvars(D);
Daniel Dunbard8fd6ff2009-05-03 11:41:43 +00001182 // If there aren't any sythesized ivars then reuse the interface
Daniel Dunbar453addb2009-05-03 11:16:44 +00001183 // entry. Note we can't cache this because we simply free all
1184 // entries later; however we shouldn't look up implementations
1185 // frequently.
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001186 if (SynthCount == 0)
Daniel Dunbar453addb2009-05-03 11:16:44 +00001187 return getObjCLayout(D, 0);
1188 }
1189
Mike Stump1eb44332009-09-09 15:08:12 +00001190 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001191 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl);
1192 ObjCLayouts[Key] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Devang Patel44a3dde2008-06-04 21:54:36 +00001194 return *NewEntry;
1195}
1196
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001197const ASTRecordLayout &
1198ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1199 return getObjCLayout(D, 0);
1200}
1201
1202const ASTRecordLayout &
1203ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1204 return getObjCLayout(D->getClassInterface(), D);
1205}
1206
Devang Patel88a981b2007-11-01 19:11:01 +00001207/// getASTRecordLayout - Get or compute information about the layout of the
Chris Lattner464175b2007-07-18 17:52:12 +00001208/// specified record (struct/union/class), which indicates its size and field
1209/// position information.
Chris Lattner98be4942008-03-05 18:54:05 +00001210const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
Douglas Gregor952b0172010-02-11 01:04:33 +00001211 D = D->getDefinition();
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001212 assert(D && "Cannot get layout of forward declarations!");
Eli Friedman4bd998b2008-05-30 09:31:38 +00001213
Chris Lattner464175b2007-07-18 17:52:12 +00001214 // Look up this layout, if already laid out, return what we have.
Eli Friedmanab22c432009-07-22 20:29:16 +00001215 // Note that we can't save a reference to the entry because this function
1216 // is recursive.
1217 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
Chris Lattner464175b2007-07-18 17:52:12 +00001218 if (Entry) return *Entry;
Eli Friedman4bd998b2008-05-30 09:31:38 +00001219
Mike Stump1eb44332009-09-09 15:08:12 +00001220 const ASTRecordLayout *NewEntry =
Anders Carlsson29445a02009-07-18 21:19:52 +00001221 ASTRecordLayoutBuilder::ComputeLayout(*this, D);
Eli Friedmanab22c432009-07-22 20:29:16 +00001222 ASTRecordLayouts[D] = NewEntry;
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Chris Lattner5d2a6302007-07-18 18:26:58 +00001224 return *NewEntry;
Chris Lattner464175b2007-07-18 17:52:12 +00001225}
1226
Anders Carlssonf53df232009-12-07 04:35:11 +00001227const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
Douglas Gregor952b0172010-02-11 01:04:33 +00001228 RD = cast<CXXRecordDecl>(RD->getDefinition());
Anders Carlssonf53df232009-12-07 04:35:11 +00001229 assert(RD && "Cannot get key function for forward declarations!");
1230
1231 const CXXMethodDecl *&Entry = KeyFunctions[RD];
1232 if (!Entry)
1233 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD);
1234 else
1235 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) &&
1236 "Key function changed!");
1237
1238 return Entry;
1239}
1240
Chris Lattnera7674d82007-07-13 22:13:22 +00001241//===----------------------------------------------------------------------===//
1242// Type creation/memoization methods
1243//===----------------------------------------------------------------------===//
1244
John McCall0953e762009-09-24 19:53:00 +00001245QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1246 unsigned Fast = Quals.getFastQualifiers();
1247 Quals.removeFastQualifiers();
1248
1249 // Check if we've already instantiated this type.
1250 llvm::FoldingSetNodeID ID;
1251 ExtQuals::Profile(ID, TypeNode, Quals);
1252 void *InsertPos = 0;
1253 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1254 assert(EQ->getQualifiers() == Quals);
1255 QualType T = QualType(EQ, Fast);
1256 return T;
1257 }
1258
John McCall6b304a02009-09-24 23:30:46 +00001259 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
John McCall0953e762009-09-24 19:53:00 +00001260 ExtQualNodes.InsertNode(New, InsertPos);
1261 QualType T = QualType(New, Fast);
1262 return T;
1263}
1264
1265QualType ASTContext::getVolatileType(QualType T) {
1266 QualType CanT = getCanonicalType(T);
1267 if (CanT.isVolatileQualified()) return T;
1268
1269 QualifierCollector Quals;
1270 const Type *TypeNode = Quals.strip(T);
1271 Quals.addVolatile();
1272
1273 return getExtQualType(TypeNode, Quals);
1274}
1275
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00001276QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001277 QualType CanT = getCanonicalType(T);
1278 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001279 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001280
John McCall0953e762009-09-24 19:53:00 +00001281 // If we are composing extended qualifiers together, merge together
1282 // into one ExtQuals node.
1283 QualifierCollector Quals;
1284 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001285
John McCall0953e762009-09-24 19:53:00 +00001286 // If this type already has an address space specified, it cannot get
1287 // another one.
1288 assert(!Quals.hasAddressSpace() &&
1289 "Type cannot be in multiple addr spaces!");
1290 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001291
John McCall0953e762009-09-24 19:53:00 +00001292 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001293}
1294
Chris Lattnerb7d25532009-02-18 22:53:11 +00001295QualType ASTContext::getObjCGCQualType(QualType T,
John McCall0953e762009-09-24 19:53:00 +00001296 Qualifiers::GC GCAttr) {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001297 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001298 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001299 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001301 if (T->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001302 QualType Pointee = T->getAs<PointerType>()->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001303 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001304 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1305 return getPointerType(ResultType);
1306 }
1307 }
Mike Stump1eb44332009-09-09 15:08:12 +00001308
John McCall0953e762009-09-24 19:53:00 +00001309 // If we are composing extended qualifiers together, merge together
1310 // into one ExtQuals node.
1311 QualifierCollector Quals;
1312 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001313
John McCall0953e762009-09-24 19:53:00 +00001314 // If this type already has an ObjCGC specified, it cannot get
1315 // another one.
1316 assert(!Quals.hasObjCGCAttr() &&
1317 "Type cannot have multiple ObjCGCs!");
1318 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001319
John McCall0953e762009-09-24 19:53:00 +00001320 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001321}
Chris Lattnera7674d82007-07-13 22:13:22 +00001322
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001323static QualType getNoReturnCallConvType(ASTContext& Context, QualType T,
1324 bool AddNoReturn,
1325 CallingConv CallConv) {
John McCall0953e762009-09-24 19:53:00 +00001326 QualType ResultType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001327 if (const PointerType *Pointer = T->getAs<PointerType>()) {
1328 QualType Pointee = Pointer->getPointeeType();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001329 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1330 CallConv);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001331 if (ResultType == Pointee)
1332 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001333
1334 ResultType = Context.getPointerType(ResultType);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001335 } else if (const BlockPointerType *BlockPointer
1336 = T->getAs<BlockPointerType>()) {
1337 QualType Pointee = BlockPointer->getPointeeType();
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001338 ResultType = getNoReturnCallConvType(Context, Pointee, AddNoReturn,
1339 CallConv);
Douglas Gregor43c79c22009-12-09 00:47:37 +00001340 if (ResultType == Pointee)
1341 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001342
1343 ResultType = Context.getBlockPointerType(ResultType);
1344 } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1345 if (F->getNoReturnAttr() == AddNoReturn && F->getCallConv() == CallConv)
Douglas Gregor43c79c22009-12-09 00:47:37 +00001346 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001347
Douglas Gregor43c79c22009-12-09 00:47:37 +00001348 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001349 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1350 AddNoReturn, CallConv);
John McCall0953e762009-09-24 19:53:00 +00001351 } else {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001352 const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
John McCall0953e762009-09-24 19:53:00 +00001353 ResultType
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001354 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1355 FPT->getNumArgs(), FPT->isVariadic(),
1356 FPT->getTypeQuals(),
1357 FPT->hasExceptionSpec(),
1358 FPT->hasAnyExceptionSpec(),
1359 FPT->getNumExceptions(),
1360 FPT->exception_begin(),
1361 AddNoReturn, CallConv);
John McCall0953e762009-09-24 19:53:00 +00001362 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001363 } else
1364 return T;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001365
1366 return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1367}
1368
1369QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1370 return getNoReturnCallConvType(*this, T, AddNoReturn, T.getCallConv());
1371}
1372
1373QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1374 return getNoReturnCallConvType(*this, T, T.getNoReturnAttr(), CallConv);
Mike Stump24556362009-07-25 21:26:53 +00001375}
1376
Reid Spencer5f016e22007-07-11 17:01:13 +00001377/// getComplexType - Return the uniqued reference to the type for a complex
1378/// number with the specified element type.
1379QualType ASTContext::getComplexType(QualType T) {
1380 // Unique pointers, to guarantee there is only one pointer of a particular
1381 // structure.
1382 llvm::FoldingSetNodeID ID;
1383 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Reid Spencer5f016e22007-07-11 17:01:13 +00001385 void *InsertPos = 0;
1386 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1387 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 // If the pointee type isn't canonical, this won't be a canonical type either,
1390 // so fill in the canonical type field.
1391 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001392 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001393 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Reid Spencer5f016e22007-07-11 17:01:13 +00001395 // Get the new insert position for the node we care about.
1396 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001397 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 }
John McCall6b304a02009-09-24 23:30:46 +00001399 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001400 Types.push_back(New);
1401 ComplexTypes.InsertNode(New, InsertPos);
1402 return QualType(New, 0);
1403}
1404
Reid Spencer5f016e22007-07-11 17:01:13 +00001405/// getPointerType - Return the uniqued reference to the type for a pointer to
1406/// the specified type.
1407QualType ASTContext::getPointerType(QualType T) {
1408 // Unique pointers, to guarantee there is only one pointer of a particular
1409 // structure.
1410 llvm::FoldingSetNodeID ID;
1411 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Reid Spencer5f016e22007-07-11 17:01:13 +00001413 void *InsertPos = 0;
1414 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1415 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Reid Spencer5f016e22007-07-11 17:01:13 +00001417 // If the pointee type isn't canonical, this won't be a canonical type either,
1418 // so fill in the canonical type field.
1419 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001420 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001421 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001422
Reid Spencer5f016e22007-07-11 17:01:13 +00001423 // Get the new insert position for the node we care about.
1424 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001425 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 }
John McCall6b304a02009-09-24 23:30:46 +00001427 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001428 Types.push_back(New);
1429 PointerTypes.InsertNode(New, InsertPos);
1430 return QualType(New, 0);
1431}
1432
Mike Stump1eb44332009-09-09 15:08:12 +00001433/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001434/// a pointer to the specified block.
1435QualType ASTContext::getBlockPointerType(QualType T) {
Steve Naroff296e8d52008-08-28 19:20:44 +00001436 assert(T->isFunctionType() && "block of function types only");
1437 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001438 // structure.
1439 llvm::FoldingSetNodeID ID;
1440 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Steve Naroff5618bd42008-08-27 16:04:49 +00001442 void *InsertPos = 0;
1443 if (BlockPointerType *PT =
1444 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1445 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001446
1447 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001448 // type either so fill in the canonical type field.
1449 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001450 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001451 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Steve Naroff5618bd42008-08-27 16:04:49 +00001453 // Get the new insert position for the node we care about.
1454 BlockPointerType *NewIP =
1455 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001456 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001457 }
John McCall6b304a02009-09-24 23:30:46 +00001458 BlockPointerType *New
1459 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001460 Types.push_back(New);
1461 BlockPointerTypes.InsertNode(New, InsertPos);
1462 return QualType(New, 0);
1463}
1464
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001465/// getLValueReferenceType - Return the uniqued reference to the type for an
1466/// lvalue reference to the specified type.
John McCall54e14c42009-10-22 22:37:11 +00001467QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001468 // Unique pointers, to guarantee there is only one pointer of a particular
1469 // structure.
1470 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001471 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001472
1473 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001474 if (LValueReferenceType *RT =
1475 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001477
John McCall54e14c42009-10-22 22:37:11 +00001478 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1479
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 // If the referencee type isn't canonical, this won't be a canonical type
1481 // either, so fill in the canonical type field.
1482 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001483 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1484 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1485 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001486
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001488 LValueReferenceType *NewIP =
1489 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001490 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 }
1492
John McCall6b304a02009-09-24 23:30:46 +00001493 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001494 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1495 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001496 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001497 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001498
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001499 return QualType(New, 0);
1500}
1501
1502/// getRValueReferenceType - Return the uniqued reference to the type for an
1503/// rvalue reference to the specified type.
1504QualType ASTContext::getRValueReferenceType(QualType T) {
1505 // Unique pointers, to guarantee there is only one pointer of a particular
1506 // structure.
1507 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001508 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001509
1510 void *InsertPos = 0;
1511 if (RValueReferenceType *RT =
1512 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1513 return QualType(RT, 0);
1514
John McCall54e14c42009-10-22 22:37:11 +00001515 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1516
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001517 // If the referencee type isn't canonical, this won't be a canonical type
1518 // either, so fill in the canonical type field.
1519 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001520 if (InnerRef || !T.isCanonical()) {
1521 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1522 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001523
1524 // Get the new insert position for the node we care about.
1525 RValueReferenceType *NewIP =
1526 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1527 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1528 }
1529
John McCall6b304a02009-09-24 23:30:46 +00001530 RValueReferenceType *New
1531 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001532 Types.push_back(New);
1533 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001534 return QualType(New, 0);
1535}
1536
Sebastian Redlf30208a2009-01-24 21:16:55 +00001537/// getMemberPointerType - Return the uniqued reference to the type for a
1538/// member pointer to the specified type, in the specified class.
Mike Stump1eb44332009-09-09 15:08:12 +00001539QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001540 // Unique pointers, to guarantee there is only one pointer of a particular
1541 // structure.
1542 llvm::FoldingSetNodeID ID;
1543 MemberPointerType::Profile(ID, T, Cls);
1544
1545 void *InsertPos = 0;
1546 if (MemberPointerType *PT =
1547 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1548 return QualType(PT, 0);
1549
1550 // If the pointee or class type isn't canonical, this won't be a canonical
1551 // type either, so fill in the canonical type field.
1552 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001553 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001554 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1555
1556 // Get the new insert position for the node we care about.
1557 MemberPointerType *NewIP =
1558 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1559 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1560 }
John McCall6b304a02009-09-24 23:30:46 +00001561 MemberPointerType *New
1562 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001563 Types.push_back(New);
1564 MemberPointerTypes.InsertNode(New, InsertPos);
1565 return QualType(New, 0);
1566}
1567
Mike Stump1eb44332009-09-09 15:08:12 +00001568/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001569/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001570QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001571 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001572 ArrayType::ArraySizeModifier ASM,
1573 unsigned EltTypeQuals) {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001574 assert((EltTy->isDependentType() ||
1575 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001576 "Constant array of VLAs is illegal!");
1577
Chris Lattner38aeec72009-05-13 04:12:56 +00001578 // Convert the array size into a canonical width matching the pointer size for
1579 // the target.
1580 llvm::APInt ArySize(ArySizeIn);
1581 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Reid Spencer5f016e22007-07-11 17:01:13 +00001583 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001584 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001587 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001588 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001589 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Reid Spencer5f016e22007-07-11 17:01:13 +00001591 // If the element type isn't canonical, this won't be a canonical type either,
1592 // so fill in the canonical type field.
1593 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001594 if (!EltTy.isCanonical()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001595 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
Steve Naroffc9406122007-08-30 18:10:14 +00001596 ASM, EltTypeQuals);
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001598 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001599 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001600 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001601 }
Mike Stump1eb44332009-09-09 15:08:12 +00001602
John McCall6b304a02009-09-24 23:30:46 +00001603 ConstantArrayType *New = new(*this,TypeAlignment)
1604 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001605 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001606 Types.push_back(New);
1607 return QualType(New, 0);
1608}
1609
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001610/// getVariableArrayType - Returns a non-unique reference to the type for a
1611/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001612QualType ASTContext::getVariableArrayType(QualType EltTy,
1613 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001614 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001615 unsigned EltTypeQuals,
1616 SourceRange Brackets) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001617 // Since we don't unique expressions, it isn't possible to unique VLA's
1618 // that have an expression provided for their size.
1619
John McCall6b304a02009-09-24 23:30:46 +00001620 VariableArrayType *New = new(*this, TypeAlignment)
1621 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001622
1623 VariableArrayTypes.push_back(New);
1624 Types.push_back(New);
1625 return QualType(New, 0);
1626}
1627
Douglas Gregor898574e2008-12-05 23:32:09 +00001628/// getDependentSizedArrayType - Returns a non-unique reference to
1629/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001630/// type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001631QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1632 Expr *NumElts,
Douglas Gregor898574e2008-12-05 23:32:09 +00001633 ArrayType::ArraySizeModifier ASM,
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001634 unsigned EltTypeQuals,
1635 SourceRange Brackets) {
Douglas Gregorcb78d882009-11-19 18:03:26 +00001636 assert((!NumElts || NumElts->isTypeDependent() ||
1637 NumElts->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001638 "Size must be type- or value-dependent!");
1639
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001640 void *InsertPos = 0;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001641 DependentSizedArrayType *Canon = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001642 llvm::FoldingSetNodeID ID;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001643
1644 if (NumElts) {
1645 // Dependently-sized array types that do not have a specified
1646 // number of elements will have their sizes deduced from an
1647 // initializer.
Douglas Gregorcb78d882009-11-19 18:03:26 +00001648 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1649 EltTypeQuals, NumElts);
1650
1651 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1652 }
1653
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001654 DependentSizedArrayType *New;
1655 if (Canon) {
1656 // We already have a canonical version of this array type; use it as
1657 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001658 New = new (*this, TypeAlignment)
1659 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1660 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001661 } else {
1662 QualType CanonEltTy = getCanonicalType(EltTy);
1663 if (CanonEltTy == EltTy) {
John McCall6b304a02009-09-24 23:30:46 +00001664 New = new (*this, TypeAlignment)
1665 DependentSizedArrayType(*this, EltTy, QualType(),
1666 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001667
Douglas Gregor789b1f62010-02-04 18:10:26 +00001668 if (NumElts) {
1669 DependentSizedArrayType *CanonCheck
1670 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1671 assert(!CanonCheck && "Dependent-sized canonical array type broken");
1672 (void)CanonCheck;
Douglas Gregorcb78d882009-11-19 18:03:26 +00001673 DependentSizedArrayTypes.InsertNode(New, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001674 }
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001675 } else {
1676 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1677 ASM, EltTypeQuals,
1678 SourceRange());
John McCall6b304a02009-09-24 23:30:46 +00001679 New = new (*this, TypeAlignment)
1680 DependentSizedArrayType(*this, EltTy, Canon,
1681 NumElts, ASM, EltTypeQuals, Brackets);
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001682 }
1683 }
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Douglas Gregor898574e2008-12-05 23:32:09 +00001685 Types.push_back(New);
1686 return QualType(New, 0);
1687}
1688
Eli Friedmanc5773c42008-02-15 18:16:39 +00001689QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1690 ArrayType::ArraySizeModifier ASM,
1691 unsigned EltTypeQuals) {
1692 llvm::FoldingSetNodeID ID;
Chris Lattner0be2ef22009-02-19 17:31:02 +00001693 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001694
1695 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001696 if (IncompleteArrayType *ATP =
Eli Friedmanc5773c42008-02-15 18:16:39 +00001697 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1698 return QualType(ATP, 0);
1699
1700 // If the element type isn't canonical, this won't be a canonical type
1701 // either, so fill in the canonical type field.
1702 QualType Canonical;
1703
John McCall467b27b2009-10-22 20:10:53 +00001704 if (!EltTy.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001705 Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001706 ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001707
1708 // Get the new insert position for the node we care about.
1709 IncompleteArrayType *NewIP =
1710 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001711 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001712 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001713
John McCall6b304a02009-09-24 23:30:46 +00001714 IncompleteArrayType *New = new (*this, TypeAlignment)
1715 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001716
1717 IncompleteArrayTypes.InsertNode(New, InsertPos);
1718 Types.push_back(New);
1719 return QualType(New, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001720}
1721
Steve Naroff73322922007-07-18 18:00:27 +00001722/// getVectorType - Return the unique reference to a vector type of
1723/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001724QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1725 bool IsAltiVec, bool IsPixel) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Chris Lattnerf52ab252008-04-06 22:59:24 +00001728 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Steve Naroff73322922007-07-18 18:00:27 +00001729 assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 // Check if we've already instantiated a vector of this type.
1732 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001733 VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1734 IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001735 void *InsertPos = 0;
1736 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1737 return QualType(VTP, 0);
1738
1739 // If the element type isn't canonical, this won't be a canonical type either,
1740 // so fill in the canonical type field.
1741 QualType Canonical;
John Thompson82287d12010-02-05 00:12:22 +00001742 if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1743 Canonical = getVectorType(getCanonicalType(vecType),
1744 NumElts, false, false);
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Reid Spencer5f016e22007-07-11 17:01:13 +00001746 // Get the new insert position for the node we care about.
1747 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001748 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001749 }
John McCall6b304a02009-09-24 23:30:46 +00001750 VectorType *New = new (*this, TypeAlignment)
John Thompson82287d12010-02-05 00:12:22 +00001751 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 VectorTypes.InsertNode(New, InsertPos);
1753 Types.push_back(New);
1754 return QualType(New, 0);
1755}
1756
Nate Begeman213541a2008-04-18 23:10:10 +00001757/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001758/// the specified element type and size. VectorType must be a built-in type.
Nate Begeman213541a2008-04-18 23:10:10 +00001759QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
Steve Naroff73322922007-07-18 18:00:27 +00001760 BuiltinType *baseType;
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Chris Lattnerf52ab252008-04-06 22:59:24 +00001762 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
Nate Begeman213541a2008-04-18 23:10:10 +00001763 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Steve Naroff73322922007-07-18 18:00:27 +00001765 // Check if we've already instantiated a vector of this type.
1766 llvm::FoldingSetNodeID ID;
John Thompson82287d12010-02-05 00:12:22 +00001767 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
Steve Naroff73322922007-07-18 18:00:27 +00001768 void *InsertPos = 0;
1769 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1770 return QualType(VTP, 0);
1771
1772 // If the element type isn't canonical, this won't be a canonical type either,
1773 // so fill in the canonical type field.
1774 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001775 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001776 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Steve Naroff73322922007-07-18 18:00:27 +00001778 // Get the new insert position for the node we care about.
1779 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001780 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001781 }
John McCall6b304a02009-09-24 23:30:46 +00001782 ExtVectorType *New = new (*this, TypeAlignment)
1783 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001784 VectorTypes.InsertNode(New, InsertPos);
1785 Types.push_back(New);
1786 return QualType(New, 0);
1787}
1788
Mike Stump1eb44332009-09-09 15:08:12 +00001789QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001790 Expr *SizeExpr,
1791 SourceLocation AttrLoc) {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001792 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001793 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001794 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001796 void *InsertPos = 0;
1797 DependentSizedExtVectorType *Canon
1798 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1799 DependentSizedExtVectorType *New;
1800 if (Canon) {
1801 // We already have a canonical version of this array type; use it as
1802 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001803 New = new (*this, TypeAlignment)
1804 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1805 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001806 } else {
1807 QualType CanonVecTy = getCanonicalType(vecType);
1808 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001809 New = new (*this, TypeAlignment)
1810 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1811 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001812
1813 DependentSizedExtVectorType *CanonCheck
1814 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1815 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1816 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001817 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1818 } else {
1819 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1820 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001821 New = new (*this, TypeAlignment)
1822 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001823 }
1824 }
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001826 Types.push_back(New);
1827 return QualType(New, 0);
1828}
1829
Douglas Gregor72564e72009-02-26 23:50:07 +00001830/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001831///
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001832QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, bool NoReturn,
1833 CallingConv CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001834 // Unique functions, to guarantee there is only one function of a particular
1835 // structure.
1836 llvm::FoldingSetNodeID ID;
John McCallf82b4e82010-02-04 05:44:44 +00001837 FunctionNoProtoType::Profile(ID, ResultTy, NoReturn, CallConv);
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Reid Spencer5f016e22007-07-11 17:01:13 +00001839 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001840 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001841 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001842 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Reid Spencer5f016e22007-07-11 17:01:13 +00001844 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001845 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001846 getCanonicalCallConv(CallConv) != CallConv) {
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001847 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), NoReturn,
John McCall04a67a62010-02-05 21:31:56 +00001848 getCanonicalCallConv(CallConv));
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Reid Spencer5f016e22007-07-11 17:01:13 +00001850 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001851 FunctionNoProtoType *NewIP =
1852 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001853 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001854 }
Mike Stump1eb44332009-09-09 15:08:12 +00001855
John McCall6b304a02009-09-24 23:30:46 +00001856 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCallf82b4e82010-02-04 05:44:44 +00001857 FunctionNoProtoType(ResultTy, Canonical, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001858 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001859 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001860 return QualType(New, 0);
1861}
1862
1863/// getFunctionType - Return a normal function type with a typed argument
1864/// list. isVariadic indicates whether the argument list includes '...'.
Chris Lattner61710852008-10-05 17:34:18 +00001865QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001866 unsigned NumArgs, bool isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001867 unsigned TypeQuals, bool hasExceptionSpec,
1868 bool hasAnyExceptionSpec, unsigned NumExs,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001869 const QualType *ExArray, bool NoReturn,
1870 CallingConv CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001871 // Unique functions, to guarantee there is only one function of a particular
1872 // structure.
1873 llvm::FoldingSetNodeID ID;
Douglas Gregor72564e72009-02-26 23:50:07 +00001874 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001875 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
John McCallf82b4e82010-02-04 05:44:44 +00001876 NumExs, ExArray, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001877
1878 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001879 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001880 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001881 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001882
1883 // Determine whether the type being created is already canonical or not.
John McCall54e14c42009-10-22 22:37:11 +00001884 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001886 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001887 isCanonical = false;
1888
1889 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001890 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001891 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001892 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001893 llvm::SmallVector<QualType, 16> CanonicalArgs;
1894 CanonicalArgs.reserve(NumArgs);
1895 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001896 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001897
Chris Lattnerf52ab252008-04-06 22:59:24 +00001898 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001899 CanonicalArgs.data(), NumArgs,
Douglas Gregor47259d92009-08-05 19:03:35 +00001900 isVariadic, TypeQuals, false,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001901 false, 0, 0, NoReturn,
John McCall04a67a62010-02-05 21:31:56 +00001902 getCanonicalCallConv(CallConv));
Sebastian Redl465226e2009-05-27 22:11:52 +00001903
Reid Spencer5f016e22007-07-11 17:01:13 +00001904 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001905 FunctionProtoType *NewIP =
1906 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Chris Lattnerf6e764f2008-10-12 00:26:57 +00001907 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001908 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001909
Douglas Gregor72564e72009-02-26 23:50:07 +00001910 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001911 // for two variable size arrays (for parameter and exception types) at the
1912 // end of them.
Mike Stump1eb44332009-09-09 15:08:12 +00001913 FunctionProtoType *FTP =
Sebastian Redl465226e2009-05-27 22:11:52 +00001914 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1915 NumArgs*sizeof(QualType) +
John McCall6b304a02009-09-24 23:30:46 +00001916 NumExs*sizeof(QualType), TypeAlignment);
Douglas Gregor72564e72009-02-26 23:50:07 +00001917 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
Sebastian Redl465226e2009-05-27 22:11:52 +00001918 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001919 ExArray, NumExs, Canonical, NoReturn, CallConv);
Reid Spencer5f016e22007-07-11 17:01:13 +00001920 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001921 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001922 return QualType(FTP, 0);
1923}
1924
John McCall3cb0ebd2010-03-10 03:28:59 +00001925#ifndef NDEBUG
1926static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1927 if (!isa<CXXRecordDecl>(D)) return false;
1928 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1929 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1930 return true;
1931 if (RD->getDescribedClassTemplate() &&
1932 !isa<ClassTemplateSpecializationDecl>(RD))
1933 return true;
1934 return false;
1935}
1936#endif
1937
1938/// getInjectedClassNameType - Return the unique reference to the
1939/// injected class name type for the specified templated declaration.
1940QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1941 QualType TST) {
1942 assert(NeedsInjectedClassNameType(Decl));
1943 if (Decl->TypeForDecl) {
1944 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1945 } else if (CXXRecordDecl *PrevDecl
1946 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1947 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1948 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1949 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1950 } else {
1951 Decl->TypeForDecl = new (*this, TypeAlignment)
1952 InjectedClassNameType(Decl, TST, TST->getCanonicalTypeInternal());
1953 Types.push_back(Decl->TypeForDecl);
1954 }
1955 return QualType(Decl->TypeForDecl, 0);
1956}
1957
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001958/// getTypeDeclType - Return the unique reference to the type for the
1959/// specified type declaration.
John McCallbecb8d52010-03-10 06:48:02 +00001960QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00001961 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00001962 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00001963
John McCall19c85762010-02-16 03:57:14 +00001964 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001965 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00001966
1967 if (const ObjCInterfaceDecl *ObjCInterface
Mike Stump9fdbab32009-07-31 02:02:20 +00001968 = dyn_cast<ObjCInterfaceDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001969 return getObjCInterfaceType(ObjCInterface);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001970
John McCallbecb8d52010-03-10 06:48:02 +00001971 assert(!isa<TemplateTypeParmDecl>(Decl) &&
1972 "Template type parameter types are always available.");
1973
John McCall19c85762010-02-16 03:57:14 +00001974 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001975 assert(!Record->getPreviousDeclaration() &&
1976 "struct/union has previous declaration");
1977 assert(!NeedsInjectedClassNameType(Record));
1978 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00001979 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00001980 assert(!Enum->getPreviousDeclaration() &&
1981 "enum has previous declaration");
1982 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00001983 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00001984 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1985 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
Mike Stump9fdbab32009-07-31 02:02:20 +00001986 } else
John McCallbecb8d52010-03-10 06:48:02 +00001987 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001988
John McCallbecb8d52010-03-10 06:48:02 +00001989 Types.push_back(Decl->TypeForDecl);
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00001990 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001991}
1992
Reid Spencer5f016e22007-07-11 17:01:13 +00001993/// getTypedefType - Return the unique reference to the type for the
1994/// specified typename decl.
John McCall19c85762010-02-16 03:57:14 +00001995QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001996 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Chris Lattnerf52ab252008-04-06 22:59:24 +00001998 QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall6b304a02009-09-24 23:30:46 +00001999 Decl->TypeForDecl = new(*this, TypeAlignment)
2000 TypedefType(Type::Typedef, Decl, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00002001 Types.push_back(Decl->TypeForDecl);
2002 return QualType(Decl->TypeForDecl, 0);
2003}
2004
John McCall49a832b2009-10-18 09:09:24 +00002005/// \brief Retrieve a substitution-result type.
2006QualType
2007ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
2008 QualType Replacement) {
John McCall467b27b2009-10-22 20:10:53 +00002009 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002010 && "replacement types must always be canonical");
2011
2012 llvm::FoldingSetNodeID ID;
2013 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2014 void *InsertPos = 0;
2015 SubstTemplateTypeParmType *SubstParm
2016 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2017
2018 if (!SubstParm) {
2019 SubstParm = new (*this, TypeAlignment)
2020 SubstTemplateTypeParmType(Parm, Replacement);
2021 Types.push_back(SubstParm);
2022 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2023 }
2024
2025 return QualType(SubstParm, 0);
2026}
2027
Douglas Gregorfab9d672009-02-05 23:33:38 +00002028/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002029/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002030/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002031QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002032 bool ParameterPack,
Douglas Gregorfab9d672009-02-05 23:33:38 +00002033 IdentifierInfo *Name) {
2034 llvm::FoldingSetNodeID ID;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002035 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002036 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002037 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002038 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2039
2040 if (TypeParm)
2041 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002043 if (Name) {
2044 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
John McCall6b304a02009-09-24 23:30:46 +00002045 TypeParm = new (*this, TypeAlignment)
2046 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002047
2048 TemplateTypeParmType *TypeCheck
2049 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2050 assert(!TypeCheck && "Template type parameter canonical type broken");
2051 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002052 } else
John McCall6b304a02009-09-24 23:30:46 +00002053 TypeParm = new (*this, TypeAlignment)
2054 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002055
2056 Types.push_back(TypeParm);
2057 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2058
2059 return QualType(TypeParm, 0);
2060}
2061
John McCall3cb0ebd2010-03-10 03:28:59 +00002062TypeSourceInfo *
2063ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2064 SourceLocation NameLoc,
2065 const TemplateArgumentListInfo &Args,
2066 QualType CanonType) {
2067 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2068
2069 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2070 TemplateSpecializationTypeLoc TL
2071 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2072 TL.setTemplateNameLoc(NameLoc);
2073 TL.setLAngleLoc(Args.getLAngleLoc());
2074 TL.setRAngleLoc(Args.getRAngleLoc());
2075 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2076 TL.setArgLocInfo(i, Args[i].getLocInfo());
2077 return DI;
2078}
2079
Mike Stump1eb44332009-09-09 15:08:12 +00002080QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002081ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002082 const TemplateArgumentListInfo &Args,
John McCall833ca992009-10-29 08:12:44 +00002083 QualType Canon) {
John McCalld5532b62009-11-23 01:53:49 +00002084 unsigned NumArgs = Args.size();
2085
John McCall833ca992009-10-29 08:12:44 +00002086 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2087 ArgVec.reserve(NumArgs);
2088 for (unsigned i = 0; i != NumArgs; ++i)
2089 ArgVec.push_back(Args[i].getArgument());
2090
2091 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, Canon);
2092}
2093
2094QualType
2095ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002096 const TemplateArgument *Args,
2097 unsigned NumArgs,
2098 QualType Canon) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00002099 if (!Canon.isNull())
2100 Canon = getCanonicalType(Canon);
2101 else {
2102 // Build the canonical template specialization type.
Douglas Gregor1275ae02009-07-28 23:00:59 +00002103 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2104 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2105 CanonArgs.reserve(NumArgs);
2106 for (unsigned I = 0; I != NumArgs; ++I)
2107 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2108
2109 // Determine whether this canonical template specialization type already
2110 // exists.
2111 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002112 TemplateSpecializationType::Profile(ID, CanonTemplate,
Douglas Gregor828e2262009-07-29 16:09:57 +00002113 CanonArgs.data(), NumArgs, *this);
Douglas Gregor1275ae02009-07-28 23:00:59 +00002114
2115 void *InsertPos = 0;
2116 TemplateSpecializationType *Spec
2117 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Douglas Gregor1275ae02009-07-28 23:00:59 +00002119 if (!Spec) {
2120 // Allocate a new canonical template specialization type.
Mike Stump1eb44332009-09-09 15:08:12 +00002121 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor1275ae02009-07-28 23:00:59 +00002122 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00002123 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002124 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate,
Douglas Gregor1275ae02009-07-28 23:00:59 +00002125 CanonArgs.data(), NumArgs,
Douglas Gregorb88e8882009-07-30 17:40:51 +00002126 Canon);
Douglas Gregor1275ae02009-07-28 23:00:59 +00002127 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002128 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
Douglas Gregor1275ae02009-07-28 23:00:59 +00002129 }
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Douglas Gregorb88e8882009-07-30 17:40:51 +00002131 if (Canon.isNull())
2132 Canon = QualType(Spec, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002133 assert(Canon->isDependentType() &&
Douglas Gregor1275ae02009-07-28 23:00:59 +00002134 "Non-dependent template-id type must have a canonical type");
Douglas Gregorb88e8882009-07-30 17:40:51 +00002135 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002136
Douglas Gregor1275ae02009-07-28 23:00:59 +00002137 // Allocate the (non-canonical) template specialization type, but don't
2138 // try to unique it: these types typically have location information that
2139 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00002140 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00002141 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00002142 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002143 TemplateSpecializationType *Spec
2144 = new (Mem) TemplateSpecializationType(*this, Template, Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00002145 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Douglas Gregor55f6b142009-02-09 18:46:07 +00002147 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002148 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002149}
2150
Mike Stump1eb44332009-09-09 15:08:12 +00002151QualType
Douglas Gregorab452ba2009-03-26 23:50:42 +00002152ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
Douglas Gregore4e5b052009-03-19 00:18:19 +00002153 QualType NamedType) {
2154 llvm::FoldingSetNodeID ID;
Douglas Gregorab452ba2009-03-26 23:50:42 +00002155 QualifiedNameType::Profile(ID, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002156
2157 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002158 QualifiedNameType *T
Douglas Gregore4e5b052009-03-19 00:18:19 +00002159 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2160 if (T)
2161 return QualType(T, 0);
2162
Douglas Gregor789b1f62010-02-04 18:10:26 +00002163 QualType Canon = NamedType;
2164 if (!Canon.isCanonical()) {
2165 Canon = getCanonicalType(NamedType);
2166 QualifiedNameType *CheckT
2167 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2168 assert(!CheckT && "Qualified name canonical type broken");
2169 (void)CheckT;
2170 }
2171
2172 T = new (*this) QualifiedNameType(NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002173 Types.push_back(T);
2174 QualifiedNameTypes.InsertNode(T, InsertPos);
2175 return QualType(T, 0);
2176}
2177
Mike Stump1eb44332009-09-09 15:08:12 +00002178QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregord57959a2009-03-27 23:10:48 +00002179 const IdentifierInfo *Name,
2180 QualType Canon) {
2181 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2182
2183 if (Canon.isNull()) {
2184 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2185 if (CanonNNS != NNS)
2186 Canon = getTypenameType(CanonNNS, Name);
2187 }
2188
2189 llvm::FoldingSetNodeID ID;
2190 TypenameType::Profile(ID, NNS, Name);
2191
2192 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002193 TypenameType *T
Douglas Gregord57959a2009-03-27 23:10:48 +00002194 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2195 if (T)
2196 return QualType(T, 0);
2197
2198 T = new (*this) TypenameType(NNS, Name, Canon);
2199 Types.push_back(T);
2200 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002201 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002202}
2203
Mike Stump1eb44332009-09-09 15:08:12 +00002204QualType
2205ASTContext::getTypenameType(NestedNameSpecifier *NNS,
Douglas Gregor17343172009-04-01 00:28:59 +00002206 const TemplateSpecializationType *TemplateId,
2207 QualType Canon) {
2208 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2209
Douglas Gregor789b1f62010-02-04 18:10:26 +00002210 llvm::FoldingSetNodeID ID;
2211 TypenameType::Profile(ID, NNS, TemplateId);
2212
2213 void *InsertPos = 0;
2214 TypenameType *T
2215 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2216 if (T)
2217 return QualType(T, 0);
2218
Douglas Gregor17343172009-04-01 00:28:59 +00002219 if (Canon.isNull()) {
2220 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2221 QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
2222 if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
2223 const TemplateSpecializationType *CanonTemplateId
John McCall183700f2009-09-21 23:43:11 +00002224 = CanonType->getAs<TemplateSpecializationType>();
Douglas Gregor17343172009-04-01 00:28:59 +00002225 assert(CanonTemplateId &&
2226 "Canonical type must also be a template specialization type");
2227 Canon = getTypenameType(CanonNNS, CanonTemplateId);
2228 }
Douglas Gregor789b1f62010-02-04 18:10:26 +00002229
2230 TypenameType *CheckT
2231 = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
2232 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT;
Douglas Gregor17343172009-04-01 00:28:59 +00002233 }
2234
Douglas Gregor17343172009-04-01 00:28:59 +00002235 T = new (*this) TypenameType(NNS, TemplateId, Canon);
2236 Types.push_back(T);
2237 TypenameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002238 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002239}
2240
John McCall7da24312009-09-05 00:15:47 +00002241QualType
2242ASTContext::getElaboratedType(QualType UnderlyingType,
2243 ElaboratedType::TagKind Tag) {
2244 llvm::FoldingSetNodeID ID;
2245 ElaboratedType::Profile(ID, UnderlyingType, Tag);
Mike Stump1eb44332009-09-09 15:08:12 +00002246
John McCall7da24312009-09-05 00:15:47 +00002247 void *InsertPos = 0;
2248 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2249 if (T)
2250 return QualType(T, 0);
2251
Douglas Gregor789b1f62010-02-04 18:10:26 +00002252 QualType Canon = UnderlyingType;
2253 if (!Canon.isCanonical()) {
2254 Canon = getCanonicalType(Canon);
2255 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2256 assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT;
2257 }
John McCall7da24312009-09-05 00:15:47 +00002258
2259 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon);
2260 Types.push_back(T);
2261 ElaboratedTypes.InsertNode(T, InsertPos);
2262 return QualType(T, 0);
2263}
2264
Chris Lattner88cb27a2008-04-07 04:56:42 +00002265/// CmpProtocolNames - Comparison predicate for sorting protocols
2266/// alphabetically.
2267static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2268 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002269 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002270}
2271
John McCall54e14c42009-10-22 22:37:11 +00002272static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols,
2273 unsigned NumProtocols) {
2274 if (NumProtocols == 0) return true;
2275
2276 for (unsigned i = 1; i != NumProtocols; ++i)
2277 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2278 return false;
2279 return true;
2280}
2281
2282static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002283 unsigned &NumProtocols) {
2284 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002285
Chris Lattner88cb27a2008-04-07 04:56:42 +00002286 // Sort protocols, keyed by name.
2287 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2288
2289 // Remove duplicates.
2290 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2291 NumProtocols = ProtocolsEnd-Protocols;
2292}
2293
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002294/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2295/// the given interface decl and the conforming protocol list.
Steve Naroff14108da2009-07-10 23:34:53 +00002296QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT,
Mike Stump1eb44332009-09-09 15:08:12 +00002297 ObjCProtocolDecl **Protocols,
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002298 unsigned NumProtocols,
2299 unsigned Quals) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002300 llvm::FoldingSetNodeID ID;
Steve Naroff14108da2009-07-10 23:34:53 +00002301 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols);
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002302 Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002303
2304 void *InsertPos = 0;
2305 if (ObjCObjectPointerType *QT =
2306 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002307 return getQualifiedType(QualType(QT, 0), Qs);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002308
John McCall54e14c42009-10-22 22:37:11 +00002309 // Sort the protocol list alphabetically to canonicalize it.
2310 QualType Canonical;
2311 if (!InterfaceT.isCanonical() ||
2312 !areSortedAndUniqued(Protocols, NumProtocols)) {
2313 if (!areSortedAndUniqued(Protocols, NumProtocols)) {
2314 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2315 unsigned UniqueCount = NumProtocols;
2316
2317 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2318 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2319
2320 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2321 &Sorted[0], UniqueCount);
2322 } else {
2323 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT),
2324 Protocols, NumProtocols);
2325 }
2326
2327 // Regenerate InsertPos.
2328 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2329 }
2330
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002331 // No match.
2332 unsigned Size = sizeof(ObjCObjectPointerType)
2333 + NumProtocols * sizeof(ObjCProtocolDecl *);
2334 void *Mem = Allocate(Size, TypeAlignment);
2335 ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical,
2336 InterfaceT,
2337 Protocols,
2338 NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002339
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002340 Types.push_back(QType);
2341 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
Fariborz Jahaniana4228642010-03-05 22:42:55 +00002342 return getQualifiedType(QualType(QType, 0), Qs);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002343}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002344
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002345/// getObjCInterfaceType - Return the unique reference to the type for the
2346/// specified ObjC interface decl. The list of protocols is optional.
2347QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002348 ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002349 llvm::FoldingSetNodeID ID;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002350 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
Mike Stump1eb44332009-09-09 15:08:12 +00002351
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002352 void *InsertPos = 0;
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002353 if (ObjCInterfaceType *QT =
2354 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002355 return QualType(QT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002356
John McCall54e14c42009-10-22 22:37:11 +00002357 // Sort the protocol list alphabetically to canonicalize it.
2358 QualType Canonical;
2359 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) {
2360 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(NumProtocols);
2361 std::copy(Protocols, Protocols + NumProtocols, Sorted.begin());
2362
2363 unsigned UniqueCount = NumProtocols;
2364 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2365
2366 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount);
2367
2368 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos);
2369 }
2370
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002371 unsigned Size = sizeof(ObjCInterfaceType)
2372 + NumProtocols * sizeof(ObjCProtocolDecl *);
2373 void *Mem = Allocate(Size, TypeAlignment);
2374 ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical,
2375 const_cast<ObjCInterfaceDecl*>(Decl),
2376 Protocols,
2377 NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002378
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002379 Types.push_back(QType);
Steve Naroffc15cb2a2009-07-18 15:33:26 +00002380 ObjCInterfaceTypes.InsertNode(QType, InsertPos);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002381 return QualType(QType, 0);
2382}
2383
Douglas Gregor72564e72009-02-26 23:50:07 +00002384/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2385/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002386/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002387/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002388/// on canonical type's (which are always unique).
Douglas Gregor72564e72009-02-26 23:50:07 +00002389QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002390 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002391 if (tofExpr->isTypeDependent()) {
2392 llvm::FoldingSetNodeID ID;
2393 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002394
Douglas Gregorb1975722009-07-30 23:18:24 +00002395 void *InsertPos = 0;
2396 DependentTypeOfExprType *Canon
2397 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2398 if (Canon) {
2399 // We already have a "canonical" version of an identical, dependent
2400 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002401 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002402 QualType((TypeOfExprType*)Canon, 0));
2403 }
2404 else {
2405 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002406 Canon
2407 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002408 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2409 toe = Canon;
2410 }
2411 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002412 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002413 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002414 }
Steve Naroff9752f252007-08-01 18:02:17 +00002415 Types.push_back(toe);
2416 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002417}
2418
Steve Naroff9752f252007-08-01 18:02:17 +00002419/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2420/// TypeOfType AST's. The only motivation to unique these nodes would be
2421/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002422/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002423/// on canonical type's (which are always unique).
Steve Naroffd1861fd2007-07-31 12:34:36 +00002424QualType ASTContext::getTypeOfType(QualType tofType) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002425 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002426 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002427 Types.push_back(tot);
2428 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002429}
2430
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002431/// getDecltypeForExpr - Given an expr, will return the decltype for that
2432/// expression, according to the rules in C++0x [dcl.type.simple]p4
2433static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002434 if (e->isTypeDependent())
2435 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002436
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002437 // If e is an id expression or a class member access, decltype(e) is defined
2438 // as the type of the entity named by e.
2439 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2440 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2441 return VD->getType();
2442 }
2443 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2444 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2445 return FD->getType();
2446 }
2447 // If e is a function call or an invocation of an overloaded operator,
2448 // (parentheses around e are ignored), decltype(e) is defined as the
2449 // return type of that function.
2450 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2451 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002452
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002453 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002454
2455 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002456 // defined as T&, otherwise decltype(e) is defined as T.
2457 if (e->isLvalue(Context) == Expr::LV_Valid)
2458 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002459
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002460 return T;
2461}
2462
Anders Carlsson395b4752009-06-24 19:06:50 +00002463/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2464/// DecltypeType AST's. The only motivation to unique these nodes would be
2465/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002466/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002467/// on canonical type's (which are always unique).
2468QualType ASTContext::getDecltypeType(Expr *e) {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002469 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002470 if (e->isTypeDependent()) {
2471 llvm::FoldingSetNodeID ID;
2472 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002473
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002474 void *InsertPos = 0;
2475 DependentDecltypeType *Canon
2476 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2477 if (Canon) {
2478 // We already have a "canonical" version of an equivalent, dependent
2479 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002480 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002481 QualType((DecltypeType*)Canon, 0));
2482 }
2483 else {
2484 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002485 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002486 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2487 dt = Canon;
2488 }
2489 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002490 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002491 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002492 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002493 Types.push_back(dt);
2494 return QualType(dt, 0);
2495}
2496
Reid Spencer5f016e22007-07-11 17:01:13 +00002497/// getTagDeclType - Return the unique reference to the type for the
2498/// specified TagDecl (struct/union/class/enum) decl.
Mike Stumpe607ed02009-08-07 18:05:12 +00002499QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
Ted Kremenekd778f882007-11-26 21:16:01 +00002500 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002501 // FIXME: What is the design on getTagDeclType when it requires casting
2502 // away const? mutable?
2503 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002504}
2505
Mike Stump1eb44332009-09-09 15:08:12 +00002506/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2507/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2508/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002509CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002510 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002511}
2512
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002513/// getSignedWCharType - Return the type of "signed wchar_t".
2514/// Used when in C++, as a GCC extension.
2515QualType ASTContext::getSignedWCharType() const {
2516 // FIXME: derive from "Target" ?
2517 return WCharTy;
2518}
2519
2520/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2521/// Used when in C++, as a GCC extension.
2522QualType ASTContext::getUnsignedWCharType() const {
2523 // FIXME: derive from "Target" ?
2524 return UnsignedIntTy;
2525}
2526
Chris Lattner8b9023b2007-07-13 03:05:23 +00002527/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2528/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2529QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002530 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002531}
2532
Chris Lattnere6327742008-04-02 05:18:44 +00002533//===----------------------------------------------------------------------===//
2534// Type Operators
2535//===----------------------------------------------------------------------===//
2536
John McCall54e14c42009-10-22 22:37:11 +00002537CanQualType ASTContext::getCanonicalParamType(QualType T) {
2538 // Push qualifiers into arrays, and then discard any remaining
2539 // qualifiers.
2540 T = getCanonicalType(T);
2541 const Type *Ty = T.getTypePtr();
2542
2543 QualType Result;
2544 if (isa<ArrayType>(Ty)) {
2545 Result = getArrayDecayedType(QualType(Ty,0));
2546 } else if (isa<FunctionType>(Ty)) {
2547 Result = getPointerType(QualType(Ty, 0));
2548 } else {
2549 Result = QualType(Ty, 0);
2550 }
2551
2552 return CanQualType::CreateUnsafe(Result);
2553}
2554
Chris Lattner77c96472008-04-06 22:41:35 +00002555/// getCanonicalType - Return the canonical (structural) type corresponding to
2556/// the specified potentially non-canonical type. The non-canonical version
2557/// of a type may have many "decorated" versions of types. Decorators can
2558/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2559/// to be free of any of these, allowing two canonical types to be compared
2560/// for exact equality with a simple pointer comparison.
Douglas Gregor50d62d12009-08-05 05:36:45 +00002561CanQualType ASTContext::getCanonicalType(QualType T) {
John McCall0953e762009-09-24 19:53:00 +00002562 QualifierCollector Quals;
2563 const Type *Ptr = Quals.strip(T);
2564 QualType CanType = Ptr->getCanonicalTypeInternal();
Mike Stump1eb44332009-09-09 15:08:12 +00002565
John McCall0953e762009-09-24 19:53:00 +00002566 // The canonical internal type will be the canonical type *except*
2567 // that we push type qualifiers down through array types.
2568
2569 // If there are no new qualifiers to push down, stop here.
2570 if (!Quals.hasQualifiers())
Douglas Gregor50d62d12009-08-05 05:36:45 +00002571 return CanQualType::CreateUnsafe(CanType);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002572
John McCall0953e762009-09-24 19:53:00 +00002573 // If the type qualifiers are on an array type, get the canonical
2574 // type of the array with the qualifiers applied to the element
2575 // type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002576 ArrayType *AT = dyn_cast<ArrayType>(CanType);
2577 if (!AT)
John McCall0953e762009-09-24 19:53:00 +00002578 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
Mike Stump1eb44332009-09-09 15:08:12 +00002579
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002580 // Get the canonical version of the element with the extra qualifiers on it.
2581 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002582 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002583 NewEltTy = getCanonicalType(NewEltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002584
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002585 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002586 return CanQualType::CreateUnsafe(
2587 getConstantArrayType(NewEltTy, CAT->getSize(),
2588 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002589 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002590 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002591 return CanQualType::CreateUnsafe(
2592 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002593 IAT->getIndexTypeCVRQualifiers()));
Mike Stump1eb44332009-09-09 15:08:12 +00002594
Douglas Gregor898574e2008-12-05 23:32:09 +00002595 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
Douglas Gregor50d62d12009-08-05 05:36:45 +00002596 return CanQualType::CreateUnsafe(
2597 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002598 DSAT->getSizeExpr() ?
2599 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002600 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002601 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor87a924e2009-10-30 22:56:57 +00002602 DSAT->getBracketsRange())->getCanonicalTypeInternal());
Douglas Gregor898574e2008-12-05 23:32:09 +00002603
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002604 VariableArrayType *VAT = cast<VariableArrayType>(AT);
Douglas Gregor50d62d12009-08-05 05:36:45 +00002605 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002606 VAT->getSizeExpr() ?
2607 VAT->getSizeExpr()->Retain() : 0,
Douglas Gregor50d62d12009-08-05 05:36:45 +00002608 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002609 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor50d62d12009-08-05 05:36:45 +00002610 VAT->getBracketsRange()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002611}
2612
Chandler Carruth28e318c2009-12-29 07:16:59 +00002613QualType ASTContext::getUnqualifiedArrayType(QualType T,
2614 Qualifiers &Quals) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002615 Quals = T.getQualifiers();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002616 if (!isa<ArrayType>(T)) {
Chandler Carruth5535c382010-01-12 20:32:25 +00002617 return T.getUnqualifiedType();
Chandler Carruth28e318c2009-12-29 07:16:59 +00002618 }
2619
Chandler Carruth28e318c2009-12-29 07:16:59 +00002620 const ArrayType *AT = cast<ArrayType>(T);
2621 QualType Elt = AT->getElementType();
Zhongxing Xuc1ae0a82010-01-05 08:15:06 +00002622 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002623 if (Elt == UnqualElt)
2624 return T;
2625
2626 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) {
2627 return getConstantArrayType(UnqualElt, CAT->getSize(),
2628 CAT->getSizeModifier(), 0);
2629 }
2630
2631 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) {
2632 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2633 }
2634
2635 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T);
2636 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2637 DSAT->getSizeModifier(), 0,
2638 SourceRange());
2639}
2640
John McCall80ad16f2009-11-24 18:42:40 +00002641DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2642 if (TemplateDecl *TD = Name.getAsTemplateDecl())
2643 return TD->getDeclName();
2644
2645 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2646 if (DTN->isIdentifier()) {
2647 return DeclarationNames.getIdentifier(DTN->getIdentifier());
2648 } else {
2649 return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2650 }
2651 }
2652
John McCall0bd6feb2009-12-02 08:04:21 +00002653 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2654 assert(Storage);
2655 return (*Storage->begin())->getDeclName();
John McCall80ad16f2009-11-24 18:42:40 +00002656}
2657
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002658TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2659 // If this template name refers to a template, the canonical
2660 // template name merely stores the template itself.
2661 if (TemplateDecl *Template = Name.getAsTemplateDecl())
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002662 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002663
John McCall0bd6feb2009-12-02 08:04:21 +00002664 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002665
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002666 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2667 assert(DTN && "Non-dependent template names must refer to template decls.");
2668 return DTN->CanonicalTemplateName;
2669}
2670
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002671bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2672 X = getCanonicalTemplateName(X);
2673 Y = getCanonicalTemplateName(Y);
2674 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2675}
2676
Mike Stump1eb44332009-09-09 15:08:12 +00002677TemplateArgument
Douglas Gregor1275ae02009-07-28 23:00:59 +00002678ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2679 switch (Arg.getKind()) {
2680 case TemplateArgument::Null:
2681 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002682
Douglas Gregor1275ae02009-07-28 23:00:59 +00002683 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002684 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002685
Douglas Gregor1275ae02009-07-28 23:00:59 +00002686 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002687 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002688
Douglas Gregor788cd062009-11-11 01:00:40 +00002689 case TemplateArgument::Template:
2690 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2691
Douglas Gregor1275ae02009-07-28 23:00:59 +00002692 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002693 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002694 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Douglas Gregor1275ae02009-07-28 23:00:59 +00002696 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002697 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002698
Douglas Gregor1275ae02009-07-28 23:00:59 +00002699 case TemplateArgument::Pack: {
2700 // FIXME: Allocate in ASTContext
2701 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2702 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002703 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002704 AEnd = Arg.pack_end();
2705 A != AEnd; (void)++A, ++Idx)
2706 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00002707
Douglas Gregor1275ae02009-07-28 23:00:59 +00002708 TemplateArgument Result;
2709 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2710 return Result;
2711 }
2712 }
2713
2714 // Silence GCC warning
2715 assert(false && "Unhandled template argument kind");
2716 return TemplateArgument();
2717}
2718
Douglas Gregord57959a2009-03-27 23:10:48 +00002719NestedNameSpecifier *
2720ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002721 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00002722 return 0;
2723
2724 switch (NNS->getKind()) {
2725 case NestedNameSpecifier::Identifier:
2726 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00002727 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00002728 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2729 NNS->getAsIdentifier());
2730
2731 case NestedNameSpecifier::Namespace:
2732 // A namespace is canonical; build a nested-name-specifier with
2733 // this namespace and no prefix.
2734 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2735
2736 case NestedNameSpecifier::TypeSpec:
2737 case NestedNameSpecifier::TypeSpecWithTemplate: {
2738 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Mike Stump1eb44332009-09-09 15:08:12 +00002739 return NestedNameSpecifier::Create(*this, 0,
2740 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
Douglas Gregord57959a2009-03-27 23:10:48 +00002741 T.getTypePtr());
2742 }
2743
2744 case NestedNameSpecifier::Global:
2745 // The global specifier is canonical and unique.
2746 return NNS;
2747 }
2748
2749 // Required to silence a GCC warning
2750 return 0;
2751}
2752
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002753
2754const ArrayType *ASTContext::getAsArrayType(QualType T) {
2755 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002756 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002757 // Handle the common positive case fast.
2758 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2759 return AT;
2760 }
Mike Stump1eb44332009-09-09 15:08:12 +00002761
John McCall0953e762009-09-24 19:53:00 +00002762 // Handle the common negative case fast.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002763 QualType CType = T->getCanonicalTypeInternal();
John McCall0953e762009-09-24 19:53:00 +00002764 if (!isa<ArrayType>(CType))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002765 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002766
John McCall0953e762009-09-24 19:53:00 +00002767 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002768 // implements C99 6.7.3p8: "If the specification of an array type includes
2769 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00002770
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002771 // If we get here, we either have type qualifiers on the type, or we have
2772 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00002773 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00002774
John McCall0953e762009-09-24 19:53:00 +00002775 QualifierCollector Qs;
2776 const Type *Ty = Qs.strip(T.getDesugaredType());
Mike Stump1eb44332009-09-09 15:08:12 +00002777
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002778 // If we have a simple case, just return now.
2779 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
John McCall0953e762009-09-24 19:53:00 +00002780 if (ATy == 0 || Qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002781 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002783 // Otherwise, we have an array and we have qualifiers on it. Push the
2784 // qualifiers into the array element type and return a new array type.
2785 // Get the canonical version of the element with the extra qualifiers on it.
2786 // This can recursively sink qualifiers through multiple levels of arrays.
John McCall0953e762009-09-24 19:53:00 +00002787 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
Mike Stump1eb44332009-09-09 15:08:12 +00002788
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002789 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2790 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2791 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002792 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002793 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2794 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2795 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002796 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00002797
Mike Stump1eb44332009-09-09 15:08:12 +00002798 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00002799 = dyn_cast<DependentSizedArrayType>(ATy))
2800 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00002801 getDependentSizedArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002802 DSAT->getSizeExpr() ?
2803 DSAT->getSizeExpr()->Retain() : 0,
Douglas Gregor898574e2008-12-05 23:32:09 +00002804 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002805 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002806 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00002807
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002808 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002809 return cast<ArrayType>(getVariableArrayType(NewEltTy,
Eli Friedmanbbed6b92009-08-15 02:50:32 +00002810 VAT->getSizeExpr() ?
John McCall0953e762009-09-24 19:53:00 +00002811 VAT->getSizeExpr()->Retain() : 0,
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002812 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00002813 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00002814 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00002815}
2816
2817
Chris Lattnere6327742008-04-02 05:18:44 +00002818/// getArrayDecayedType - Return the properly qualified result of decaying the
2819/// specified array type to a pointer. This operation is non-trivial when
2820/// handling typedefs etc. The canonical type of "T" must be an array type,
2821/// this returns a pointer to a properly qualified element of the array.
2822///
2823/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2824QualType ASTContext::getArrayDecayedType(QualType Ty) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002825 // Get the element type with 'getAsArrayType' so that we don't lose any
2826 // typedefs in the element type of the array. This also handles propagation
2827 // of type qualifiers from the array type into the element type if present
2828 // (C99 6.7.3p8).
2829 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2830 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00002831
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002832 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00002833
2834 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00002835 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00002836}
2837
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002838QualType ASTContext::getBaseElementType(QualType QT) {
John McCall0953e762009-09-24 19:53:00 +00002839 QualifierCollector Qs;
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002840 while (true) {
John McCall0953e762009-09-24 19:53:00 +00002841 const Type *UT = Qs.strip(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002842 if (const ArrayType *AT = getAsArrayType(QualType(UT,0))) {
2843 QT = AT->getElementType();
Mike Stump6dcbc292009-07-25 23:24:03 +00002844 } else {
John McCall0953e762009-09-24 19:53:00 +00002845 return Qs.apply(QT);
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00002846 }
2847 }
2848}
2849
Anders Carlssonfbbce492009-09-25 01:23:32 +00002850QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2851 QualType ElemTy = AT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002852
Anders Carlssonfbbce492009-09-25 01:23:32 +00002853 if (const ArrayType *AT = getAsArrayType(ElemTy))
2854 return getBaseElementType(AT);
Mike Stump1eb44332009-09-09 15:08:12 +00002855
Anders Carlsson6183a992008-12-21 03:44:36 +00002856 return ElemTy;
2857}
2858
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002859/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00002860uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00002861ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
2862 uint64_t ElementCount = 1;
2863 do {
2864 ElementCount *= CA->getSize().getZExtValue();
2865 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2866 } while (CA);
2867 return ElementCount;
2868}
2869
Reid Spencer5f016e22007-07-11 17:01:13 +00002870/// getFloatingRank - Return a relative rank for floating point types.
2871/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00002872static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00002873 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00002874 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00002875
John McCall183700f2009-09-21 23:43:11 +00002876 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2877 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00002878 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002879 case BuiltinType::Float: return FloatRank;
2880 case BuiltinType::Double: return DoubleRank;
2881 case BuiltinType::LongDouble: return LongDoubleRank;
2882 }
2883}
2884
Mike Stump1eb44332009-09-09 15:08:12 +00002885/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2886/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00002887/// 'typeDomain' is a real floating point or complex type.
2888/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00002889QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2890 QualType Domain) const {
2891 FloatingRank EltRank = getFloatingRank(Size);
2892 if (Domain->isComplexType()) {
2893 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00002894 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00002895 case FloatRank: return FloatComplexTy;
2896 case DoubleRank: return DoubleComplexTy;
2897 case LongDoubleRank: return LongDoubleComplexTy;
2898 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002899 }
Chris Lattner1361b112008-04-06 23:58:54 +00002900
2901 assert(Domain->isRealFloatingType() && "Unknown domain!");
2902 switch (EltRank) {
2903 default: assert(0 && "getFloatingRank(): illegal value for rank");
2904 case FloatRank: return FloatTy;
2905 case DoubleRank: return DoubleTy;
2906 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00002907 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002908}
2909
Chris Lattner7cfeb082008-04-06 23:55:33 +00002910/// getFloatingTypeOrder - Compare the rank of the two specified floating
2911/// point types, ignoring the domain of the type (i.e. 'double' ==
2912/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00002913/// LHS < RHS, return -1.
Chris Lattnera75cea32008-04-06 23:38:49 +00002914int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2915 FloatingRank LHSR = getFloatingRank(LHS);
2916 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00002917
Chris Lattnera75cea32008-04-06 23:38:49 +00002918 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002919 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00002920 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00002921 return 1;
2922 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00002923}
2924
Chris Lattnerf52ab252008-04-06 22:59:24 +00002925/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2926/// routine will assert if passed a built-in type that isn't an integer or enum,
2927/// or if it is not canonicalized.
Eli Friedmanf98aba32009-02-13 02:31:07 +00002928unsigned ASTContext::getIntegerRank(Type *T) {
John McCall467b27b2009-10-22 20:10:53 +00002929 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Eli Friedmanf98aba32009-02-13 02:31:07 +00002930 if (EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00002931 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00002932
Eli Friedmana3426752009-07-05 23:44:27 +00002933 if (T->isSpecificBuiltinType(BuiltinType::WChar))
2934 T = getFromTargetType(Target.getWCharType()).getTypePtr();
2935
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00002936 if (T->isSpecificBuiltinType(BuiltinType::Char16))
2937 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2938
2939 if (T->isSpecificBuiltinType(BuiltinType::Char32))
2940 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2941
Chris Lattnerf52ab252008-04-06 22:59:24 +00002942 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00002943 default: assert(0 && "getIntegerRank(): not a built-in integer");
2944 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002945 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002946 case BuiltinType::Char_S:
2947 case BuiltinType::Char_U:
2948 case BuiltinType::SChar:
2949 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002950 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002951 case BuiltinType::Short:
2952 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002953 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002954 case BuiltinType::Int:
2955 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002956 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002957 case BuiltinType::Long:
2958 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002959 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00002960 case BuiltinType::LongLong:
2961 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00002962 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00002963 case BuiltinType::Int128:
2964 case BuiltinType::UInt128:
2965 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00002966 }
2967}
2968
Eli Friedman04e83572009-08-20 04:21:42 +00002969/// \brief Whether this is a promotable bitfield reference according
2970/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2971///
2972/// \returns the type this bit-field will promote to, or NULL if no
2973/// promotion occurs.
2974QualType ASTContext::isPromotableBitField(Expr *E) {
2975 FieldDecl *Field = E->getBitField();
2976 if (!Field)
2977 return QualType();
2978
2979 QualType FT = Field->getType();
2980
2981 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2982 uint64_t BitWidth = BitWidthAP.getZExtValue();
2983 uint64_t IntSize = getTypeSize(IntTy);
2984 // GCC extension compatibility: if the bit-field size is less than or equal
2985 // to the size of int, it gets promoted no matter what its type is.
2986 // For instance, unsigned long bf : 4 gets promoted to signed int.
2987 if (BitWidth < IntSize)
2988 return IntTy;
2989
2990 if (BitWidth == IntSize)
2991 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2992
2993 // Types bigger than int are not subject to promotions, and therefore act
2994 // like the base type.
2995 // FIXME: This doesn't quite match what gcc does, but what gcc does here
2996 // is ridiculous.
2997 return QualType();
2998}
2999
Eli Friedmana95d7572009-08-19 07:44:53 +00003000/// getPromotedIntegerType - Returns the type that Promotable will
3001/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3002/// integer type.
3003QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
3004 assert(!Promotable.isNull());
3005 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003006 if (const EnumType *ET = Promotable->getAs<EnumType>())
3007 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003008 if (Promotable->isSignedIntegerType())
3009 return IntTy;
3010 uint64_t PromotableSize = getTypeSize(Promotable);
3011 uint64_t IntSize = getTypeSize(IntTy);
3012 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3013 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3014}
3015
Mike Stump1eb44332009-09-09 15:08:12 +00003016/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003017/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003018/// LHS < RHS, return -1.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003019int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00003020 Type *LHSC = getCanonicalType(LHS).getTypePtr();
3021 Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003022 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003023
Chris Lattnerf52ab252008-04-06 22:59:24 +00003024 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3025 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Chris Lattner7cfeb082008-04-06 23:55:33 +00003027 unsigned LHSRank = getIntegerRank(LHSC);
3028 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003029
Chris Lattner7cfeb082008-04-06 23:55:33 +00003030 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3031 if (LHSRank == RHSRank) return 0;
3032 return LHSRank > RHSRank ? 1 : -1;
3033 }
Mike Stump1eb44332009-09-09 15:08:12 +00003034
Chris Lattner7cfeb082008-04-06 23:55:33 +00003035 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3036 if (LHSUnsigned) {
3037 // If the unsigned [LHS] type is larger, return it.
3038 if (LHSRank >= RHSRank)
3039 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003040
Chris Lattner7cfeb082008-04-06 23:55:33 +00003041 // If the signed type can represent all values of the unsigned type, it
3042 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003043 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003044 return -1;
3045 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003046
Chris Lattner7cfeb082008-04-06 23:55:33 +00003047 // If the unsigned [RHS] type is larger, return it.
3048 if (RHSRank >= LHSRank)
3049 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003050
Chris Lattner7cfeb082008-04-06 23:55:33 +00003051 // If the signed type can represent all values of the unsigned type, it
3052 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003053 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003054 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003055}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003056
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003057static RecordDecl *
3058CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
3059 SourceLocation L, IdentifierInfo *Id) {
3060 if (Ctx.getLangOptions().CPlusPlus)
3061 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
3062 else
3063 return RecordDecl::Create(Ctx, TK, DC, L, Id);
3064}
3065
Mike Stump1eb44332009-09-09 15:08:12 +00003066// getCFConstantStringType - Return the type used for constant CFStrings.
Anders Carlsson71993dd2007-08-17 05:31:46 +00003067QualType ASTContext::getCFConstantStringType() {
3068 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003069 CFConstantStringTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003070 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3071 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003072 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003073
Anders Carlssonf06273f2007-11-19 00:25:30 +00003074 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003075
Anders Carlsson71993dd2007-08-17 05:31:46 +00003076 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003077 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003078 // int flags;
3079 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003080 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003081 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003082 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003083 FieldTypes[3] = LongTy;
3084
Anders Carlsson71993dd2007-08-17 05:31:46 +00003085 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003086 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003087 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00003088 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003089 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003090 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003091 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003092 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003093 }
3094
Douglas Gregor838db382010-02-11 01:19:42 +00003095 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003096 }
Mike Stump1eb44332009-09-09 15:08:12 +00003097
Anders Carlsson71993dd2007-08-17 05:31:46 +00003098 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003099}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003100
Douglas Gregor319ac892009-04-23 22:29:11 +00003101void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003102 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003103 assert(Rec && "Invalid CFConstantStringType");
3104 CFConstantStringTypeDecl = Rec->getDecl();
3105}
3106
Mike Stump1eb44332009-09-09 15:08:12 +00003107QualType ASTContext::getObjCFastEnumerationStateType() {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003108 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003109 ObjCFastEnumerationStateTypeDecl =
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003110 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3111 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003112 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003113
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003114 QualType FieldTypes[] = {
3115 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003116 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003117 getPointerType(UnsignedLongTy),
3118 getConstantArrayType(UnsignedLongTy,
3119 llvm::APInt(32, 5), ArrayType::Normal, 0)
3120 };
Mike Stump1eb44332009-09-09 15:08:12 +00003121
Douglas Gregor44b43212008-12-11 16:49:14 +00003122 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003123 FieldDecl *Field = FieldDecl::Create(*this,
3124 ObjCFastEnumerationStateTypeDecl,
3125 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003126 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003127 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003128 /*Mutable=*/false);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003129 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003130 }
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Douglas Gregor838db382010-02-11 01:19:42 +00003132 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003133 }
Mike Stump1eb44332009-09-09 15:08:12 +00003134
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003135 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3136}
3137
Mike Stumpadaaad32009-10-20 02:12:22 +00003138QualType ASTContext::getBlockDescriptorType() {
3139 if (BlockDescriptorType)
3140 return getTagDeclType(BlockDescriptorType);
3141
3142 RecordDecl *T;
3143 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003144 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3145 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003146 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003147
3148 QualType FieldTypes[] = {
3149 UnsignedLongTy,
3150 UnsignedLongTy,
3151 };
3152
3153 const char *FieldNames[] = {
3154 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003155 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003156 };
3157
3158 for (size_t i = 0; i < 2; ++i) {
3159 FieldDecl *Field = FieldDecl::Create(*this,
3160 T,
3161 SourceLocation(),
3162 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003163 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003164 /*BitWidth=*/0,
3165 /*Mutable=*/false);
3166 T->addDecl(Field);
3167 }
3168
Douglas Gregor838db382010-02-11 01:19:42 +00003169 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003170
3171 BlockDescriptorType = T;
3172
3173 return getTagDeclType(BlockDescriptorType);
3174}
3175
3176void ASTContext::setBlockDescriptorType(QualType T) {
3177 const RecordType *Rec = T->getAs<RecordType>();
3178 assert(Rec && "Invalid BlockDescriptorType");
3179 BlockDescriptorType = Rec->getDecl();
3180}
3181
Mike Stump083c25e2009-10-22 00:49:09 +00003182QualType ASTContext::getBlockDescriptorExtendedType() {
3183 if (BlockDescriptorExtendedType)
3184 return getTagDeclType(BlockDescriptorExtendedType);
3185
3186 RecordDecl *T;
3187 // FIXME: Needs the FlagAppleBlock bit.
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003188 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3189 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003190 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003191
3192 QualType FieldTypes[] = {
3193 UnsignedLongTy,
3194 UnsignedLongTy,
3195 getPointerType(VoidPtrTy),
3196 getPointerType(VoidPtrTy)
3197 };
3198
3199 const char *FieldNames[] = {
3200 "reserved",
3201 "Size",
3202 "CopyFuncPtr",
3203 "DestroyFuncPtr"
3204 };
3205
3206 for (size_t i = 0; i < 4; ++i) {
3207 FieldDecl *Field = FieldDecl::Create(*this,
3208 T,
3209 SourceLocation(),
3210 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003211 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003212 /*BitWidth=*/0,
3213 /*Mutable=*/false);
3214 T->addDecl(Field);
3215 }
3216
Douglas Gregor838db382010-02-11 01:19:42 +00003217 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003218
3219 BlockDescriptorExtendedType = T;
3220
3221 return getTagDeclType(BlockDescriptorExtendedType);
3222}
3223
3224void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3225 const RecordType *Rec = T->getAs<RecordType>();
3226 assert(Rec && "Invalid BlockDescriptorType");
3227 BlockDescriptorExtendedType = Rec->getDecl();
3228}
3229
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003230bool ASTContext::BlockRequiresCopying(QualType Ty) {
3231 if (Ty->isBlockPointerType())
3232 return true;
3233 if (isObjCNSObjectType(Ty))
3234 return true;
3235 if (Ty->isObjCObjectPointerType())
3236 return true;
3237 return false;
3238}
3239
3240QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3241 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003242 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003243 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003244 // unsigned int __flags;
3245 // unsigned int __size;
Mike Stump38e16272009-10-21 22:01:24 +00003246 // void *__copy_helper; // as needed
3247 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003248 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003249 // } *
3250
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003251 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3252
3253 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003254 static unsigned int UniqueBlockByRefTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003255 llvm::SmallString<36> Name;
3256 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3257 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003258 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003259 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3260 &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003261 T->startDefinition();
3262 QualType Int32Ty = IntTy;
3263 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3264 QualType FieldTypes[] = {
3265 getPointerType(VoidPtrTy),
3266 getPointerType(getTagDeclType(T)),
3267 Int32Ty,
3268 Int32Ty,
3269 getPointerType(VoidPtrTy),
3270 getPointerType(VoidPtrTy),
3271 Ty
3272 };
3273
3274 const char *FieldNames[] = {
3275 "__isa",
3276 "__forwarding",
3277 "__flags",
3278 "__size",
3279 "__copy_helper",
3280 "__destroy_helper",
3281 DeclName,
3282 };
3283
3284 for (size_t i = 0; i < 7; ++i) {
3285 if (!HasCopyAndDispose && i >=4 && i <= 5)
3286 continue;
3287 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3288 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003289 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003290 /*BitWidth=*/0, /*Mutable=*/false);
3291 T->addDecl(Field);
3292 }
3293
Douglas Gregor838db382010-02-11 01:19:42 +00003294 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003295
3296 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003297}
3298
3299
3300QualType ASTContext::getBlockParmType(
Mike Stump083c25e2009-10-22 00:49:09 +00003301 bool BlockHasCopyDispose,
Mike Stumpea26cb52009-10-21 03:49:08 +00003302 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
Mike Stumpadaaad32009-10-20 02:12:22 +00003303 // FIXME: Move up
Fariborz Jahanian4d0d85c2009-10-24 00:16:42 +00003304 static unsigned int UniqueBlockParmTypeID = 0;
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003305 llvm::SmallString<36> Name;
3306 llvm::raw_svector_ostream(Name) << "__block_literal_"
3307 << ++UniqueBlockParmTypeID;
Mike Stumpadaaad32009-10-20 02:12:22 +00003308 RecordDecl *T;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003309 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3310 &Idents.get(Name.str()));
John McCall5cfa0112010-02-05 01:33:36 +00003311 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003312 QualType FieldTypes[] = {
3313 getPointerType(VoidPtrTy),
3314 IntTy,
3315 IntTy,
3316 getPointerType(VoidPtrTy),
Mike Stump083c25e2009-10-22 00:49:09 +00003317 (BlockHasCopyDispose ?
3318 getPointerType(getBlockDescriptorExtendedType()) :
3319 getPointerType(getBlockDescriptorType()))
Mike Stumpadaaad32009-10-20 02:12:22 +00003320 };
3321
3322 const char *FieldNames[] = {
3323 "__isa",
3324 "__flags",
3325 "__reserved",
3326 "__FuncPtr",
3327 "__descriptor"
3328 };
3329
3330 for (size_t i = 0; i < 5; ++i) {
Mike Stumpea26cb52009-10-21 03:49:08 +00003331 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003332 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003333 FieldTypes[i], /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003334 /*BitWidth=*/0, /*Mutable=*/false);
3335 T->addDecl(Field);
3336 }
3337
3338 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3339 const Expr *E = BlockDeclRefDecls[i];
3340 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3341 clang::IdentifierInfo *Name = 0;
3342 if (BDRE) {
3343 const ValueDecl *D = BDRE->getDecl();
3344 Name = &Idents.get(D->getName());
3345 }
3346 QualType FieldType = E->getType();
3347
3348 if (BDRE && BDRE->isByRef())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003349 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3350 FieldType);
Mike Stumpea26cb52009-10-21 03:49:08 +00003351
3352 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
John McCalla93c9342009-12-07 02:54:59 +00003353 Name, FieldType, /*TInfo=*/0,
Mike Stumpea26cb52009-10-21 03:49:08 +00003354 /*BitWidth=*/0, /*Mutable=*/false);
Mike Stumpadaaad32009-10-20 02:12:22 +00003355 T->addDecl(Field);
3356 }
3357
Douglas Gregor838db382010-02-11 01:19:42 +00003358 T->completeDefinition();
Mike Stumpea26cb52009-10-21 03:49:08 +00003359
3360 return getPointerType(getTagDeclType(T));
Mike Stumpadaaad32009-10-20 02:12:22 +00003361}
3362
Douglas Gregor319ac892009-04-23 22:29:11 +00003363void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003364 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003365 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3366 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3367}
3368
Anders Carlssone8c49532007-10-29 06:33:42 +00003369// This returns true if a type has been typedefed to BOOL:
3370// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003371static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003372 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003373 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3374 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003375
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003376 return false;
3377}
3378
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003379/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003380/// purpose.
Ken Dyckaa8741a2010-01-11 19:19:56 +00003381CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
Ken Dyck199c3d62010-01-11 17:06:35 +00003382 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003383
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003384 // Make all integer and enum types at least as large as an int
Ken Dyck199c3d62010-01-11 17:06:35 +00003385 if (sz.isPositive() && type->isIntegralType())
3386 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003387 // Treat arrays as pointers, since that's how they're passed in.
3388 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003389 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003390 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003391}
3392
3393static inline
3394std::string charUnitsToString(const CharUnits &CU) {
3395 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003396}
3397
David Chisnall5e530af2009-11-17 19:33:30 +00003398/// getObjCEncodingForBlockDecl - Return the encoded type for this method
3399/// declaration.
3400void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3401 std::string& S) {
3402 const BlockDecl *Decl = Expr->getBlockDecl();
3403 QualType BlockTy =
3404 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3405 // Encode result type.
3406 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3407 // Compute size of all parameters.
3408 // Start with computing size of a pointer in number of bytes.
3409 // FIXME: There might(should) be a better way of doing this computation!
3410 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003411 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3412 CharUnits ParmOffset = PtrSize;
David Chisnall5e530af2009-11-17 19:33:30 +00003413 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3414 E = Decl->param_end(); PI != E; ++PI) {
3415 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003416 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003417 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003418 ParmOffset += sz;
3419 }
3420 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003421 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003422 // Block pointer and offset.
3423 S += "@?0";
3424 ParmOffset = PtrSize;
3425
3426 // Argument types.
3427 ParmOffset = PtrSize;
3428 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3429 Decl->param_end(); PI != E; ++PI) {
3430 ParmVarDecl *PVDecl = *PI;
3431 QualType PType = PVDecl->getOriginalType();
3432 if (const ArrayType *AT =
3433 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3434 // Use array's original type only if it has known number of
3435 // elements.
3436 if (!isa<ConstantArrayType>(AT))
3437 PType = PVDecl->getType();
3438 } else if (PType->isFunctionType())
3439 PType = PVDecl->getType();
3440 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003441 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003442 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003443 }
3444}
3445
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003446/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003447/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003448void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003449 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003450 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003451 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003452 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003453 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003454 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003455 // Compute size of all parameters.
3456 // Start with computing size of a pointer in number of bytes.
3457 // FIXME: There might(should) be a better way of doing this computation!
3458 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003459 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003460 // The first two arguments (self and _cmd) are pointers; account for
3461 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003462 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003463 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3464 E = Decl->param_end(); PI != E; ++PI) {
3465 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003466 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003467 assert (sz.isPositive() &&
3468 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003469 ParmOffset += sz;
3470 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003471 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003472 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003473 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003474
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003475 // Argument types.
3476 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003477 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3478 E = Decl->param_end(); PI != E; ++PI) {
3479 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003480 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003481 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003482 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3483 // Use array's original type only if it has known number of
3484 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003485 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003486 PType = PVDecl->getType();
3487 } else if (PType->isFunctionType())
3488 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003489 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003490 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003491 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003492 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003493 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003494 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003495 }
3496}
3497
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003498/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003499/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003500/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3501/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003502/// Property attributes are stored as a comma-delimited C string. The simple
3503/// attributes readonly and bycopy are encoded as single characters. The
3504/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3505/// encoded as single characters, followed by an identifier. Property types
3506/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003507/// these attributes are defined by the following enumeration:
3508/// @code
3509/// enum PropertyAttributes {
3510/// kPropertyReadOnly = 'R', // property is read-only.
3511/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3512/// kPropertyByref = '&', // property is a reference to the value last assigned
3513/// kPropertyDynamic = 'D', // property is dynamic
3514/// kPropertyGetter = 'G', // followed by getter selector name
3515/// kPropertySetter = 'S', // followed by setter selector name
3516/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3517/// kPropertyType = 't' // followed by old-style type encoding.
3518/// kPropertyWeak = 'W' // 'weak' property
3519/// kPropertyStrong = 'P' // property GC'able
3520/// kPropertyNonAtomic = 'N' // property non-atomic
3521/// };
3522/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003523void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003524 const Decl *Container,
Chris Lattnere6db3b02008-11-19 07:24:05 +00003525 std::string& S) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003526 // Collect information from the property implementation decl(s).
3527 bool Dynamic = false;
3528 ObjCPropertyImplDecl *SynthesizePID = 0;
3529
3530 // FIXME: Duplicated code due to poor abstraction.
3531 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003532 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003533 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3534 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003535 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003536 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003537 ObjCPropertyImplDecl *PID = *i;
3538 if (PID->getPropertyDecl() == PD) {
3539 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3540 Dynamic = true;
3541 } else {
3542 SynthesizePID = PID;
3543 }
3544 }
3545 }
3546 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003547 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003548 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003549 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003550 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003551 ObjCPropertyImplDecl *PID = *i;
3552 if (PID->getPropertyDecl() == PD) {
3553 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3554 Dynamic = true;
3555 } else {
3556 SynthesizePID = PID;
3557 }
3558 }
Mike Stump1eb44332009-09-09 15:08:12 +00003559 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003560 }
3561 }
3562
3563 // FIXME: This is not very efficient.
3564 S = "T";
3565
3566 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003567 // GCC has some special rules regarding encoding of properties which
3568 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003569 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003570 true /* outermost type */,
3571 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003572
3573 if (PD->isReadOnly()) {
3574 S += ",R";
3575 } else {
3576 switch (PD->getSetterKind()) {
3577 case ObjCPropertyDecl::Assign: break;
3578 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003579 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003580 }
3581 }
3582
3583 // It really isn't clear at all what this means, since properties
3584 // are "dynamic by default".
3585 if (Dynamic)
3586 S += ",D";
3587
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003588 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3589 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003590
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003591 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3592 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003593 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003594 }
3595
3596 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3597 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003598 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003599 }
3600
3601 if (SynthesizePID) {
3602 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3603 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003604 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003605 }
3606
3607 // FIXME: OBJCGC: weak & strong
3608}
3609
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003610/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003611/// Another legacy compatibility encoding: 32-bit longs are encoded as
3612/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003613/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3614///
3615void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003616 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003617 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003618 if (BT->getKind() == BuiltinType::ULong &&
3619 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003620 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003621 else
Fariborz Jahanianc657eba2009-02-11 23:59:18 +00003622 if (BT->getKind() == BuiltinType::Long &&
3623 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003624 PointeeTy = IntTy;
3625 }
3626 }
3627}
3628
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003629void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003630 const FieldDecl *Field) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003631 // We follow the behavior of gcc, expanding structures which are
3632 // directly pointed to, and expanding embedded structures. Note that
3633 // these rules are sufficient to prevent recursive encoding of the
3634 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003635 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003636 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003637}
3638
Mike Stump1eb44332009-09-09 15:08:12 +00003639static void EncodeBitField(const ASTContext *Context, std::string& S,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003640 const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003641 const Expr *E = FD->getBitWidth();
3642 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3643 ASTContext *Ctx = const_cast<ASTContext*>(Context);
Eli Friedman9a901bb2009-04-26 19:19:15 +00003644 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003645 S += 'b';
3646 S += llvm::utostr(N);
3647}
3648
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00003649// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003650void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3651 bool ExpandPointedToStructures,
3652 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00003653 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003654 bool OutermostType,
Douglas Gregor6ab35242009-04-09 21:40:53 +00003655 bool EncodingProperty) {
John McCall183700f2009-09-21 23:43:11 +00003656 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003657 if (FD && FD->isBitField())
3658 return EncodeBitField(this, S, FD);
3659 char encoding;
3660 switch (BT->getKind()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003661 default: assert(0 && "Unhandled builtin type kind");
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003662 case BuiltinType::Void: encoding = 'v'; break;
3663 case BuiltinType::Bool: encoding = 'B'; break;
3664 case BuiltinType::Char_U:
3665 case BuiltinType::UChar: encoding = 'C'; break;
3666 case BuiltinType::UShort: encoding = 'S'; break;
3667 case BuiltinType::UInt: encoding = 'I'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003668 case BuiltinType::ULong:
3669 encoding =
3670 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
Fariborz Jahanian72696e12009-02-11 22:31:45 +00003671 break;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003672 case BuiltinType::UInt128: encoding = 'T'; break;
3673 case BuiltinType::ULongLong: encoding = 'Q'; break;
3674 case BuiltinType::Char_S:
3675 case BuiltinType::SChar: encoding = 'c'; break;
3676 case BuiltinType::Short: encoding = 's'; break;
3677 case BuiltinType::Int: encoding = 'i'; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003678 case BuiltinType::Long:
3679 encoding =
3680 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003681 break;
3682 case BuiltinType::LongLong: encoding = 'q'; break;
3683 case BuiltinType::Int128: encoding = 't'; break;
3684 case BuiltinType::Float: encoding = 'f'; break;
3685 case BuiltinType::Double: encoding = 'd'; break;
3686 case BuiltinType::LongDouble: encoding = 'd'; break;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003687 }
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003689 S += encoding;
3690 return;
3691 }
Mike Stump1eb44332009-09-09 15:08:12 +00003692
John McCall183700f2009-09-21 23:43:11 +00003693 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003694 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00003695 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00003696 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003697 return;
3698 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00003699
Ted Kremenek6217b802009-07-29 21:53:49 +00003700 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003701 if (PT->isObjCSelType()) {
3702 S += ':';
3703 return;
3704 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003705 QualType PointeeTy = PT->getPointeeType();
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00003706
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003707 bool isReadOnly = false;
3708 // For historical/compatibility reasons, the read-only qualifier of the
3709 // pointee gets emitted _before_ the '^'. The read-only qualifier of
3710 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00003711 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00003712 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003713 if (OutermostType && T.isConstQualified()) {
3714 isReadOnly = true;
3715 S += 'r';
3716 }
Mike Stump9fdbab32009-07-31 02:02:20 +00003717 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003718 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00003719 while (P->getAs<PointerType>())
3720 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003721 if (P.isConstQualified()) {
3722 isReadOnly = true;
3723 S += 'r';
3724 }
3725 }
3726 if (isReadOnly) {
3727 // Another legacy compatibility encoding. Some ObjC qualifier and type
3728 // combinations need to be rearranged.
3729 // Rewrite "in const" from "nr" to "rn"
3730 const char * s = S.c_str();
3731 int len = S.length();
3732 if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
3733 std::string replace = "rn";
3734 S.replace(S.end()-2, S.end(), replace);
3735 }
3736 }
Mike Stump1eb44332009-09-09 15:08:12 +00003737
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003738 if (PointeeTy->isCharType()) {
3739 // char pointer types should be encoded as '*' unless it is a
3740 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00003741 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003742 S += '*';
3743 return;
3744 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003745 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00003746 // GCC binary compat: Need to convert "struct objc_class *" to "#".
3747 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3748 S += '#';
3749 return;
3750 }
3751 // GCC binary compat: Need to convert "struct objc_object *" to "@".
3752 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3753 S += '@';
3754 return;
3755 }
3756 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003757 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003758 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003759 getLegacyIntegralTypeEncoding(PointeeTy);
3760
Mike Stump1eb44332009-09-09 15:08:12 +00003761 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003762 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003763 return;
3764 }
Mike Stump1eb44332009-09-09 15:08:12 +00003765
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003766 if (const ArrayType *AT =
3767 // Ignore type qualifiers etc.
3768 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00003769 if (isa<IncompleteArrayType>(AT)) {
3770 // Incomplete arrays are encoded as a pointer to the array element.
3771 S += '^';
3772
Mike Stump1eb44332009-09-09 15:08:12 +00003773 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003774 false, ExpandStructures, FD);
3775 } else {
3776 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00003777
Anders Carlsson559a8332009-02-22 01:38:57 +00003778 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3779 S += llvm::utostr(CAT->getSize().getZExtValue());
3780 else {
3781 //Variable length arrays are encoded as a regular array with 0 elements.
3782 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3783 S += '0';
3784 }
Mike Stump1eb44332009-09-09 15:08:12 +00003785
3786 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00003787 false, ExpandStructures, FD);
3788 S += ']';
3789 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003790 return;
3791 }
Mike Stump1eb44332009-09-09 15:08:12 +00003792
John McCall183700f2009-09-21 23:43:11 +00003793 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00003794 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003795 return;
3796 }
Mike Stump1eb44332009-09-09 15:08:12 +00003797
Ted Kremenek6217b802009-07-29 21:53:49 +00003798 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003799 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003800 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00003801 // Anonymous structures print as '?'
3802 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3803 S += II->getName();
3804 } else {
3805 S += '?';
3806 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003807 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003808 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003809 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3810 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00003811 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003812 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003813 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00003814 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003815 S += '"';
3816 }
Mike Stump1eb44332009-09-09 15:08:12 +00003817
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003818 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003819 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003820 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003821 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003822 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003823 QualType qt = Field->getType();
3824 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00003825 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003826 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003827 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003828 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00003829 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00003830 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003831 return;
3832 }
Mike Stump1eb44332009-09-09 15:08:12 +00003833
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003834 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00003835 if (FD && FD->isBitField())
3836 EncodeBitField(this, S, FD);
3837 else
3838 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003839 return;
3840 }
Mike Stump1eb44332009-09-09 15:08:12 +00003841
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003842 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00003843 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003844 return;
3845 }
Mike Stump1eb44332009-09-09 15:08:12 +00003846
John McCall0953e762009-09-24 19:53:00 +00003847 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003848 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00003849 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003850 S += '{';
3851 const IdentifierInfo *II = OI->getIdentifier();
3852 S += II->getName();
3853 S += '=';
Chris Lattnerf1690852009-03-31 08:48:01 +00003854 llvm::SmallVector<FieldDecl*, 32> RecFields;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003855 CollectObjCIvars(OI, RecFields);
Chris Lattnerf1690852009-03-31 08:48:01 +00003856 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003857 if (RecFields[i]->isBitField())
Mike Stump1eb44332009-09-09 15:08:12 +00003858 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003859 RecFields[i]);
3860 else
Mike Stump1eb44332009-09-09 15:08:12 +00003861 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003862 FD);
3863 }
3864 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003865 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00003866 }
Mike Stump1eb44332009-09-09 15:08:12 +00003867
John McCall183700f2009-09-21 23:43:11 +00003868 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003869 if (OPT->isObjCIdType()) {
3870 S += '@';
3871 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003872 }
Mike Stump1eb44332009-09-09 15:08:12 +00003873
Steve Naroff27d20a22009-10-28 22:03:49 +00003874 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3875 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3876 // Since this is a binary compatibility issue, need to consult with runtime
3877 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00003878 S += '#';
3879 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003880 }
Mike Stump1eb44332009-09-09 15:08:12 +00003881
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003882 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003883 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00003884 ExpandPointedToStructures,
3885 ExpandStructures, FD);
3886 if (FD || EncodingProperty) {
3887 // Note that we do extended encoding of protocol qualifer list
3888 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00003889 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003890 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3891 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00003892 S += '<';
3893 S += (*I)->getNameAsString();
3894 S += '>';
3895 }
3896 S += '"';
3897 }
3898 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003899 }
Mike Stump1eb44332009-09-09 15:08:12 +00003900
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003901 QualType PointeeTy = OPT->getPointeeType();
3902 if (!EncodingProperty &&
3903 isa<TypedefType>(PointeeTy.getTypePtr())) {
3904 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00003905 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003906 // {...};
3907 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00003908 getObjCEncodingForTypeImpl(PointeeTy, S,
3909 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003910 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00003911 return;
3912 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003913
3914 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00003915 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003916 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00003917 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003918 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3919 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003920 S += '<';
3921 S += (*I)->getNameAsString();
3922 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00003923 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003924 S += '"';
3925 }
3926 return;
3927 }
Mike Stump1eb44332009-09-09 15:08:12 +00003928
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003929 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003930}
3931
Mike Stump1eb44332009-09-09 15:08:12 +00003932void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003933 std::string& S) const {
3934 if (QT & Decl::OBJC_TQ_In)
3935 S += 'n';
3936 if (QT & Decl::OBJC_TQ_Inout)
3937 S += 'N';
3938 if (QT & Decl::OBJC_TQ_Out)
3939 S += 'o';
3940 if (QT & Decl::OBJC_TQ_Bycopy)
3941 S += 'O';
3942 if (QT & Decl::OBJC_TQ_Byref)
3943 S += 'R';
3944 if (QT & Decl::OBJC_TQ_Oneway)
3945 S += 'V';
3946}
3947
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003948void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003949 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003950
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003951 BuiltinVaListType = T;
3952}
3953
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003954void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003955 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00003956}
3957
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003958void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00003959 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00003960}
3961
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003962void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003963 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00003964}
3965
Chris Lattnerce7b38c2009-07-13 00:10:46 +00003966void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003967 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00003968}
3969
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003970void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003971 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00003972 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00003973
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003974 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00003975}
3976
John McCall0bd6feb2009-12-02 08:04:21 +00003977/// \brief Retrieve the template name that corresponds to a non-empty
3978/// lookup.
John McCalleec51cf2010-01-20 00:46:10 +00003979TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3980 UnresolvedSetIterator End) {
John McCall0bd6feb2009-12-02 08:04:21 +00003981 unsigned size = End - Begin;
3982 assert(size > 1 && "set is not overloaded!");
3983
3984 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3985 size * sizeof(FunctionTemplateDecl*));
3986 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3987
3988 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00003989 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00003990 NamedDecl *D = *I;
3991 assert(isa<FunctionTemplateDecl>(D) ||
3992 (isa<UsingShadowDecl>(D) &&
3993 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3994 *Storage++ = D;
3995 }
3996
3997 return TemplateName(OT);
3998}
3999
Douglas Gregor7532dc62009-03-30 22:58:21 +00004000/// \brief Retrieve the template name that represents a qualified
4001/// template name such as \c std::vector.
Mike Stump1eb44332009-09-09 15:08:12 +00004002TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004003 bool TemplateKeyword,
4004 TemplateDecl *Template) {
Douglas Gregor789b1f62010-02-04 18:10:26 +00004005 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004006 llvm::FoldingSetNodeID ID;
4007 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4008
4009 void *InsertPos = 0;
4010 QualifiedTemplateName *QTN =
4011 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4012 if (!QTN) {
4013 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4014 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4015 }
4016
4017 return TemplateName(QTN);
4018}
4019
4020/// \brief Retrieve the template name that represents a dependent
4021/// template name such as \c MetaFun::template apply.
Mike Stump1eb44332009-09-09 15:08:12 +00004022TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004023 const IdentifierInfo *Name) {
Mike Stump1eb44332009-09-09 15:08:12 +00004024 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004025 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004026
4027 llvm::FoldingSetNodeID ID;
4028 DependentTemplateName::Profile(ID, NNS, Name);
4029
4030 void *InsertPos = 0;
4031 DependentTemplateName *QTN =
4032 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4033
4034 if (QTN)
4035 return TemplateName(QTN);
4036
4037 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4038 if (CanonNNS == NNS) {
4039 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4040 } else {
4041 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4042 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004043 DependentTemplateName *CheckQTN =
4044 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4045 assert(!CheckQTN && "Dependent type name canonicalization broken");
4046 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004047 }
4048
4049 DependentTemplateNames.InsertNode(QTN, InsertPos);
4050 return TemplateName(QTN);
4051}
4052
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004053/// \brief Retrieve the template name that represents a dependent
4054/// template name such as \c MetaFun::template operator+.
4055TemplateName
4056ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4057 OverloadedOperatorKind Operator) {
4058 assert((!NNS || NNS->isDependent()) &&
4059 "Nested name specifier must be dependent");
4060
4061 llvm::FoldingSetNodeID ID;
4062 DependentTemplateName::Profile(ID, NNS, Operator);
4063
4064 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004065 DependentTemplateName *QTN
4066 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004067
4068 if (QTN)
4069 return TemplateName(QTN);
4070
4071 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4072 if (CanonNNS == NNS) {
4073 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4074 } else {
4075 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4076 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004077
4078 DependentTemplateName *CheckQTN
4079 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4080 assert(!CheckQTN && "Dependent template name canonicalization broken");
4081 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004082 }
4083
4084 DependentTemplateNames.InsertNode(QTN, InsertPos);
4085 return TemplateName(QTN);
4086}
4087
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004088/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004089/// TargetInfo, produce the corresponding type. The unsigned @p Type
4090/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004091CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004092 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004093 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004094 case TargetInfo::SignedShort: return ShortTy;
4095 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4096 case TargetInfo::SignedInt: return IntTy;
4097 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4098 case TargetInfo::SignedLong: return LongTy;
4099 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4100 case TargetInfo::SignedLongLong: return LongLongTy;
4101 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4102 }
4103
4104 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004105 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004106}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004107
4108//===----------------------------------------------------------------------===//
4109// Type Predicates.
4110//===----------------------------------------------------------------------===//
4111
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004112/// isObjCNSObjectType - Return true if this is an NSObject object using
4113/// NSObject attribute on a c-style pointer type.
4114/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004115/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004116///
4117bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4118 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4119 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004120 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004121 return true;
4122 }
Mike Stump1eb44332009-09-09 15:08:12 +00004123 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004124}
4125
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004126/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4127/// garbage collection attribute.
4128///
John McCall0953e762009-09-24 19:53:00 +00004129Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4130 Qualifiers::GC GCAttrs = Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004131 if (getLangOptions().ObjC1 &&
4132 getLangOptions().getGCMode() != LangOptions::NonGC) {
Chris Lattnerb7d25532009-02-18 22:53:11 +00004133 GCAttrs = Ty.getObjCGCAttr();
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004134 // Default behavious under objective-c's gc is for objective-c pointers
Mike Stump1eb44332009-09-09 15:08:12 +00004135 // (or pointers to them) be treated as though they were declared
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004136 // as __strong.
John McCall0953e762009-09-24 19:53:00 +00004137 if (GCAttrs == Qualifiers::GCNone) {
Fariborz Jahanian75212ee2009-09-10 23:38:45 +00004138 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004139 GCAttrs = Qualifiers::Strong;
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004140 else if (Ty->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004141 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
Fariborz Jahaniana223cca2009-02-19 23:36:06 +00004142 }
Fariborz Jahanianc2112182009-04-11 00:00:54 +00004143 // Non-pointers have none gc'able attribute regardless of the attribute
4144 // set on them.
Steve Narofff4954562009-07-16 15:41:00 +00004145 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
John McCall0953e762009-09-24 19:53:00 +00004146 return Qualifiers::GCNone;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004147 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004148 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004149}
4150
Chris Lattner6ac46a42008-04-07 06:51:04 +00004151//===----------------------------------------------------------------------===//
4152// Type Compatibility Testing
4153//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004154
Mike Stump1eb44332009-09-09 15:08:12 +00004155/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004156/// compatible.
4157static bool areCompatVectorTypes(const VectorType *LHS,
4158 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004159 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004160 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004161 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004162}
4163
Steve Naroff4084c302009-07-23 01:01:38 +00004164//===----------------------------------------------------------------------===//
4165// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4166//===----------------------------------------------------------------------===//
4167
4168/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4169/// inheritance hierarchy of 'rProto'.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004170bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4171 ObjCProtocolDecl *rProto) {
Steve Naroff4084c302009-07-23 01:01:38 +00004172 if (lProto == rProto)
4173 return true;
4174 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4175 E = rProto->protocol_end(); PI != E; ++PI)
4176 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4177 return true;
4178 return false;
4179}
4180
Steve Naroff4084c302009-07-23 01:01:38 +00004181/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4182/// return true if lhs's protocols conform to rhs's protocol; false
4183/// otherwise.
4184bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4185 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4186 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4187 return false;
4188}
4189
4190/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4191/// ObjCQualifiedIDType.
4192bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4193 bool compare) {
4194 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004195 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004196 lhs->isObjCIdType() || lhs->isObjCClassType())
4197 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004198 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004199 rhs->isObjCIdType() || rhs->isObjCClassType())
4200 return true;
4201
4202 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004203 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004204
Steve Naroff4084c302009-07-23 01:01:38 +00004205 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004206
Steve Naroff4084c302009-07-23 01:01:38 +00004207 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004208 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004209 // make sure we check the class hierarchy.
4210 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4211 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4212 E = lhsQID->qual_end(); I != E; ++I) {
4213 // when comparing an id<P> on lhs with a static type on rhs,
4214 // see if static class implements all of id's protocols, directly or
4215 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004216 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004217 return false;
4218 }
4219 }
4220 // If there are no qualifiers and no interface, we have an 'id'.
4221 return true;
4222 }
Mike Stump1eb44332009-09-09 15:08:12 +00004223 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004224 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4225 E = lhsQID->qual_end(); I != E; ++I) {
4226 ObjCProtocolDecl *lhsProto = *I;
4227 bool match = false;
4228
4229 // when comparing an id<P> on lhs with a static type on rhs,
4230 // see if static class implements all of id's protocols, directly or
4231 // through its super class and categories.
4232 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4233 E = rhsOPT->qual_end(); J != E; ++J) {
4234 ObjCProtocolDecl *rhsProto = *J;
4235 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4236 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4237 match = true;
4238 break;
4239 }
4240 }
Mike Stump1eb44332009-09-09 15:08:12 +00004241 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004242 // make sure we check the class hierarchy.
4243 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4244 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4245 E = lhsQID->qual_end(); I != E; ++I) {
4246 // when comparing an id<P> on lhs with a static type on rhs,
4247 // see if static class implements all of id's protocols, directly or
4248 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004249 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004250 match = true;
4251 break;
4252 }
4253 }
4254 }
4255 if (!match)
4256 return false;
4257 }
Mike Stump1eb44332009-09-09 15:08:12 +00004258
Steve Naroff4084c302009-07-23 01:01:38 +00004259 return true;
4260 }
Mike Stump1eb44332009-09-09 15:08:12 +00004261
Steve Naroff4084c302009-07-23 01:01:38 +00004262 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4263 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4264
Mike Stump1eb44332009-09-09 15:08:12 +00004265 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004266 lhs->getAsObjCInterfacePointerType()) {
4267 if (lhsOPT->qual_empty()) {
4268 bool match = false;
4269 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4270 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4271 E = rhsQID->qual_end(); I != E; ++I) {
4272 // when comparing an id<P> on lhs with a static type on rhs,
4273 // see if static class implements all of id's protocols, directly or
4274 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004275 if (lhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004276 match = true;
4277 break;
4278 }
4279 }
4280 if (!match)
4281 return false;
4282 }
4283 return true;
4284 }
Mike Stump1eb44332009-09-09 15:08:12 +00004285 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004286 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4287 E = lhsOPT->qual_end(); I != E; ++I) {
4288 ObjCProtocolDecl *lhsProto = *I;
4289 bool match = false;
4290
4291 // when comparing an id<P> on lhs with a static type on rhs,
4292 // see if static class implements all of id's protocols, directly or
4293 // through its super class and categories.
4294 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4295 E = rhsQID->qual_end(); J != E; ++J) {
4296 ObjCProtocolDecl *rhsProto = *J;
4297 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4298 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4299 match = true;
4300 break;
4301 }
4302 }
4303 if (!match)
4304 return false;
4305 }
4306 return true;
4307 }
4308 return false;
4309}
4310
Eli Friedman3d815e72008-08-22 00:56:42 +00004311/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004312/// compatible for assignment from RHS to LHS. This handles validation of any
4313/// protocol qualifiers on the LHS or RHS.
4314///
Steve Naroff14108da2009-07-10 23:34:53 +00004315bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4316 const ObjCObjectPointerType *RHSOPT) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004317 // If either type represents the built-in 'id' or 'Class' types, return true.
4318 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00004319 return true;
4320
Steve Naroff4084c302009-07-23 01:01:38 +00004321 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Mike Stump1eb44332009-09-09 15:08:12 +00004322 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4323 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004324 false);
4325
Steve Naroff14108da2009-07-10 23:34:53 +00004326 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4327 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
Steve Naroff4084c302009-07-23 01:01:38 +00004328 if (LHS && RHS) // We have 2 user-defined types.
4329 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004330
Steve Naroff4084c302009-07-23 01:01:38 +00004331 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004332}
4333
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004334/// getIntersectionOfProtocols - This routine finds the intersection of set
4335/// of protocols inherited from two distinct objective-c pointer objects.
4336/// It is used to build composite qualifier list of the composite type of
4337/// the conditional expression involving two objective-c pointer objects.
4338static
4339void getIntersectionOfProtocols(ASTContext &Context,
4340 const ObjCObjectPointerType *LHSOPT,
4341 const ObjCObjectPointerType *RHSOPT,
4342 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4343
4344 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4345 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4346
4347 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4348 unsigned LHSNumProtocols = LHS->getNumProtocols();
4349 if (LHSNumProtocols > 0)
4350 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4351 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004352 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4353 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004354 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4355 LHSInheritedProtocols.end());
4356 }
4357
4358 unsigned RHSNumProtocols = RHS->getNumProtocols();
4359 if (RHSNumProtocols > 0) {
4360 ObjCProtocolDecl **RHSProtocols = (ObjCProtocolDecl **)RHS->qual_begin();
4361 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4362 if (InheritedProtocolSet.count(RHSProtocols[i]))
4363 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4364 }
4365 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004366 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004367 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004368 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4369 RHSInheritedProtocols.begin(),
4370 E = RHSInheritedProtocols.end(); I != E; ++I)
4371 if (InheritedProtocolSet.count((*I)))
4372 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004373 }
4374}
4375
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004376/// areCommonBaseCompatible - Returns common base class of the two classes if
4377/// one found. Note that this is O'2 algorithm. But it will be called as the
4378/// last type comparison in a ?-exp of ObjC pointer types before a
4379/// warning is issued. So, its invokation is extremely rare.
4380QualType ASTContext::areCommonBaseCompatible(
4381 const ObjCObjectPointerType *LHSOPT,
4382 const ObjCObjectPointerType *RHSOPT) {
4383 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4384 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4385 if (!LHS || !RHS)
4386 return QualType();
4387
4388 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4389 QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4390 LHS = LHSTy->getAs<ObjCInterfaceType>();
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004391 if (canAssignObjCInterfaces(LHS, RHS)) {
4392 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4393 getIntersectionOfProtocols(*this,
4394 LHSOPT, RHSOPT, IntersectionOfProtocols);
4395 if (IntersectionOfProtocols.empty())
4396 LHSTy = getObjCObjectPointerType(LHSTy);
4397 else
4398 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4399 IntersectionOfProtocols.size());
4400 return LHSTy;
4401 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004402 }
4403
4404 return QualType();
4405}
4406
Eli Friedman3d815e72008-08-22 00:56:42 +00004407bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4408 const ObjCInterfaceType *RHS) {
Chris Lattner6ac46a42008-04-07 06:51:04 +00004409 // Verify that the base decls are compatible: the RHS must be a subclass of
4410 // the LHS.
4411 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4412 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004413
Chris Lattner6ac46a42008-04-07 06:51:04 +00004414 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4415 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004416 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004417 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004418
Chris Lattner6ac46a42008-04-07 06:51:04 +00004419 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4420 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004421 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004422 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004423
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004424 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4425 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004426 LHSPI != LHSPE; LHSPI++) {
4427 bool RHSImplementsProtocol = false;
4428
4429 // If the RHS doesn't implement the protocol on the left, the types
4430 // are incompatible.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004431 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
Steve Naroff4084c302009-07-23 01:01:38 +00004432 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004433 RHSPI != RHSPE; RHSPI++) {
4434 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004435 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004436 break;
4437 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004438 }
4439 // FIXME: For better diagnostics, consider passing back the protocol name.
4440 if (!RHSImplementsProtocol)
4441 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004442 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004443 // The RHS implements all protocols listed on the LHS.
4444 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00004445}
4446
Steve Naroff389bf462009-02-12 17:52:19 +00004447bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4448 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00004449 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4450 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004451
Steve Naroff14108da2009-07-10 23:34:53 +00004452 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00004453 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004454
4455 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4456 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00004457}
4458
Mike Stump1eb44332009-09-09 15:08:12 +00004459/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00004460/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00004461/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00004462/// same. See 6.7.[2,3,5] for additional rules.
Eli Friedman3d815e72008-08-22 00:56:42 +00004463bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004464 if (getLangOptions().CPlusPlus)
4465 return hasSameType(LHS, RHS);
4466
Eli Friedman3d815e72008-08-22 00:56:42 +00004467 return !mergeTypes(LHS, RHS).isNull();
4468}
4469
4470QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
John McCall183700f2009-09-21 23:43:11 +00004471 const FunctionType *lbase = lhs->getAs<FunctionType>();
4472 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00004473 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4474 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00004475 bool allLTypes = true;
4476 bool allRTypes = true;
4477
4478 // Check return type
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004479 QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
Eli Friedman3d815e72008-08-22 00:56:42 +00004480 if (retType.isNull()) return QualType();
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004481 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004482 allLTypes = false;
Fariborz Jahanian6de8b622010-02-10 00:32:12 +00004483 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
Chris Lattner61710852008-10-05 17:34:18 +00004484 allRTypes = false;
Mike Stump6dcbc292009-07-25 23:24:03 +00004485 // FIXME: double check this
Mike Stump24556362009-07-25 21:26:53 +00004486 bool NoReturn = lbase->getNoReturnAttr() || rbase->getNoReturnAttr();
4487 if (NoReturn != lbase->getNoReturnAttr())
4488 allLTypes = false;
4489 if (NoReturn != rbase->getNoReturnAttr())
4490 allRTypes = false;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004491 CallingConv lcc = lbase->getCallConv();
4492 CallingConv rcc = rbase->getCallConv();
4493 // Compatible functions must have compatible calling conventions
John McCall04a67a62010-02-05 21:31:56 +00004494 if (!isSameCallConv(lcc, rcc))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004495 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00004496
Eli Friedman3d815e72008-08-22 00:56:42 +00004497 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00004498 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4499 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004500 unsigned lproto_nargs = lproto->getNumArgs();
4501 unsigned rproto_nargs = rproto->getNumArgs();
4502
4503 // Compatible functions must have the same number of arguments
4504 if (lproto_nargs != rproto_nargs)
4505 return QualType();
4506
4507 // Variadic and non-variadic functions aren't compatible
4508 if (lproto->isVariadic() != rproto->isVariadic())
4509 return QualType();
4510
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00004511 if (lproto->getTypeQuals() != rproto->getTypeQuals())
4512 return QualType();
4513
Eli Friedman3d815e72008-08-22 00:56:42 +00004514 // Check argument compatibility
4515 llvm::SmallVector<QualType, 10> types;
4516 for (unsigned i = 0; i < lproto_nargs; i++) {
4517 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4518 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4519 QualType argtype = mergeTypes(largtype, rargtype);
4520 if (argtype.isNull()) return QualType();
4521 types.push_back(argtype);
Chris Lattner61710852008-10-05 17:34:18 +00004522 if (getCanonicalType(argtype) != getCanonicalType(largtype))
4523 allLTypes = false;
4524 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4525 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00004526 }
4527 if (allLTypes) return lhs;
4528 if (allRTypes) return rhs;
4529 return getFunctionType(retType, types.begin(), types.size(),
Mike Stump24556362009-07-25 21:26:53 +00004530 lproto->isVariadic(), lproto->getTypeQuals(),
Douglas Gregor1bf40242010-02-12 17:17:28 +00004531 false, false, 0, 0, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004532 }
4533
4534 if (lproto) allRTypes = false;
4535 if (rproto) allLTypes = false;
4536
Douglas Gregor72564e72009-02-26 23:50:07 +00004537 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00004538 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00004539 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00004540 if (proto->isVariadic()) return QualType();
4541 // Check that the types are compatible with the types that
4542 // would result from default argument promotions (C99 6.7.5.3p15).
4543 // The only types actually affected are promotable integer
4544 // types and floats, which would be passed as a different
4545 // type depending on whether the prototype is visible.
4546 unsigned proto_nargs = proto->getNumArgs();
4547 for (unsigned i = 0; i < proto_nargs; ++i) {
4548 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00004549
4550 // Look at the promotion type of enum types, since that is the type used
4551 // to pass enum values.
4552 if (const EnumType *Enum = argTy->getAs<EnumType>())
4553 argTy = Enum->getDecl()->getPromotionType();
4554
Eli Friedman3d815e72008-08-22 00:56:42 +00004555 if (argTy->isPromotableIntegerType() ||
4556 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4557 return QualType();
4558 }
4559
4560 if (allLTypes) return lhs;
4561 if (allRTypes) return rhs;
4562 return getFunctionType(retType, proto->arg_type_begin(),
Mike Stump2d3c1912009-07-27 00:44:23 +00004563 proto->getNumArgs(), proto->isVariadic(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004564 proto->getTypeQuals(),
4565 false, false, 0, 0, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004566 }
4567
4568 if (allLTypes) return lhs;
4569 if (allRTypes) return rhs;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00004570 return getFunctionNoProtoType(retType, NoReturn, lcc);
Eli Friedman3d815e72008-08-22 00:56:42 +00004571}
4572
4573QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
Bill Wendling43d69752007-12-03 07:33:35 +00004574 // C++ [expr]: If an expression initially has the type "reference to T", the
4575 // type is adjusted to "T" prior to any further analysis, the expression
4576 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004577 // expression is an lvalue unless the reference is an rvalue reference and
4578 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00004579 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4580 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4581
Eli Friedman3d815e72008-08-22 00:56:42 +00004582 QualType LHSCan = getCanonicalType(LHS),
4583 RHSCan = getCanonicalType(RHS);
4584
4585 // If two types are identical, they are compatible.
4586 if (LHSCan == RHSCan)
4587 return LHS;
4588
John McCall0953e762009-09-24 19:53:00 +00004589 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004590 Qualifiers LQuals = LHSCan.getLocalQualifiers();
4591 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00004592 if (LQuals != RQuals) {
4593 // If any of these qualifiers are different, we have a type
4594 // mismatch.
4595 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4596 LQuals.getAddressSpace() != RQuals.getAddressSpace())
4597 return QualType();
4598
4599 // Exactly one GC qualifier difference is allowed: __strong is
4600 // okay if the other type has no GC qualifier but is an Objective
4601 // C object pointer (i.e. implicitly strong by default). We fix
4602 // this by pretending that the unqualified type was actually
4603 // qualified __strong.
4604 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4605 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4606 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4607
4608 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4609 return QualType();
4610
4611 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4612 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4613 }
4614 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4615 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4616 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004617 return QualType();
John McCall0953e762009-09-24 19:53:00 +00004618 }
4619
4620 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00004621
Eli Friedman852d63b2009-06-01 01:22:52 +00004622 Type::TypeClass LHSClass = LHSCan->getTypeClass();
4623 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00004624
Chris Lattner1adb8832008-01-14 05:45:46 +00004625 // We want to consider the two function types to be the same for these
4626 // comparisons, just force one to the other.
4627 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4628 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00004629
4630 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00004631 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4632 LHSClass = Type::ConstantArray;
4633 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4634 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00004635
Nate Begeman213541a2008-04-18 23:10:10 +00004636 // Canonicalize ExtVector -> Vector.
4637 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4638 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00004639
Chris Lattnera36a61f2008-04-07 05:43:21 +00004640 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004641 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00004642 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00004643 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00004644 // Compatibility is based on the underlying type, not the promotion
4645 // type.
John McCall183700f2009-09-21 23:43:11 +00004646 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004647 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4648 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004649 }
John McCall183700f2009-09-21 23:43:11 +00004650 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00004651 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4652 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00004653 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004654
Eli Friedman3d815e72008-08-22 00:56:42 +00004655 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004656 }
Eli Friedman3d815e72008-08-22 00:56:42 +00004657
Steve Naroff4a746782008-01-09 22:43:08 +00004658 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00004659 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004660#define TYPE(Class, Base)
4661#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00004662#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00004663#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4664#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4665#include "clang/AST/TypeNodes.def"
4666 assert(false && "Non-canonical and dependent types shouldn't get here");
4667 return QualType();
4668
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004669 case Type::LValueReference:
4670 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00004671 case Type::MemberPointer:
4672 assert(false && "C++ should never be in mergeTypes");
4673 return QualType();
4674
4675 case Type::IncompleteArray:
4676 case Type::VariableArray:
4677 case Type::FunctionProto:
4678 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00004679 assert(false && "Types are eliminated above");
4680 return QualType();
4681
Chris Lattner1adb8832008-01-14 05:45:46 +00004682 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00004683 {
4684 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004685 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4686 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Eli Friedman3d815e72008-08-22 00:56:42 +00004687 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4688 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00004689 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004690 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00004691 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00004692 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004693 return getPointerType(ResultType);
4694 }
Steve Naroffc0febd52008-12-10 17:49:55 +00004695 case Type::BlockPointer:
4696 {
4697 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00004698 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4699 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Steve Naroffc0febd52008-12-10 17:49:55 +00004700 QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4701 if (ResultType.isNull()) return QualType();
4702 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4703 return LHS;
4704 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4705 return RHS;
4706 return getBlockPointerType(ResultType);
4707 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004708 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00004709 {
4710 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4711 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4712 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4713 return QualType();
4714
4715 QualType LHSElem = getAsArrayType(LHS)->getElementType();
4716 QualType RHSElem = getAsArrayType(RHS)->getElementType();
4717 QualType ResultType = mergeTypes(LHSElem, RHSElem);
4718 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00004719 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4720 return LHS;
4721 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4722 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00004723 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4724 ArrayType::ArraySizeModifier(), 0);
4725 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4726 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004727 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4728 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00004729 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4730 return LHS;
4731 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4732 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00004733 if (LVAT) {
4734 // FIXME: This isn't correct! But tricky to implement because
4735 // the array's size has to be the size of LHS, but the type
4736 // has to be different.
4737 return LHS;
4738 }
4739 if (RVAT) {
4740 // FIXME: This isn't correct! But tricky to implement because
4741 // the array's size has to be the size of RHS, but the type
4742 // has to be different.
4743 return RHS;
4744 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00004745 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4746 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00004747 return getIncompleteArrayType(ResultType,
4748 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00004749 }
Chris Lattner1adb8832008-01-14 05:45:46 +00004750 case Type::FunctionNoProto:
Eli Friedman3d815e72008-08-22 00:56:42 +00004751 return mergeFunctionTypes(LHS, RHS);
Douglas Gregor72564e72009-02-26 23:50:07 +00004752 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00004753 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00004754 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00004755 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004756 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00004757 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00004758 case Type::Complex:
4759 // Distinct complex types are incompatible.
4760 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00004761 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004762 // FIXME: The merged type should be an ExtVector!
John McCall183700f2009-09-21 23:43:11 +00004763 if (areCompatVectorTypes(LHS->getAs<VectorType>(), RHS->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00004764 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00004765 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004766 case Type::ObjCInterface: {
Steve Naroff5fd659d2009-02-21 16:18:07 +00004767 // Check if the interfaces are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00004768 // FIXME: This should be type compatibility, e.g. whether
4769 // "LHS x; RHS x;" at global scope is legal.
John McCall183700f2009-09-21 23:43:11 +00004770 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4771 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
Steve Naroff5fd659d2009-02-21 16:18:07 +00004772 if (LHSIface && RHSIface &&
4773 canAssignObjCInterfaces(LHSIface, RHSIface))
4774 return LHS;
4775
Eli Friedman3d815e72008-08-22 00:56:42 +00004776 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00004777 }
Steve Naroff14108da2009-07-10 23:34:53 +00004778 case Type::ObjCObjectPointer: {
John McCall183700f2009-09-21 23:43:11 +00004779 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4780 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00004781 return LHS;
4782
Steve Naroffbc76dd02008-12-10 22:14:21 +00004783 return QualType();
Steve Naroff14108da2009-07-10 23:34:53 +00004784 }
Steve Naroffec0550f2007-10-15 20:41:53 +00004785 }
Douglas Gregor72564e72009-02-26 23:50:07 +00004786
4787 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00004788}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00004789
Chris Lattner5426bf62008-04-07 07:01:58 +00004790//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00004791// Integer Predicates
4792//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00004793
Eli Friedmanad74a752008-06-28 06:23:08 +00004794unsigned ASTContext::getIntWidth(QualType T) {
Sebastian Redl632d7722009-11-05 21:10:57 +00004795 if (T->isBooleanType())
Eli Friedmanad74a752008-06-28 06:23:08 +00004796 return 1;
John McCall842aef82009-12-09 09:09:27 +00004797 if (EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00004798 T = ET->getDecl()->getIntegerType();
Eli Friedmanf98aba32009-02-13 02:31:07 +00004799 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00004800 return (unsigned)getTypeSize(T);
4801}
4802
4803QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4804 assert(T->isSignedIntegerType() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00004805
4806 // Turn <4 x signed int> -> <4 x unsigned int>
4807 if (const VectorType *VTy = T->getAs<VectorType>())
4808 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
John Thompson82287d12010-02-05 00:12:22 +00004809 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
Chris Lattner6a2b9262009-10-17 20:33:28 +00004810
4811 // For enums, we return the unsigned version of the base type.
4812 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00004813 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00004814
4815 const BuiltinType *BTy = T->getAs<BuiltinType>();
4816 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00004817 switch (BTy->getKind()) {
4818 case BuiltinType::Char_S:
4819 case BuiltinType::SChar:
4820 return UnsignedCharTy;
4821 case BuiltinType::Short:
4822 return UnsignedShortTy;
4823 case BuiltinType::Int:
4824 return UnsignedIntTy;
4825 case BuiltinType::Long:
4826 return UnsignedLongTy;
4827 case BuiltinType::LongLong:
4828 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00004829 case BuiltinType::Int128:
4830 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00004831 default:
4832 assert(0 && "Unexpected signed integer type");
4833 return QualType();
4834 }
4835}
4836
Douglas Gregor2cf26342009-04-09 22:27:44 +00004837ExternalASTSource::~ExternalASTSource() { }
4838
4839void ExternalASTSource::PrintStats() { }
Chris Lattner86df27b2009-06-14 00:45:47 +00004840
4841
4842//===----------------------------------------------------------------------===//
4843// Builtin Type Computation
4844//===----------------------------------------------------------------------===//
4845
4846/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4847/// pointer over the consumed characters. This returns the resultant type.
Mike Stump1eb44332009-09-09 15:08:12 +00004848static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00004849 ASTContext::GetBuiltinTypeError &Error,
4850 bool AllowTypeModifiers = true) {
4851 // Modifiers.
4852 int HowLong = 0;
4853 bool Signed = false, Unsigned = false;
Mike Stump1eb44332009-09-09 15:08:12 +00004854
Chris Lattner86df27b2009-06-14 00:45:47 +00004855 // Read the modifiers first.
4856 bool Done = false;
4857 while (!Done) {
4858 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00004859 default: Done = true; --Str; break;
Chris Lattner86df27b2009-06-14 00:45:47 +00004860 case 'S':
4861 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4862 assert(!Signed && "Can't use 'S' modifier multiple times!");
4863 Signed = true;
4864 break;
4865 case 'U':
4866 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4867 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4868 Unsigned = true;
4869 break;
4870 case 'L':
4871 assert(HowLong <= 2 && "Can't have LLLL modifier");
4872 ++HowLong;
4873 break;
4874 }
4875 }
4876
4877 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004878
Chris Lattner86df27b2009-06-14 00:45:47 +00004879 // Read the base type.
4880 switch (*Str++) {
4881 default: assert(0 && "Unknown builtin type letter!");
4882 case 'v':
4883 assert(HowLong == 0 && !Signed && !Unsigned &&
4884 "Bad modifiers used with 'v'!");
4885 Type = Context.VoidTy;
4886 break;
4887 case 'f':
4888 assert(HowLong == 0 && !Signed && !Unsigned &&
4889 "Bad modifiers used with 'f'!");
4890 Type = Context.FloatTy;
4891 break;
4892 case 'd':
4893 assert(HowLong < 2 && !Signed && !Unsigned &&
4894 "Bad modifiers used with 'd'!");
4895 if (HowLong)
4896 Type = Context.LongDoubleTy;
4897 else
4898 Type = Context.DoubleTy;
4899 break;
4900 case 's':
4901 assert(HowLong == 0 && "Bad modifiers used with 's'!");
4902 if (Unsigned)
4903 Type = Context.UnsignedShortTy;
4904 else
4905 Type = Context.ShortTy;
4906 break;
4907 case 'i':
4908 if (HowLong == 3)
4909 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4910 else if (HowLong == 2)
4911 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4912 else if (HowLong == 1)
4913 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4914 else
4915 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4916 break;
4917 case 'c':
4918 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4919 if (Signed)
4920 Type = Context.SignedCharTy;
4921 else if (Unsigned)
4922 Type = Context.UnsignedCharTy;
4923 else
4924 Type = Context.CharTy;
4925 break;
4926 case 'b': // boolean
4927 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4928 Type = Context.BoolTy;
4929 break;
4930 case 'z': // size_t.
4931 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4932 Type = Context.getSizeType();
4933 break;
4934 case 'F':
4935 Type = Context.getCFConstantStringType();
4936 break;
4937 case 'a':
4938 Type = Context.getBuiltinVaListType();
4939 assert(!Type.isNull() && "builtin va list type not initialized!");
4940 break;
4941 case 'A':
4942 // This is a "reference" to a va_list; however, what exactly
4943 // this means depends on how va_list is defined. There are two
4944 // different kinds of va_list: ones passed by value, and ones
4945 // passed by reference. An example of a by-value va_list is
4946 // x86, where va_list is a char*. An example of by-ref va_list
4947 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4948 // we want this argument to be a char*&; for x86-64, we want
4949 // it to be a __va_list_tag*.
4950 Type = Context.getBuiltinVaListType();
4951 assert(!Type.isNull() && "builtin va list type not initialized!");
4952 if (Type->isArrayType()) {
4953 Type = Context.getArrayDecayedType(Type);
4954 } else {
4955 Type = Context.getLValueReferenceType(Type);
4956 }
4957 break;
4958 case 'V': {
4959 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00004960 unsigned NumElements = strtoul(Str, &End, 10);
4961 assert(End != Str && "Missing vector size");
Mike Stump1eb44332009-09-09 15:08:12 +00004962
Chris Lattner86df27b2009-06-14 00:45:47 +00004963 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00004964
Chris Lattner86df27b2009-06-14 00:45:47 +00004965 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
John Thompson82287d12010-02-05 00:12:22 +00004966 // FIXME: Don't know what to do about AltiVec.
4967 Type = Context.getVectorType(ElementType, NumElements, false, false);
Chris Lattner86df27b2009-06-14 00:45:47 +00004968 break;
4969 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00004970 case 'X': {
4971 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4972 Type = Context.getComplexType(ElementType);
4973 break;
4974 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004975 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00004976 Type = Context.getFILEType();
4977 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004978 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00004979 return QualType();
4980 }
Mike Stumpfd612db2009-07-28 23:47:15 +00004981 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00004982 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00004983 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00004984 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00004985 else
4986 Type = Context.getjmp_bufType();
4987
Mike Stumpfd612db2009-07-28 23:47:15 +00004988 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00004989 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00004990 return QualType();
4991 }
4992 break;
Mike Stump782fa302009-07-28 02:25:19 +00004993 }
Mike Stump1eb44332009-09-09 15:08:12 +00004994
Chris Lattner86df27b2009-06-14 00:45:47 +00004995 if (!AllowTypeModifiers)
4996 return Type;
Mike Stump1eb44332009-09-09 15:08:12 +00004997
Chris Lattner86df27b2009-06-14 00:45:47 +00004998 Done = false;
4999 while (!Done) {
5000 switch (*Str++) {
5001 default: Done = true; --Str; break;
5002 case '*':
5003 Type = Context.getPointerType(Type);
5004 break;
5005 case '&':
5006 Type = Context.getLValueReferenceType(Type);
5007 break;
5008 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5009 case 'C':
John McCall0953e762009-09-24 19:53:00 +00005010 Type = Type.withConst();
Chris Lattner86df27b2009-06-14 00:45:47 +00005011 break;
Fariborz Jahanian013af392010-01-26 22:48:42 +00005012 case 'D':
5013 Type = Context.getVolatileType(Type);
5014 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005015 }
5016 }
Mike Stump1eb44332009-09-09 15:08:12 +00005017
Chris Lattner86df27b2009-06-14 00:45:47 +00005018 return Type;
5019}
5020
5021/// GetBuiltinType - Return the type for the specified builtin.
5022QualType ASTContext::GetBuiltinType(unsigned id,
5023 GetBuiltinTypeError &Error) {
5024 const char *TypeStr = BuiltinInfo.GetTypeString(id);
Mike Stump1eb44332009-09-09 15:08:12 +00005025
Chris Lattner86df27b2009-06-14 00:45:47 +00005026 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005027
Chris Lattner86df27b2009-06-14 00:45:47 +00005028 Error = GE_None;
5029 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5030 if (Error != GE_None)
5031 return QualType();
5032 while (TypeStr[0] && TypeStr[0] != '.') {
5033 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5034 if (Error != GE_None)
5035 return QualType();
5036
5037 // Do array -> pointer decay. The builtin should use the decayed type.
5038 if (Ty->isArrayType())
5039 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005040
Chris Lattner86df27b2009-06-14 00:45:47 +00005041 ArgTypes.push_back(Ty);
5042 }
5043
5044 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5045 "'.' should only occur at end of builtin type list!");
5046
5047 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5048 if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5049 return getFunctionNoProtoType(ResType);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005050
5051 // FIXME: Should we create noreturn types?
Chris Lattner86df27b2009-06-14 00:45:47 +00005052 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00005053 TypeStr[0] == '.', 0, false, false, 0, 0,
5054 false, CC_Default);
Chris Lattner86df27b2009-06-14 00:45:47 +00005055}
Eli Friedmana95d7572009-08-19 07:44:53 +00005056
5057QualType
5058ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5059 // Perform the usual unary conversions. We do this early so that
5060 // integral promotions to "int" can allow us to exit early, in the
5061 // lhs == rhs check. Also, for conversion purposes, we ignore any
5062 // qualifiers. For example, "const float" and "float" are
5063 // equivalent.
5064 if (lhs->isPromotableIntegerType())
5065 lhs = getPromotedIntegerType(lhs);
5066 else
5067 lhs = lhs.getUnqualifiedType();
5068 if (rhs->isPromotableIntegerType())
5069 rhs = getPromotedIntegerType(rhs);
5070 else
5071 rhs = rhs.getUnqualifiedType();
5072
5073 // If both types are identical, no conversion is needed.
5074 if (lhs == rhs)
5075 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005076
Eli Friedmana95d7572009-08-19 07:44:53 +00005077 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5078 // The caller can deal with this (e.g. pointer + int).
5079 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5080 return lhs;
Mike Stump1eb44332009-09-09 15:08:12 +00005081
5082 // At this point, we have two different arithmetic types.
5083
Eli Friedmana95d7572009-08-19 07:44:53 +00005084 // Handle complex types first (C99 6.3.1.8p1).
5085 if (lhs->isComplexType() || rhs->isComplexType()) {
5086 // if we have an integer operand, the result is the complex type.
Mike Stump1eb44332009-09-09 15:08:12 +00005087 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005088 // convert the rhs to the lhs complex type.
5089 return lhs;
5090 }
Mike Stump1eb44332009-09-09 15:08:12 +00005091 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005092 // convert the lhs to the rhs complex type.
5093 return rhs;
5094 }
5095 // This handles complex/complex, complex/float, or float/complex.
Mike Stump1eb44332009-09-09 15:08:12 +00005096 // When both operands are complex, the shorter operand is converted to the
5097 // type of the longer, and that is the type of the result. This corresponds
5098 // to what is done when combining two real floating-point operands.
5099 // The fun begins when size promotion occur across type domains.
Eli Friedmana95d7572009-08-19 07:44:53 +00005100 // From H&S 6.3.4: When one operand is complex and the other is a real
Mike Stump1eb44332009-09-09 15:08:12 +00005101 // floating-point type, the less precise type is converted, within it's
Eli Friedmana95d7572009-08-19 07:44:53 +00005102 // real or complex domain, to the precision of the other type. For example,
Mike Stump1eb44332009-09-09 15:08:12 +00005103 // when combining a "long double" with a "double _Complex", the
Eli Friedmana95d7572009-08-19 07:44:53 +00005104 // "double _Complex" is promoted to "long double _Complex".
5105 int result = getFloatingTypeOrder(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005106
5107 if (result > 0) { // The left side is bigger, convert rhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005108 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005109 } else if (result < 0) { // The right side is bigger, convert lhs.
Eli Friedmana95d7572009-08-19 07:44:53 +00005110 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Mike Stump1eb44332009-09-09 15:08:12 +00005111 }
Eli Friedmana95d7572009-08-19 07:44:53 +00005112 // At this point, lhs and rhs have the same rank/size. Now, make sure the
5113 // domains match. This is a requirement for our implementation, C99
5114 // does not require this promotion.
5115 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5116 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5117 return rhs;
5118 } else { // handle "_Complex double, double".
5119 return lhs;
5120 }
5121 }
5122 return lhs; // The domain/size match exactly.
5123 }
5124 // Now handle "real" floating types (i.e. float, double, long double).
5125 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5126 // if we have an integer operand, the result is the real floating type.
5127 if (rhs->isIntegerType()) {
5128 // convert rhs to the lhs floating point type.
5129 return lhs;
5130 }
5131 if (rhs->isComplexIntegerType()) {
5132 // convert rhs to the complex floating point type.
5133 return getComplexType(lhs);
5134 }
5135 if (lhs->isIntegerType()) {
5136 // convert lhs to the rhs floating point type.
5137 return rhs;
5138 }
Mike Stump1eb44332009-09-09 15:08:12 +00005139 if (lhs->isComplexIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +00005140 // convert lhs to the complex floating point type.
5141 return getComplexType(rhs);
5142 }
5143 // We have two real floating types, float/complex combos were handled above.
5144 // Convert the smaller operand to the bigger result.
5145 int result = getFloatingTypeOrder(lhs, rhs);
5146 if (result > 0) // convert the rhs
5147 return lhs;
5148 assert(result < 0 && "illegal float comparison");
5149 return rhs; // convert the lhs
5150 }
5151 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5152 // Handle GCC complex int extension.
5153 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5154 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5155
5156 if (lhsComplexInt && rhsComplexInt) {
Mike Stump1eb44332009-09-09 15:08:12 +00005157 if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
Eli Friedmana95d7572009-08-19 07:44:53 +00005158 rhsComplexInt->getElementType()) >= 0)
5159 return lhs; // convert the rhs
5160 return rhs;
5161 } else if (lhsComplexInt && rhs->isIntegerType()) {
5162 // convert the rhs to the lhs complex type.
5163 return lhs;
5164 } else if (rhsComplexInt && lhs->isIntegerType()) {
5165 // convert the lhs to the rhs complex type.
5166 return rhs;
5167 }
5168 }
5169 // Finally, we have two differing integer types.
5170 // The rules for this case are in C99 6.3.1.8
5171 int compare = getIntegerTypeOrder(lhs, rhs);
5172 bool lhsSigned = lhs->isSignedIntegerType(),
5173 rhsSigned = rhs->isSignedIntegerType();
5174 QualType destType;
5175 if (lhsSigned == rhsSigned) {
5176 // Same signedness; use the higher-ranked type
5177 destType = compare >= 0 ? lhs : rhs;
5178 } else if (compare != (lhsSigned ? 1 : -1)) {
5179 // The unsigned type has greater than or equal rank to the
5180 // signed type, so use the unsigned type
5181 destType = lhsSigned ? rhs : lhs;
5182 } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5183 // The two types are different widths; if we are here, that
5184 // means the signed type is larger than the unsigned type, so
5185 // use the signed type.
5186 destType = lhsSigned ? lhs : rhs;
5187 } else {
5188 // The signed type is higher-ranked than the unsigned type,
5189 // but isn't actually any bigger (like unsigned int and long
5190 // on most 32-bit systems). Use the unsigned type corresponding
5191 // to the signed type.
5192 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5193 }
5194 return destType;
5195}