blob: 39229a7b731e4b2bb31a493e2c83e013f68aa689 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Charles Davis53c59df2010-08-16 03:33:14 +000033#include "CXXABI.h"
Anders Carlssona4267a62009-07-18 21:19:52 +000034
Chris Lattnerddc135e2006-11-10 06:34:16 +000035using namespace clang;
36
Douglas Gregor9672f922010-07-03 00:47:00 +000037unsigned ASTContext::NumImplicitDefaultConstructors;
38unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000039unsigned ASTContext::NumImplicitCopyConstructors;
40unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000041unsigned ASTContext::NumImplicitCopyAssignmentOperators;
42unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000043unsigned ASTContext::NumImplicitDestructors;
44unsigned ASTContext::NumImplicitDestructorsDeclared;
45
Steve Naroff0af91202007-04-27 21:51:21 +000046enum FloatingRank {
47 FloatRank, DoubleRank, LongDoubleRank
48};
49
Douglas Gregor7dbfb462010-06-16 21:09:37 +000050void
51ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
52 TemplateTemplateParmDecl *Parm) {
53 ID.AddInteger(Parm->getDepth());
54 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +000055 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000056
57 TemplateParameterList *Params = Parm->getTemplateParameters();
58 ID.AddInteger(Params->size());
59 for (TemplateParameterList::const_iterator P = Params->begin(),
60 PEnd = Params->end();
61 P != PEnd; ++P) {
62 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
63 ID.AddInteger(0);
64 ID.AddBoolean(TTP->isParameterPack());
65 continue;
66 }
67
68 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
69 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +000070 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000071 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +000072 if (NTTP->isExpandedParameterPack()) {
73 ID.AddBoolean(true);
74 ID.AddInteger(NTTP->getNumExpansionTypes());
75 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
76 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
77 } else
78 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +000079 continue;
80 }
81
82 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
83 ID.AddInteger(2);
84 Profile(ID, TTP);
85 }
86}
87
88TemplateTemplateParmDecl *
89ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000090 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000091 // Check if we already have a canonical template template parameter.
92 llvm::FoldingSetNodeID ID;
93 CanonicalTemplateTemplateParm::Profile(ID, TTP);
94 void *InsertPos = 0;
95 CanonicalTemplateTemplateParm *Canonical
96 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
97 if (Canonical)
98 return Canonical->getParam();
99
100 // Build a canonical template parameter list.
101 TemplateParameterList *Params = TTP->getTemplateParameters();
102 llvm::SmallVector<NamedDecl *, 4> CanonParams;
103 CanonParams.reserve(Params->size());
104 for (TemplateParameterList::const_iterator P = Params->begin(),
105 PEnd = Params->end();
106 P != PEnd; ++P) {
107 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
108 CanonParams.push_back(
109 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000110 SourceLocation(),
111 SourceLocation(),
112 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000113 TTP->getIndex(), 0, false,
114 TTP->isParameterPack()));
115 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000116 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
117 QualType T = getCanonicalType(NTTP->getType());
118 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
119 NonTypeTemplateParmDecl *Param;
120 if (NTTP->isExpandedParameterPack()) {
121 llvm::SmallVector<QualType, 2> ExpandedTypes;
122 llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
123 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
124 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
125 ExpandedTInfos.push_back(
126 getTrivialTypeSourceInfo(ExpandedTypes.back()));
127 }
128
129 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000130 SourceLocation(),
131 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000132 NTTP->getDepth(),
133 NTTP->getPosition(), 0,
134 T,
135 TInfo,
136 ExpandedTypes.data(),
137 ExpandedTypes.size(),
138 ExpandedTInfos.data());
139 } else {
140 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000141 SourceLocation(),
142 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000143 NTTP->getDepth(),
144 NTTP->getPosition(), 0,
145 T,
146 NTTP->isParameterPack(),
147 TInfo);
148 }
149 CanonParams.push_back(Param);
150
151 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000152 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
153 cast<TemplateTemplateParmDecl>(*P)));
154 }
155
156 TemplateTemplateParmDecl *CanonTTP
157 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
158 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000159 TTP->getPosition(),
160 TTP->isParameterPack(),
161 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000162 TemplateParameterList::Create(*this, SourceLocation(),
163 SourceLocation(),
164 CanonParams.data(),
165 CanonParams.size(),
166 SourceLocation()));
167
168 // Get the new insert position for the node we care about.
169 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
170 assert(Canonical == 0 && "Shouldn't be in the map!");
171 (void)Canonical;
172
173 // Create the canonical template template parameter entry.
174 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
175 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
176 return CanonTTP;
177}
178
Charles Davis53c59df2010-08-16 03:33:14 +0000179CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000180 if (!LangOpts.CPlusPlus) return 0;
181
Charles Davis6bcb07a2010-08-19 02:18:14 +0000182 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000183 case CXXABI_ARM:
184 return CreateARMCXXABI(*this);
185 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000186 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000187 case CXXABI_Microsoft:
188 return CreateMicrosoftCXXABI(*this);
189 }
John McCall86353412010-08-21 22:46:04 +0000190 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000191}
192
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000193static const LangAS::Map &getAddressSpaceMap(const TargetInfo &T,
194 const LangOptions &LOpts) {
195 if (LOpts.FakeAddressSpaceMap) {
196 // The fake address space map must have a distinct entry for each
197 // language-specific address space.
198 static const unsigned FakeAddrSpaceMap[] = {
199 1, // opencl_global
200 2, // opencl_local
201 3 // opencl_constant
202 };
203 return FakeAddrSpaceMap;
204 } else {
205 return T.getAddressSpaceMap();
206 }
207}
208
Chris Lattner465fa322008-10-05 17:34:18 +0000209ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000210 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000211 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000212 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000213 unsigned size_reserve) :
Sebastian Redl31ad7542011-03-13 17:09:40 +0000214 FunctionProtoTypes(this_()),
John McCall773cc982010-06-11 11:07:21 +0000215 TemplateSpecializationTypes(this_()),
216 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000217 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
218 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stumpa4de80b2009-07-28 02:25:19 +0000219 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stumpe1b19ba2009-10-22 00:49:09 +0000220 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +0000221 cudaConfigureCallDecl(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000222 NullTypeSourceInfo(QualType()),
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000223 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
224 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000225 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000226 BuiltinInfo(builtins),
227 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000228 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000229 LastSDM(0, 0),
John McCall147d0212011-02-22 22:38:33 +0000230 UniqueBlockByRefTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000231 ObjCIdRedefinitionType = QualType();
232 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000233 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000234 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000235 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000236 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000237}
238
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000239ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000240 // Release the DenseMaps associated with DeclContext objects.
241 // FIXME: Is this the ideal solution?
242 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000243
Douglas Gregor5b11d492010-07-25 17:53:33 +0000244 // Call all of the deallocation functions.
245 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
246 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000247
Douglas Gregor832940b2010-03-02 23:58:15 +0000248 // Release all of the memory associated with overridden C++ methods.
249 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
250 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
251 OM != OMEnd; ++OM)
252 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000253
Ted Kremenek076baeb2010-06-08 23:00:58 +0000254 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000255 // because they can contain DenseMaps.
256 for (llvm::DenseMap<const ObjCContainerDecl*,
257 const ASTRecordLayout*>::iterator
258 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
259 // Increment in loop to prevent using deallocated memory.
260 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
261 R->Destroy(*this);
262
Ted Kremenek076baeb2010-06-08 23:00:58 +0000263 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
264 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
265 // Increment in loop to prevent using deallocated memory.
266 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
267 R->Destroy(*this);
268 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000269
270 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
271 AEnd = DeclAttrs.end();
272 A != AEnd; ++A)
273 A->second->~AttrVec();
274}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000275
Douglas Gregor1a809332010-05-23 18:26:36 +0000276void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
277 Deallocations.push_back(std::make_pair(Callback, Data));
278}
279
Mike Stump11289f42009-09-09 15:08:12 +0000280void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000281ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
282 ExternalSource.reset(Source.take());
283}
284
Chris Lattner4eb445d2007-01-26 01:27:23 +0000285void ASTContext::PrintStats() const {
286 fprintf(stderr, "*** AST Context Stats:\n");
287 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000288
Douglas Gregora30d0462009-05-26 14:40:08 +0000289 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000290#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000291#define ABSTRACT_TYPE(Name, Parent)
292#include "clang/AST/TypeNodes.def"
293 0 // Extra
294 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000295
Chris Lattner4eb445d2007-01-26 01:27:23 +0000296 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
297 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000298 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000299 }
300
Douglas Gregora30d0462009-05-26 14:40:08 +0000301 unsigned Idx = 0;
302 unsigned TotalBytes = 0;
303#define TYPE(Name, Parent) \
304 if (counts[Idx]) \
305 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
306 TotalBytes += counts[Idx] * sizeof(Name##Type); \
307 ++Idx;
308#define ABSTRACT_TYPE(Name, Parent)
309#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000310
Douglas Gregora30d0462009-05-26 14:40:08 +0000311 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000312
Douglas Gregor7454c562010-07-02 20:37:36 +0000313 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000314 fprintf(stderr, " %u/%u implicit default constructors created\n",
315 NumImplicitDefaultConstructorsDeclared,
316 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000317 fprintf(stderr, " %u/%u implicit copy constructors created\n",
318 NumImplicitCopyConstructorsDeclared,
319 NumImplicitCopyConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000320 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
321 NumImplicitCopyAssignmentOperatorsDeclared,
322 NumImplicitCopyAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000323 fprintf(stderr, " %u/%u implicit destructors created\n",
324 NumImplicitDestructorsDeclared, NumImplicitDestructors);
325
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000326 if (ExternalSource.get()) {
327 fprintf(stderr, "\n");
328 ExternalSource->PrintStats();
329 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000330
Douglas Gregor5b11d492010-07-25 17:53:33 +0000331 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000332}
333
334
John McCall48f2d582009-10-23 23:03:21 +0000335void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000336 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000337 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000338 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000339}
340
Chris Lattner970e54e2006-11-12 00:37:36 +0000341void ASTContext::InitBuiltinTypes() {
342 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000343
Chris Lattner970e54e2006-11-12 00:37:36 +0000344 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000345 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000346
Chris Lattner970e54e2006-11-12 00:37:36 +0000347 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000348 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000349 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000350 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000351 InitBuiltinType(CharTy, BuiltinType::Char_S);
352 else
353 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000354 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000355 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
356 InitBuiltinType(ShortTy, BuiltinType::Short);
357 InitBuiltinType(IntTy, BuiltinType::Int);
358 InitBuiltinType(LongTy, BuiltinType::Long);
359 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000360
Chris Lattner970e54e2006-11-12 00:37:36 +0000361 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000362 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
363 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
364 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
365 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
366 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000367
Chris Lattner970e54e2006-11-12 00:37:36 +0000368 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000369 InitBuiltinType(FloatTy, BuiltinType::Float);
370 InitBuiltinType(DoubleTy, BuiltinType::Double);
371 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000372
Chris Lattnerf122cef2009-04-30 02:43:43 +0000373 // GNU extension, 128-bit integers.
374 InitBuiltinType(Int128Ty, BuiltinType::Int128);
375 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
376
Chris Lattnerad3467e2010-12-25 23:25:43 +0000377 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
378 if (!LangOpts.ShortWChar)
379 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
380 else // -fshort-wchar makes wchar_t be unsigned.
381 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
382 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000383 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000384
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000385 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
386 InitBuiltinType(Char16Ty, BuiltinType::Char16);
387 else // C99
388 Char16Ty = getFromTargetType(Target.getChar16Type());
389
390 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
391 InitBuiltinType(Char32Ty, BuiltinType::Char32);
392 else // C99
393 Char32Ty = getFromTargetType(Target.getChar32Type());
394
Douglas Gregor4619e432008-12-05 23:32:09 +0000395 // Placeholder type for type-dependent expressions whose type is
396 // completely unknown. No code should ever check a type against
397 // DependentTy and users should never see it; however, it is here to
398 // help diagnose failures to properly check for type-dependent
399 // expressions.
400 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000401
John McCall36e7fe32010-10-12 00:20:44 +0000402 // Placeholder type for functions.
403 InitBuiltinType(OverloadTy, BuiltinType::Overload);
404
John McCall31996342011-04-07 08:22:57 +0000405 // "any" type; useful for debugger-like clients.
406 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
407
Chris Lattner970e54e2006-11-12 00:37:36 +0000408 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000409 FloatComplexTy = getComplexType(FloatTy);
410 DoubleComplexTy = getComplexType(DoubleTy);
411 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000412
Steve Naroff66e9f332007-10-15 14:41:52 +0000413 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000414
Steve Naroff1329fa02009-07-15 18:40:39 +0000415 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
416 ObjCIdTypedefType = QualType();
417 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000418 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000419
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000420 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000421 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
422 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000423 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000424
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000425 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000426
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000427 // void * type
428 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000429
430 // nullptr type (C++0x 2.14.7)
431 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000432}
433
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000434Diagnostic &ASTContext::getDiagnostics() const {
435 return SourceMgr.getDiagnostics();
436}
437
Douglas Gregor561eceb2010-08-30 16:49:28 +0000438AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
439 AttrVec *&Result = DeclAttrs[D];
440 if (!Result) {
441 void *Mem = Allocate(sizeof(AttrVec));
442 Result = new (Mem) AttrVec;
443 }
444
445 return *Result;
446}
447
448/// \brief Erase the attributes corresponding to the given declaration.
449void ASTContext::eraseDeclAttrs(const Decl *D) {
450 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
451 if (Pos != DeclAttrs.end()) {
452 Pos->second->~AttrVec();
453 DeclAttrs.erase(Pos);
454 }
455}
456
Douglas Gregor86d142a2009-10-08 07:24:58 +0000457MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000458ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000459 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000460 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000461 = InstantiatedFromStaticDataMember.find(Var);
462 if (Pos == InstantiatedFromStaticDataMember.end())
463 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000464
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000465 return Pos->second;
466}
467
Mike Stump11289f42009-09-09 15:08:12 +0000468void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000469ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000470 TemplateSpecializationKind TSK,
471 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000472 assert(Inst->isStaticDataMember() && "Not a static data member");
473 assert(Tmpl->isStaticDataMember() && "Not a static data member");
474 assert(!InstantiatedFromStaticDataMember[Inst] &&
475 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000476 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000477 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000478}
479
John McCalle61f2ba2009-11-18 02:36:19 +0000480NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000481ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000482 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000483 = InstantiatedFromUsingDecl.find(UUD);
484 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000485 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000486
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000487 return Pos->second;
488}
489
490void
John McCallb96ec562009-12-04 22:46:56 +0000491ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
492 assert((isa<UsingDecl>(Pattern) ||
493 isa<UnresolvedUsingValueDecl>(Pattern) ||
494 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
495 "pattern decl is not a using decl");
496 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
497 InstantiatedFromUsingDecl[Inst] = Pattern;
498}
499
500UsingShadowDecl *
501ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
502 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
503 = InstantiatedFromUsingShadowDecl.find(Inst);
504 if (Pos == InstantiatedFromUsingShadowDecl.end())
505 return 0;
506
507 return Pos->second;
508}
509
510void
511ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
512 UsingShadowDecl *Pattern) {
513 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
514 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000515}
516
Anders Carlsson5da84842009-09-01 04:26:58 +0000517FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
518 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
519 = InstantiatedFromUnnamedFieldDecl.find(Field);
520 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
521 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000522
Anders Carlsson5da84842009-09-01 04:26:58 +0000523 return Pos->second;
524}
525
526void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
527 FieldDecl *Tmpl) {
528 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
529 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
530 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
531 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000532
Anders Carlsson5da84842009-09-01 04:26:58 +0000533 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
534}
535
Douglas Gregor832940b2010-03-02 23:58:15 +0000536ASTContext::overridden_cxx_method_iterator
537ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
538 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
539 = OverriddenMethods.find(Method);
540 if (Pos == OverriddenMethods.end())
541 return 0;
542
543 return Pos->second.begin();
544}
545
546ASTContext::overridden_cxx_method_iterator
547ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
548 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
549 = OverriddenMethods.find(Method);
550 if (Pos == OverriddenMethods.end())
551 return 0;
552
553 return Pos->second.end();
554}
555
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000556unsigned
557ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
558 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
559 = OverriddenMethods.find(Method);
560 if (Pos == OverriddenMethods.end())
561 return 0;
562
563 return Pos->second.size();
564}
565
Douglas Gregor832940b2010-03-02 23:58:15 +0000566void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
567 const CXXMethodDecl *Overridden) {
568 OverriddenMethods[Method].push_back(Overridden);
569}
570
Chris Lattner53cfe802007-07-18 17:52:12 +0000571//===----------------------------------------------------------------------===//
572// Type Sizing and Analysis
573//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000574
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000575/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
576/// scalar floating point type.
577const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000578 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000579 assert(BT && "Not a floating point type!");
580 switch (BT->getKind()) {
581 default: assert(0 && "Not a floating point type!");
582 case BuiltinType::Float: return Target.getFloatFormat();
583 case BuiltinType::Double: return Target.getDoubleFormat();
584 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
585 }
586}
587
Ken Dyck160146e2010-01-27 17:10:57 +0000588/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000589/// specified decl. Note that bitfields do not have a valid alignment, so
590/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000591/// If @p RefAsPointee, references are treated like their underlying type
592/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000593CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000594 unsigned Align = Target.getCharWidth();
595
John McCall94268702010-10-08 18:24:19 +0000596 bool UseAlignAttrOnly = false;
597 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
598 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000599
John McCall94268702010-10-08 18:24:19 +0000600 // __attribute__((aligned)) can increase or decrease alignment
601 // *except* on a struct or struct member, where it only increases
602 // alignment unless 'packed' is also specified.
603 //
604 // It is an error for [[align]] to decrease alignment, so we can
605 // ignore that possibility; Sema should diagnose it.
606 if (isa<FieldDecl>(D)) {
607 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
608 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
609 } else {
610 UseAlignAttrOnly = true;
611 }
612 }
613
John McCall4e819612011-01-20 07:57:12 +0000614 // If we're using the align attribute only, just ignore everything
615 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000616 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000617 // do nothing
618
John McCall94268702010-10-08 18:24:19 +0000619 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000620 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000621 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000622 if (RefAsPointee)
623 T = RT->getPointeeType();
624 else
625 T = getPointerType(RT->getPointeeType());
626 }
627 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000628 // Adjust alignments of declarations with array type by the
629 // large-array alignment on the target.
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000630 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000631 const ArrayType *arrayType;
632 if (MinWidth && (arrayType = getAsArrayType(T))) {
633 if (isa<VariableArrayType>(arrayType))
634 Align = std::max(Align, Target.getLargeArrayAlign());
635 else if (isa<ConstantArrayType>(arrayType) &&
636 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
637 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000638
John McCall33ddac02011-01-19 10:06:00 +0000639 // Walk through any array types while we're at it.
640 T = getBaseElementType(arrayType);
641 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000642 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
643 }
John McCall4e819612011-01-20 07:57:12 +0000644
645 // Fields can be subject to extra alignment constraints, like if
646 // the field is packed, the struct is packed, or the struct has a
647 // a max-field-alignment constraint (#pragma pack). So calculate
648 // the actual alignment of the field within the struct, and then
649 // (as we're expected to) constrain that by the alignment of the type.
650 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
651 // So calculate the alignment of the field.
652 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
653
654 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000655 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000656
657 // Use the GCD of that and the offset within the record.
658 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
659 if (offset > 0) {
660 // Alignment is always a power of 2, so the GCD will be a power of 2,
661 // which means we get to do this crazy thing instead of Euclid's.
662 uint64_t lowBitOfOffset = offset & (~offset + 1);
663 if (lowBitOfOffset < fieldAlign)
664 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
665 }
666
667 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000668 }
Chris Lattner68061312009-01-24 21:53:27 +0000669 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000670
Ken Dyckcc56c542011-01-15 18:38:59 +0000671 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000672}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000673
John McCall87fe5d52010-05-20 01:18:31 +0000674std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000675ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000676 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000677 return std::make_pair(toCharUnitsFromBits(Info.first),
678 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000679}
680
681std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000682ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000683 return getTypeInfoInChars(T.getTypePtr());
684}
685
Chris Lattner983a8bb2007-07-13 22:13:22 +0000686/// getTypeSize - Return the size of the specified type, in bits. This method
687/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000688///
689/// FIXME: Pointers into different addr spaces could have different sizes and
690/// alignment requirements: getPointerInfo should take an AddrSpace, this
691/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000692std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000693ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000694 uint64_t Width=0;
695 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000696 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000697#define TYPE(Class, Base)
698#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000699#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000700#define DEPENDENT_TYPE(Class, Base) case Type::Class:
701#include "clang/AST/TypeNodes.def"
Douglas Gregoref462e62009-04-30 17:32:17 +0000702 assert(false && "Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000703 break;
704
Chris Lattner355332d2007-07-13 22:27:08 +0000705 case Type::FunctionNoProto:
706 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000707 // GCC extension: alignof(function) = 32 bits
708 Width = 0;
709 Align = 32;
710 break;
711
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000712 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000713 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000714 Width = 0;
715 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
716 break;
717
Steve Naroff5c131802007-08-30 01:06:46 +0000718 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000719 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000720
Chris Lattner37e05872008-03-05 18:54:05 +0000721 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000722 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000723 Align = EltInfo.second;
724 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000725 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000726 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000727 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000728 const VectorType *VT = cast<VectorType>(T);
729 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
730 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000731 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000732 // If the alignment is not a power of 2, round up to the next power of 2.
733 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000734 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000735 Align = llvm::NextPowerOf2(Align);
736 Width = llvm::RoundUpToAlignment(Width, Align);
737 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000738 break;
739 }
Chris Lattner647fb222007-07-18 18:26:58 +0000740
Chris Lattner7570e9c2008-03-08 08:52:55 +0000741 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000742 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000743 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000744 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000745 // GCC extension: alignof(void) = 8 bits.
746 Width = 0;
747 Align = 8;
748 break;
749
Chris Lattner6a4f7452007-12-19 19:23:28 +0000750 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000751 Width = Target.getBoolWidth();
752 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000753 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000754 case BuiltinType::Char_S:
755 case BuiltinType::Char_U:
756 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000757 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000758 Width = Target.getCharWidth();
759 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000760 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000761 case BuiltinType::WChar_S:
762 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000763 Width = Target.getWCharWidth();
764 Align = Target.getWCharAlign();
765 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000766 case BuiltinType::Char16:
767 Width = Target.getChar16Width();
768 Align = Target.getChar16Align();
769 break;
770 case BuiltinType::Char32:
771 Width = Target.getChar32Width();
772 Align = Target.getChar32Align();
773 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000774 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000775 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000776 Width = Target.getShortWidth();
777 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000778 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000779 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000780 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000781 Width = Target.getIntWidth();
782 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000783 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000784 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000785 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000786 Width = Target.getLongWidth();
787 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000788 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000789 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000790 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000791 Width = Target.getLongLongWidth();
792 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000793 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000794 case BuiltinType::Int128:
795 case BuiltinType::UInt128:
796 Width = 128;
797 Align = 128; // int128_t is 128-bit aligned on all targets.
798 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000799 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000800 Width = Target.getFloatWidth();
801 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000802 break;
803 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000804 Width = Target.getDoubleWidth();
805 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000806 break;
807 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000808 Width = Target.getLongDoubleWidth();
809 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000810 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000811 case BuiltinType::NullPtr:
812 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
813 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000814 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000815 case BuiltinType::ObjCId:
816 case BuiltinType::ObjCClass:
817 case BuiltinType::ObjCSel:
818 Width = Target.getPointerWidth(0);
819 Align = Target.getPointerAlign(0);
820 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000821 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000822 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000823 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000824 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000825 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000826 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000827 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000828 unsigned AS = getTargetAddressSpace(
829 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff921a45c2008-09-24 15:05:44 +0000830 Width = Target.getPointerWidth(AS);
831 Align = Target.getPointerAlign(AS);
832 break;
833 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000834 case Type::LValueReference:
835 case Type::RValueReference: {
836 // alignof and sizeof should never enter this code path here, so we go
837 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000838 unsigned AS = getTargetAddressSpace(
839 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000840 Width = Target.getPointerWidth(AS);
841 Align = Target.getPointerAlign(AS);
842 break;
843 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000844 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000845 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000846 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000847 Align = Target.getPointerAlign(AS);
848 break;
849 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000850 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000851 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000852 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000853 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000854 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000855 Align = PtrDiffInfo.second;
856 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000857 }
Chris Lattner647fb222007-07-18 18:26:58 +0000858 case Type::Complex: {
859 // Complex types have the same alignment as their elements, but twice the
860 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000861 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000862 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000863 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000864 Align = EltInfo.second;
865 break;
866 }
John McCall8b07ec22010-05-15 11:32:37 +0000867 case Type::ObjCObject:
868 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000869 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000870 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000871 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000872 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000873 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000874 break;
875 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000876 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000877 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000878 const TagType *TT = cast<TagType>(T);
879
880 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner572100b2008-08-09 21:35:13 +0000881 Width = 1;
882 Align = 1;
883 break;
884 }
Mike Stump11289f42009-09-09 15:08:12 +0000885
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000886 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000887 return getTypeInfo(ET->getDecl()->getIntegerType());
888
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000889 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000890 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000891 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000892 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +0000893 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000894 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000895
Chris Lattner63d2b362009-10-22 05:17:15 +0000896 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000897 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
898 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000899
Richard Smith30482bc2011-02-20 03:19:35 +0000900 case Type::Auto: {
901 const AutoType *A = cast<AutoType>(T);
902 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +0000903 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +0000904 }
905
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000906 case Type::Paren:
907 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
908
Douglas Gregoref462e62009-04-30 17:32:17 +0000909 case Type::Typedef: {
910 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000911 std::pair<uint64_t, unsigned> Info
912 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +0000913 // If the typedef has an aligned attribute on it, it overrides any computed
914 // alignment we have. This violates the GCC documentation (which says that
915 // attribute(aligned) can only round up) but matches its implementation.
916 if (unsigned AttrAlign = Typedef->getMaxAlignment())
917 Align = AttrAlign;
918 else
919 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +0000920 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000921 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000922 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000923
924 case Type::TypeOfExpr:
925 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
926 .getTypePtr());
927
928 case Type::TypeOf:
929 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
930
Anders Carlsson81df7b82009-06-24 19:06:50 +0000931 case Type::Decltype:
932 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
933 .getTypePtr());
934
Abramo Bagnara6150c882010-05-11 21:36:43 +0000935 case Type::Elaborated:
936 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000937
John McCall81904512011-01-06 01:58:22 +0000938 case Type::Attributed:
939 return getTypeInfo(
940 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
941
Douglas Gregoref462e62009-04-30 17:32:17 +0000942 case Type::TemplateSpecialization:
Mike Stump11289f42009-09-09 15:08:12 +0000943 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +0000944 "Cannot request the size of a dependent type");
945 // FIXME: this is likely to be wrong once we support template
946 // aliases, since a template alias could refer to a typedef that
947 // has an __aligned__ attribute on it.
948 return getTypeInfo(getCanonicalType(T));
949 }
Mike Stump11289f42009-09-09 15:08:12 +0000950
Chris Lattner53cfe802007-07-18 17:52:12 +0000951 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +0000952 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +0000953}
954
Ken Dyckcc56c542011-01-15 18:38:59 +0000955/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
956CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
957 return CharUnits::fromQuantity(BitSize / getCharWidth());
958}
959
Ken Dyckb0fcc592011-02-11 01:54:29 +0000960/// toBits - Convert a size in characters to a size in characters.
961int64_t ASTContext::toBits(CharUnits CharSize) const {
962 return CharSize.getQuantity() * getCharWidth();
963}
964
Ken Dyck8c89d592009-12-22 14:23:30 +0000965/// getTypeSizeInChars - Return the size of the specified type, in characters.
966/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000967CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000968 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000969}
Jay Foad39c79802011-01-12 09:06:06 +0000970CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000971 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +0000972}
973
Ken Dycka6046ab2010-01-26 17:25:18 +0000974/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +0000975/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +0000976CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000977 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000978}
Jay Foad39c79802011-01-12 09:06:06 +0000979CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +0000980 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +0000981}
982
Chris Lattnera3402cd2009-01-27 18:08:34 +0000983/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
984/// type for the current target in bits. This can be different than the ABI
985/// alignment in cases where it is beneficial for performance to overalign
986/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +0000987unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +0000988 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +0000989
990 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +0000991 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +0000992 T = CT->getElementType().getTypePtr();
993 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
994 T->isSpecificBuiltinType(BuiltinType::LongLong))
995 return std::max(ABIAlign, (unsigned)getTypeSize(T));
996
Chris Lattnera3402cd2009-01-27 18:08:34 +0000997 return ABIAlign;
998}
999
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001000/// ShallowCollectObjCIvars -
1001/// Collect all ivars, including those synthesized, in the current class.
1002///
1003void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +00001004 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001005 // FIXME. This need be removed but there are two many places which
1006 // assume const-ness of ObjCInterfaceDecl
1007 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1008 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1009 Iv= Iv->getNextIvar())
1010 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001011}
1012
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001013/// DeepCollectObjCIvars -
1014/// This routine first collects all declared, but not synthesized, ivars in
1015/// super class and then collects all ivars, including those synthesized for
1016/// current class. This routine is used for implementation of current class
1017/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001018///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001019void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1020 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +00001021 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001022 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1023 DeepCollectObjCIvars(SuperClass, false, Ivars);
1024 if (!leafClass) {
1025 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1026 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001027 Ivars.push_back(*I);
1028 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001029 else
1030 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001031}
1032
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001033/// CollectInheritedProtocols - Collect all protocols in current class and
1034/// those inherited by it.
1035void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001036 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001037 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001038 // We can use protocol_iterator here instead of
1039 // all_referenced_protocol_iterator since we are walking all categories.
1040 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1041 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001042 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001043 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001044 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001045 PE = Proto->protocol_end(); P != PE; ++P) {
1046 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001047 CollectInheritedProtocols(*P, Protocols);
1048 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001049 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001050
1051 // Categories of this Interface.
1052 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1053 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1054 CollectInheritedProtocols(CDeclChain, Protocols);
1055 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1056 while (SD) {
1057 CollectInheritedProtocols(SD, Protocols);
1058 SD = SD->getSuperClass();
1059 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001060 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001061 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001062 PE = OC->protocol_end(); P != PE; ++P) {
1063 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001064 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-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 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001069 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001070 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1071 PE = OP->protocol_end(); P != PE; ++P) {
1072 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001073 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001074 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1075 PE = Proto->protocol_end(); P != PE; ++P)
1076 CollectInheritedProtocols(*P, Protocols);
1077 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001078 }
1079}
1080
Jay Foad39c79802011-01-12 09:06:06 +00001081unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001082 unsigned count = 0;
1083 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001084 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1085 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001086 count += CDecl->ivar_size();
1087
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001088 // Count ivar defined in this class's implementation. This
1089 // includes synthesized ivars.
1090 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001091 count += ImplDecl->ivar_size();
1092
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001093 return count;
1094}
1095
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001096/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1097ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1098 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1099 I = ObjCImpls.find(D);
1100 if (I != ObjCImpls.end())
1101 return cast<ObjCImplementationDecl>(I->second);
1102 return 0;
1103}
1104/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1105ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1106 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1107 I = ObjCImpls.find(D);
1108 if (I != ObjCImpls.end())
1109 return cast<ObjCCategoryImplDecl>(I->second);
1110 return 0;
1111}
1112
1113/// \brief Set the implementation of ObjCInterfaceDecl.
1114void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1115 ObjCImplementationDecl *ImplD) {
1116 assert(IFaceD && ImplD && "Passed null params");
1117 ObjCImpls[IFaceD] = ImplD;
1118}
1119/// \brief Set the implementation of ObjCCategoryDecl.
1120void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1121 ObjCCategoryImplDecl *ImplD) {
1122 assert(CatD && ImplD && "Passed null params");
1123 ObjCImpls[CatD] = ImplD;
1124}
1125
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001126/// \brief Get the copy initialization expression of VarDecl,or NULL if
1127/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001128Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001129 assert(VD && "Passed null params");
1130 assert(VD->hasAttr<BlocksAttr>() &&
1131 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001132 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001133 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001134 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1135}
1136
1137/// \brief Set the copy inialization expression of a block var decl.
1138void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1139 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001140 assert(VD->hasAttr<BlocksAttr>() &&
1141 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001142 BlockVarCopyInits[VD] = Init;
1143}
1144
John McCallbcd03502009-12-07 02:54:59 +00001145/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001146///
John McCallbcd03502009-12-07 02:54:59 +00001147/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001148/// the TypeLoc wrappers.
1149///
1150/// \param T the type that will be the basis for type source info. This type
1151/// should refer to how the declarator was written in source code, not to
1152/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001153TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001154 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001155 if (!DataSize)
1156 DataSize = TypeLoc::getFullDataSizeForType(T);
1157 else
1158 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001159 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001160
John McCallbcd03502009-12-07 02:54:59 +00001161 TypeSourceInfo *TInfo =
1162 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1163 new (TInfo) TypeSourceInfo(T);
1164 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001165}
1166
John McCallbcd03502009-12-07 02:54:59 +00001167TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001168 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001169 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001170 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001171 return DI;
1172}
1173
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001174const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001175ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001176 return getObjCLayout(D, 0);
1177}
1178
1179const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001180ASTContext::getASTObjCImplementationLayout(
1181 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001182 return getObjCLayout(D->getClassInterface(), D);
1183}
1184
Chris Lattner983a8bb2007-07-13 22:13:22 +00001185//===----------------------------------------------------------------------===//
1186// Type creation/memoization methods
1187//===----------------------------------------------------------------------===//
1188
Jay Foad39c79802011-01-12 09:06:06 +00001189QualType
John McCall33ddac02011-01-19 10:06:00 +00001190ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1191 unsigned fastQuals = quals.getFastQualifiers();
1192 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001193
1194 // Check if we've already instantiated this type.
1195 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001196 ExtQuals::Profile(ID, baseType, quals);
1197 void *insertPos = 0;
1198 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1199 assert(eq->getQualifiers() == quals);
1200 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001201 }
1202
John McCall33ddac02011-01-19 10:06:00 +00001203 // If the base type is not canonical, make the appropriate canonical type.
1204 QualType canon;
1205 if (!baseType->isCanonicalUnqualified()) {
1206 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1207 canonSplit.second.addConsistentQualifiers(quals);
1208 canon = getExtQualType(canonSplit.first, canonSplit.second);
1209
1210 // Re-find the insert position.
1211 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1212 }
1213
1214 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1215 ExtQualNodes.InsertNode(eq, insertPos);
1216 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001217}
1218
Jay Foad39c79802011-01-12 09:06:06 +00001219QualType
1220ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001221 QualType CanT = getCanonicalType(T);
1222 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001223 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001224
John McCall8ccfcb52009-09-24 19:53:00 +00001225 // If we are composing extended qualifiers together, merge together
1226 // into one ExtQuals node.
1227 QualifierCollector Quals;
1228 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001229
John McCall8ccfcb52009-09-24 19:53:00 +00001230 // If this type already has an address space specified, it cannot get
1231 // another one.
1232 assert(!Quals.hasAddressSpace() &&
1233 "Type cannot be in multiple addr spaces!");
1234 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001235
John McCall8ccfcb52009-09-24 19:53:00 +00001236 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001237}
1238
Chris Lattnerd60183d2009-02-18 22:53:11 +00001239QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001240 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001241 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001242 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001243 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001244
John McCall53fa7142010-12-24 02:08:15 +00001245 if (const PointerType *ptr = T->getAs<PointerType>()) {
1246 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001247 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001248 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1249 return getPointerType(ResultType);
1250 }
1251 }
Mike Stump11289f42009-09-09 15:08:12 +00001252
John McCall8ccfcb52009-09-24 19:53:00 +00001253 // If we are composing extended qualifiers together, merge together
1254 // into one ExtQuals node.
1255 QualifierCollector Quals;
1256 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001257
John McCall8ccfcb52009-09-24 19:53:00 +00001258 // If this type already has an ObjCGC specified, it cannot get
1259 // another one.
1260 assert(!Quals.hasObjCGCAttr() &&
1261 "Type cannot have multiple ObjCGCs!");
1262 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001263
John McCall8ccfcb52009-09-24 19:53:00 +00001264 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001265}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001266
John McCall4f5019e2010-12-19 02:44:49 +00001267const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1268 FunctionType::ExtInfo Info) {
1269 if (T->getExtInfo() == Info)
1270 return T;
1271
1272 QualType Result;
1273 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1274 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1275 } else {
1276 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1277 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1278 EPI.ExtInfo = Info;
1279 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1280 FPT->getNumArgs(), EPI);
1281 }
1282
1283 return cast<FunctionType>(Result.getTypePtr());
1284}
1285
Chris Lattnerc6395932007-06-22 20:56:16 +00001286/// getComplexType - Return the uniqued reference to the type for a complex
1287/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001288QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001289 // Unique pointers, to guarantee there is only one pointer of a particular
1290 // structure.
1291 llvm::FoldingSetNodeID ID;
1292 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001293
Chris Lattnerc6395932007-06-22 20:56:16 +00001294 void *InsertPos = 0;
1295 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1296 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001297
Chris Lattnerc6395932007-06-22 20:56:16 +00001298 // If the pointee type isn't canonical, this won't be a canonical type either,
1299 // so fill in the canonical type field.
1300 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001301 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001302 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001303
Chris Lattnerc6395932007-06-22 20:56:16 +00001304 // Get the new insert position for the node we care about.
1305 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001306 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001307 }
John McCall90d1c2d2009-09-24 23:30:46 +00001308 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001309 Types.push_back(New);
1310 ComplexTypes.InsertNode(New, InsertPos);
1311 return QualType(New, 0);
1312}
1313
Chris Lattner970e54e2006-11-12 00:37:36 +00001314/// getPointerType - Return the uniqued reference to the type for a pointer to
1315/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001316QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001317 // Unique pointers, to guarantee there is only one pointer of a particular
1318 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001319 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001320 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001321
Chris Lattner67521df2007-01-27 01:29:36 +00001322 void *InsertPos = 0;
1323 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001324 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001325
Chris Lattner7ccecb92006-11-12 08:50:50 +00001326 // If the pointee type isn't canonical, this won't be a canonical type either,
1327 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001328 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001329 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001330 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001331
Chris Lattner67521df2007-01-27 01:29:36 +00001332 // Get the new insert position for the node we care about.
1333 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001334 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001335 }
John McCall90d1c2d2009-09-24 23:30:46 +00001336 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001337 Types.push_back(New);
1338 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001339 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001340}
1341
Mike Stump11289f42009-09-09 15:08:12 +00001342/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001343/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001344QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001345 assert(T->isFunctionType() && "block of function types only");
1346 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001347 // structure.
1348 llvm::FoldingSetNodeID ID;
1349 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001350
Steve Naroffec33ed92008-08-27 16:04:49 +00001351 void *InsertPos = 0;
1352 if (BlockPointerType *PT =
1353 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1354 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001355
1356 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001357 // type either so fill in the canonical type field.
1358 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001359 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001360 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001361
Steve Naroffec33ed92008-08-27 16:04:49 +00001362 // Get the new insert position for the node we care about.
1363 BlockPointerType *NewIP =
1364 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001365 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001366 }
John McCall90d1c2d2009-09-24 23:30:46 +00001367 BlockPointerType *New
1368 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001369 Types.push_back(New);
1370 BlockPointerTypes.InsertNode(New, InsertPos);
1371 return QualType(New, 0);
1372}
1373
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001374/// getLValueReferenceType - Return the uniqued reference to the type for an
1375/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001376QualType
1377ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Bill Wendling3708c182007-05-27 10:15:43 +00001378 // Unique pointers, to guarantee there is only one pointer of a particular
1379 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001380 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001381 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001382
1383 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001384 if (LValueReferenceType *RT =
1385 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001386 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001387
John McCallfc93cf92009-10-22 22:37:11 +00001388 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1389
Bill Wendling3708c182007-05-27 10:15:43 +00001390 // If the referencee type isn't canonical, this won't be a canonical type
1391 // either, so fill in the canonical type field.
1392 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001393 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1394 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1395 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001396
Bill Wendling3708c182007-05-27 10:15:43 +00001397 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001398 LValueReferenceType *NewIP =
1399 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001400 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001401 }
1402
John McCall90d1c2d2009-09-24 23:30:46 +00001403 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001404 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1405 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001406 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001407 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001408
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001409 return QualType(New, 0);
1410}
1411
1412/// getRValueReferenceType - Return the uniqued reference to the type for an
1413/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001414QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001415 // Unique pointers, to guarantee there is only one pointer of a particular
1416 // structure.
1417 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001418 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001419
1420 void *InsertPos = 0;
1421 if (RValueReferenceType *RT =
1422 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1423 return QualType(RT, 0);
1424
John McCallfc93cf92009-10-22 22:37:11 +00001425 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1426
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001427 // If the referencee type isn't canonical, this won't be a canonical type
1428 // either, so fill in the canonical type field.
1429 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001430 if (InnerRef || !T.isCanonical()) {
1431 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1432 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001433
1434 // Get the new insert position for the node we care about.
1435 RValueReferenceType *NewIP =
1436 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001437 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001438 }
1439
John McCall90d1c2d2009-09-24 23:30:46 +00001440 RValueReferenceType *New
1441 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001442 Types.push_back(New);
1443 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001444 return QualType(New, 0);
1445}
1446
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001447/// getMemberPointerType - Return the uniqued reference to the type for a
1448/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001449QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001450 // Unique pointers, to guarantee there is only one pointer of a particular
1451 // structure.
1452 llvm::FoldingSetNodeID ID;
1453 MemberPointerType::Profile(ID, T, Cls);
1454
1455 void *InsertPos = 0;
1456 if (MemberPointerType *PT =
1457 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1458 return QualType(PT, 0);
1459
1460 // If the pointee or class type isn't canonical, this won't be a canonical
1461 // type either, so fill in the canonical type field.
1462 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001463 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001464 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1465
1466 // Get the new insert position for the node we care about.
1467 MemberPointerType *NewIP =
1468 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001469 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001470 }
John McCall90d1c2d2009-09-24 23:30:46 +00001471 MemberPointerType *New
1472 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001473 Types.push_back(New);
1474 MemberPointerTypes.InsertNode(New, InsertPos);
1475 return QualType(New, 0);
1476}
1477
Mike Stump11289f42009-09-09 15:08:12 +00001478/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001479/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001480QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001481 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001482 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001483 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001484 assert((EltTy->isDependentType() ||
1485 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001486 "Constant array of VLAs is illegal!");
1487
Chris Lattnere2df3f92009-05-13 04:12:56 +00001488 // Convert the array size into a canonical width matching the pointer size for
1489 // the target.
1490 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001491 ArySize =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001492 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001493
Chris Lattner23b7eb62007-06-15 23:05:46 +00001494 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001495 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001496
Chris Lattner36f8e652007-01-27 08:31:04 +00001497 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001498 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001499 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001500 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001501
John McCall33ddac02011-01-19 10:06:00 +00001502 // If the element type isn't canonical or has qualifiers, this won't
1503 // be a canonical type either, so fill in the canonical type field.
1504 QualType Canon;
1505 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1506 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1507 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001508 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001509 Canon = getQualifiedType(Canon, canonSplit.second);
1510
Chris Lattner36f8e652007-01-27 08:31:04 +00001511 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001512 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001513 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001514 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001515 }
Mike Stump11289f42009-09-09 15:08:12 +00001516
John McCall90d1c2d2009-09-24 23:30:46 +00001517 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001518 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001519 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001520 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001521 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001522}
1523
John McCall06549462011-01-18 08:40:38 +00001524/// getVariableArrayDecayedType - Turns the given type, which may be
1525/// variably-modified, into the corresponding type with all the known
1526/// sizes replaced with [*].
1527QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1528 // Vastly most common case.
1529 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001530
John McCall06549462011-01-18 08:40:38 +00001531 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001532
John McCall06549462011-01-18 08:40:38 +00001533 SplitQualType split = type.getSplitDesugaredType();
1534 const Type *ty = split.first;
1535 switch (ty->getTypeClass()) {
1536#define TYPE(Class, Base)
1537#define ABSTRACT_TYPE(Class, Base)
1538#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1539#include "clang/AST/TypeNodes.def"
1540 llvm_unreachable("didn't desugar past all non-canonical types?");
1541
1542 // These types should never be variably-modified.
1543 case Type::Builtin:
1544 case Type::Complex:
1545 case Type::Vector:
1546 case Type::ExtVector:
1547 case Type::DependentSizedExtVector:
1548 case Type::ObjCObject:
1549 case Type::ObjCInterface:
1550 case Type::ObjCObjectPointer:
1551 case Type::Record:
1552 case Type::Enum:
1553 case Type::UnresolvedUsing:
1554 case Type::TypeOfExpr:
1555 case Type::TypeOf:
1556 case Type::Decltype:
1557 case Type::DependentName:
1558 case Type::InjectedClassName:
1559 case Type::TemplateSpecialization:
1560 case Type::DependentTemplateSpecialization:
1561 case Type::TemplateTypeParm:
1562 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001563 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001564 case Type::PackExpansion:
1565 llvm_unreachable("type should never be variably-modified");
1566
1567 // These types can be variably-modified but should never need to
1568 // further decay.
1569 case Type::FunctionNoProto:
1570 case Type::FunctionProto:
1571 case Type::BlockPointer:
1572 case Type::MemberPointer:
1573 return type;
1574
1575 // These types can be variably-modified. All these modifications
1576 // preserve structure except as noted by comments.
1577 // TODO: if we ever care about optimizing VLAs, there are no-op
1578 // optimizations available here.
1579 case Type::Pointer:
1580 result = getPointerType(getVariableArrayDecayedType(
1581 cast<PointerType>(ty)->getPointeeType()));
1582 break;
1583
1584 case Type::LValueReference: {
1585 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1586 result = getLValueReferenceType(
1587 getVariableArrayDecayedType(lv->getPointeeType()),
1588 lv->isSpelledAsLValue());
1589 break;
1590 }
1591
1592 case Type::RValueReference: {
1593 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1594 result = getRValueReferenceType(
1595 getVariableArrayDecayedType(lv->getPointeeType()));
1596 break;
1597 }
1598
1599 case Type::ConstantArray: {
1600 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1601 result = getConstantArrayType(
1602 getVariableArrayDecayedType(cat->getElementType()),
1603 cat->getSize(),
1604 cat->getSizeModifier(),
1605 cat->getIndexTypeCVRQualifiers());
1606 break;
1607 }
1608
1609 case Type::DependentSizedArray: {
1610 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1611 result = getDependentSizedArrayType(
1612 getVariableArrayDecayedType(dat->getElementType()),
1613 dat->getSizeExpr(),
1614 dat->getSizeModifier(),
1615 dat->getIndexTypeCVRQualifiers(),
1616 dat->getBracketsRange());
1617 break;
1618 }
1619
1620 // Turn incomplete types into [*] types.
1621 case Type::IncompleteArray: {
1622 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1623 result = getVariableArrayType(
1624 getVariableArrayDecayedType(iat->getElementType()),
1625 /*size*/ 0,
1626 ArrayType::Normal,
1627 iat->getIndexTypeCVRQualifiers(),
1628 SourceRange());
1629 break;
1630 }
1631
1632 // Turn VLA types into [*] types.
1633 case Type::VariableArray: {
1634 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1635 result = getVariableArrayType(
1636 getVariableArrayDecayedType(vat->getElementType()),
1637 /*size*/ 0,
1638 ArrayType::Star,
1639 vat->getIndexTypeCVRQualifiers(),
1640 vat->getBracketsRange());
1641 break;
1642 }
1643 }
1644
1645 // Apply the top-level qualifiers from the original.
1646 return getQualifiedType(result, split.second);
1647}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001648
Steve Naroffcadebd02007-08-30 18:14:25 +00001649/// getVariableArrayType - Returns a non-unique reference to the type for a
1650/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001651QualType ASTContext::getVariableArrayType(QualType EltTy,
1652 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001653 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001654 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001655 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001656 // Since we don't unique expressions, it isn't possible to unique VLA's
1657 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001658 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001659
John McCall33ddac02011-01-19 10:06:00 +00001660 // Be sure to pull qualifiers off the element type.
1661 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1662 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1663 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001664 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001665 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001666 }
1667
John McCall90d1c2d2009-09-24 23:30:46 +00001668 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001669 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001670
1671 VariableArrayTypes.push_back(New);
1672 Types.push_back(New);
1673 return QualType(New, 0);
1674}
1675
Douglas Gregor4619e432008-12-05 23:32:09 +00001676/// getDependentSizedArrayType - Returns a non-unique reference to
1677/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001678/// type.
John McCall33ddac02011-01-19 10:06:00 +00001679QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1680 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001681 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001682 unsigned elementTypeQuals,
1683 SourceRange brackets) const {
1684 assert((!numElements || numElements->isTypeDependent() ||
1685 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001686 "Size must be type- or value-dependent!");
1687
John McCall33ddac02011-01-19 10:06:00 +00001688 // Dependently-sized array types that do not have a specified number
1689 // of elements will have their sizes deduced from a dependent
1690 // initializer. We do no canonicalization here at all, which is okay
1691 // because they can't be used in most locations.
1692 if (!numElements) {
1693 DependentSizedArrayType *newType
1694 = new (*this, TypeAlignment)
1695 DependentSizedArrayType(*this, elementType, QualType(),
1696 numElements, ASM, elementTypeQuals,
1697 brackets);
1698 Types.push_back(newType);
1699 return QualType(newType, 0);
1700 }
1701
1702 // Otherwise, we actually build a new type every time, but we
1703 // also build a canonical type.
1704
1705 SplitQualType canonElementType = getCanonicalType(elementType).split();
1706
1707 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001708 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001709 DependentSizedArrayType::Profile(ID, *this,
1710 QualType(canonElementType.first, 0),
1711 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001712
John McCall33ddac02011-01-19 10:06:00 +00001713 // Look for an existing type with these properties.
1714 DependentSizedArrayType *canonTy =
1715 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001716
John McCall33ddac02011-01-19 10:06:00 +00001717 // If we don't have one, build one.
1718 if (!canonTy) {
1719 canonTy = new (*this, TypeAlignment)
1720 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1721 QualType(), numElements, ASM, elementTypeQuals,
1722 brackets);
1723 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1724 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001725 }
1726
John McCall33ddac02011-01-19 10:06:00 +00001727 // Apply qualifiers from the element type to the array.
1728 QualType canon = getQualifiedType(QualType(canonTy,0),
1729 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001730
John McCall33ddac02011-01-19 10:06:00 +00001731 // If we didn't need extra canonicalization for the element type,
1732 // then just use that as our result.
1733 if (QualType(canonElementType.first, 0) == elementType)
1734 return canon;
1735
1736 // Otherwise, we need to build a type which follows the spelling
1737 // of the element type.
1738 DependentSizedArrayType *sugaredType
1739 = new (*this, TypeAlignment)
1740 DependentSizedArrayType(*this, elementType, canon, numElements,
1741 ASM, elementTypeQuals, brackets);
1742 Types.push_back(sugaredType);
1743 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001744}
1745
John McCall33ddac02011-01-19 10:06:00 +00001746QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001747 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001748 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001749 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001750 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001751
John McCall33ddac02011-01-19 10:06:00 +00001752 void *insertPos = 0;
1753 if (IncompleteArrayType *iat =
1754 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1755 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001756
1757 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001758 // either, so fill in the canonical type field. We also have to pull
1759 // qualifiers off the element type.
1760 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001761
John McCall33ddac02011-01-19 10:06:00 +00001762 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1763 SplitQualType canonSplit = getCanonicalType(elementType).split();
1764 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1765 ASM, elementTypeQuals);
1766 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001767
1768 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001769 IncompleteArrayType *existing =
1770 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1771 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001772 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001773
John McCall33ddac02011-01-19 10:06:00 +00001774 IncompleteArrayType *newType = new (*this, TypeAlignment)
1775 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001776
John McCall33ddac02011-01-19 10:06:00 +00001777 IncompleteArrayTypes.InsertNode(newType, insertPos);
1778 Types.push_back(newType);
1779 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001780}
1781
Steve Naroff91fcddb2007-07-18 18:00:27 +00001782/// getVectorType - Return the unique reference to a vector type of
1783/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001784QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001785 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001786 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001787
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001788 // Check if we've already instantiated a vector of this type.
1789 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001790 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001791
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001792 void *InsertPos = 0;
1793 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1794 return QualType(VTP, 0);
1795
1796 // If the element type isn't canonical, this won't be a canonical type either,
1797 // so fill in the canonical type field.
1798 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001799 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001800 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001801
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001802 // Get the new insert position for the node we care about.
1803 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001804 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001805 }
John McCall90d1c2d2009-09-24 23:30:46 +00001806 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001807 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001808 VectorTypes.InsertNode(New, InsertPos);
1809 Types.push_back(New);
1810 return QualType(New, 0);
1811}
1812
Nate Begemance4d7fc2008-04-18 23:10:10 +00001813/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001814/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001815QualType
1816ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall33ddac02011-01-19 10:06:00 +00001817 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001818
Steve Naroff91fcddb2007-07-18 18:00:27 +00001819 // Check if we've already instantiated a vector of this type.
1820 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001821 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001822 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001823 void *InsertPos = 0;
1824 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1825 return QualType(VTP, 0);
1826
1827 // If the element type isn't canonical, this won't be a canonical type either,
1828 // so fill in the canonical type field.
1829 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001830 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001831 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001832
Steve Naroff91fcddb2007-07-18 18:00:27 +00001833 // Get the new insert position for the node we care about.
1834 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001835 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001836 }
John McCall90d1c2d2009-09-24 23:30:46 +00001837 ExtVectorType *New = new (*this, TypeAlignment)
1838 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001839 VectorTypes.InsertNode(New, InsertPos);
1840 Types.push_back(New);
1841 return QualType(New, 0);
1842}
1843
Jay Foad39c79802011-01-12 09:06:06 +00001844QualType
1845ASTContext::getDependentSizedExtVectorType(QualType vecType,
1846 Expr *SizeExpr,
1847 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001848 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001849 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001850 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001851
Douglas Gregor352169a2009-07-31 03:54:25 +00001852 void *InsertPos = 0;
1853 DependentSizedExtVectorType *Canon
1854 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1855 DependentSizedExtVectorType *New;
1856 if (Canon) {
1857 // We already have a canonical version of this array type; use it as
1858 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001859 New = new (*this, TypeAlignment)
1860 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1861 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001862 } else {
1863 QualType CanonVecTy = getCanonicalType(vecType);
1864 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001865 New = new (*this, TypeAlignment)
1866 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1867 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001868
1869 DependentSizedExtVectorType *CanonCheck
1870 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1871 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1872 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001873 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1874 } else {
1875 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1876 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001877 New = new (*this, TypeAlignment)
1878 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001879 }
1880 }
Mike Stump11289f42009-09-09 15:08:12 +00001881
Douglas Gregor758a8692009-06-17 21:51:59 +00001882 Types.push_back(New);
1883 return QualType(New, 0);
1884}
1885
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001886/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001887///
Jay Foad39c79802011-01-12 09:06:06 +00001888QualType
1889ASTContext::getFunctionNoProtoType(QualType ResultTy,
1890 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00001891 const CallingConv DefaultCC = Info.getCC();
1892 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1893 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001894 // Unique functions, to guarantee there is only one function of a particular
1895 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001896 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001897 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001898
Chris Lattner47955de2007-01-27 08:37:20 +00001899 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001900 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001901 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001902 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001903
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001904 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001905 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001906 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001907 Canonical =
1908 getFunctionNoProtoType(getCanonicalType(ResultTy),
1909 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001910
Chris Lattner47955de2007-01-27 08:37:20 +00001911 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001912 FunctionNoProtoType *NewIP =
1913 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001914 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001915 }
Mike Stump11289f42009-09-09 15:08:12 +00001916
Roman Divacky65b88cd2011-03-01 17:40:53 +00001917 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00001918 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00001919 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00001920 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001921 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001922 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001923}
1924
1925/// getFunctionType - Return a normal function type with a typed argument
1926/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001927QualType
1928ASTContext::getFunctionType(QualType ResultTy,
1929 const QualType *ArgArray, unsigned NumArgs,
1930 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001931 // Unique functions, to guarantee there is only one function of a particular
1932 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001933 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00001934 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001935
1936 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001937 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001938 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001939 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001940
1941 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00001942 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001943 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001944 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001945 isCanonical = false;
1946
Roman Divacky65b88cd2011-03-01 17:40:53 +00001947 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
1948 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1949 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00001950
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001951 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001952 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001953 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00001954 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001955 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001956 CanonicalArgs.reserve(NumArgs);
1957 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00001958 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001959
John McCalldb40c7f2010-12-14 08:05:40 +00001960 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00001961 CanonicalEPI.ExceptionSpecType = EST_None;
1962 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00001963 CanonicalEPI.ExtInfo
1964 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1965
Chris Lattner76a00cf2008-04-06 22:59:24 +00001966 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00001967 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00001968 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001969
Chris Lattnerfd4de792007-01-27 01:15:32 +00001970 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001971 FunctionProtoType *NewIP =
1972 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001973 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001974 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001975
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001976 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00001977 // for two variable size arrays (for parameter and exception types) at the
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001978 // end of them. Instead of the exception types, there could be a noexcept
1979 // expression and a context pointer.
John McCalldb40c7f2010-12-14 08:05:40 +00001980 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001981 NumArgs * sizeof(QualType);
1982 if (EPI.ExceptionSpecType == EST_Dynamic)
1983 Size += EPI.NumExceptions * sizeof(QualType);
1984 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00001985 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001986 }
John McCalldb40c7f2010-12-14 08:05:40 +00001987 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00001988 FunctionProtoType::ExtProtoInfo newEPI = EPI;
1989 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00001990 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001991 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001992 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001993 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001994}
Chris Lattneref51c202006-11-10 07:17:23 +00001995
John McCalle78aac42010-03-10 03:28:59 +00001996#ifndef NDEBUG
1997static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1998 if (!isa<CXXRecordDecl>(D)) return false;
1999 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2000 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2001 return true;
2002 if (RD->getDescribedClassTemplate() &&
2003 !isa<ClassTemplateSpecializationDecl>(RD))
2004 return true;
2005 return false;
2006}
2007#endif
2008
2009/// getInjectedClassNameType - Return the unique reference to the
2010/// injected class name type for the specified templated declaration.
2011QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002012 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002013 assert(NeedsInjectedClassNameType(Decl));
2014 if (Decl->TypeForDecl) {
2015 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00002016 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00002017 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2018 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2019 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2020 } else {
John McCall424cec92011-01-19 06:33:43 +00002021 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002022 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002023 Decl->TypeForDecl = newType;
2024 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002025 }
2026 return QualType(Decl->TypeForDecl, 0);
2027}
2028
Douglas Gregor83a586e2008-04-13 21:07:44 +00002029/// getTypeDeclType - Return the unique reference to the type for the
2030/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002031QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002032 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002033 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002034
John McCall81e38502010-02-16 03:57:14 +00002035 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002036 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002037
John McCall96f0b5f2010-03-10 06:48:02 +00002038 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2039 "Template type parameter types are always available.");
2040
John McCall81e38502010-02-16 03:57:14 +00002041 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002042 assert(!Record->getPreviousDeclaration() &&
2043 "struct/union has previous declaration");
2044 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002045 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002046 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002047 assert(!Enum->getPreviousDeclaration() &&
2048 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002049 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002050 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002051 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002052 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2053 Decl->TypeForDecl = newType;
2054 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002055 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002056 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002057
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002058 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002059}
2060
Chris Lattner32d920b2007-01-26 02:01:53 +00002061/// getTypedefType - Return the unique reference to the type for the
Chris Lattnerd0342e52006-11-20 04:02:15 +00002062/// specified typename decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002063QualType
Jay Foad39c79802011-01-12 09:06:06 +00002064ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002065 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002066
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002067 if (Canonical.isNull())
2068 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002069 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002070 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002071 Decl->TypeForDecl = newType;
2072 Types.push_back(newType);
2073 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002074}
2075
Jay Foad39c79802011-01-12 09:06:06 +00002076QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002077 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2078
2079 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2080 if (PrevDecl->TypeForDecl)
2081 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2082
John McCall424cec92011-01-19 06:33:43 +00002083 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2084 Decl->TypeForDecl = newType;
2085 Types.push_back(newType);
2086 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002087}
2088
Jay Foad39c79802011-01-12 09:06:06 +00002089QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002090 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2091
2092 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2093 if (PrevDecl->TypeForDecl)
2094 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2095
John McCall424cec92011-01-19 06:33:43 +00002096 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2097 Decl->TypeForDecl = newType;
2098 Types.push_back(newType);
2099 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002100}
2101
John McCall81904512011-01-06 01:58:22 +00002102QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2103 QualType modifiedType,
2104 QualType equivalentType) {
2105 llvm::FoldingSetNodeID id;
2106 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2107
2108 void *insertPos = 0;
2109 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2110 if (type) return QualType(type, 0);
2111
2112 QualType canon = getCanonicalType(equivalentType);
2113 type = new (*this, TypeAlignment)
2114 AttributedType(canon, attrKind, modifiedType, equivalentType);
2115
2116 Types.push_back(type);
2117 AttributedTypes.InsertNode(type, insertPos);
2118
2119 return QualType(type, 0);
2120}
2121
2122
John McCallcebee162009-10-18 09:09:24 +00002123/// \brief Retrieve a substitution-result type.
2124QualType
2125ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002126 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002127 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002128 && "replacement types must always be canonical");
2129
2130 llvm::FoldingSetNodeID ID;
2131 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2132 void *InsertPos = 0;
2133 SubstTemplateTypeParmType *SubstParm
2134 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2135
2136 if (!SubstParm) {
2137 SubstParm = new (*this, TypeAlignment)
2138 SubstTemplateTypeParmType(Parm, Replacement);
2139 Types.push_back(SubstParm);
2140 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2141 }
2142
2143 return QualType(SubstParm, 0);
2144}
2145
Douglas Gregorada4b792011-01-14 02:55:32 +00002146/// \brief Retrieve a
2147QualType ASTContext::getSubstTemplateTypeParmPackType(
2148 const TemplateTypeParmType *Parm,
2149 const TemplateArgument &ArgPack) {
2150#ifndef NDEBUG
2151 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2152 PEnd = ArgPack.pack_end();
2153 P != PEnd; ++P) {
2154 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2155 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2156 }
2157#endif
2158
2159 llvm::FoldingSetNodeID ID;
2160 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2161 void *InsertPos = 0;
2162 if (SubstTemplateTypeParmPackType *SubstParm
2163 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2164 return QualType(SubstParm, 0);
2165
2166 QualType Canon;
2167 if (!Parm->isCanonicalUnqualified()) {
2168 Canon = getCanonicalType(QualType(Parm, 0));
2169 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2170 ArgPack);
2171 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2172 }
2173
2174 SubstTemplateTypeParmPackType *SubstParm
2175 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2176 ArgPack);
2177 Types.push_back(SubstParm);
2178 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2179 return QualType(SubstParm, 0);
2180}
2181
Douglas Gregoreff93e02009-02-05 23:33:38 +00002182/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002183/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002184/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002185QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002186 bool ParameterPack,
Jay Foad39c79802011-01-12 09:06:06 +00002187 IdentifierInfo *Name) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002188 llvm::FoldingSetNodeID ID;
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002189 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002190 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002191 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002192 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2193
2194 if (TypeParm)
2195 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002196
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002197 if (Name) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002198 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregor2ebcae12010-06-16 15:23:05 +00002199 TypeParm = new (*this, TypeAlignment)
2200 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002201
2202 TemplateTypeParmType *TypeCheck
2203 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2204 assert(!TypeCheck && "Template type parameter canonical type broken");
2205 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002206 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002207 TypeParm = new (*this, TypeAlignment)
2208 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002209
2210 Types.push_back(TypeParm);
2211 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2212
2213 return QualType(TypeParm, 0);
2214}
2215
John McCalle78aac42010-03-10 03:28:59 +00002216TypeSourceInfo *
2217ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2218 SourceLocation NameLoc,
2219 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002220 QualType CanonType) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002221 assert(!Name.getAsDependentTemplateName() &&
2222 "No dependent template names here!");
John McCalle78aac42010-03-10 03:28:59 +00002223 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2224
2225 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2226 TemplateSpecializationTypeLoc TL
2227 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2228 TL.setTemplateNameLoc(NameLoc);
2229 TL.setLAngleLoc(Args.getLAngleLoc());
2230 TL.setRAngleLoc(Args.getRAngleLoc());
2231 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2232 TL.setArgLocInfo(i, Args[i].getLocInfo());
2233 return DI;
2234}
2235
Mike Stump11289f42009-09-09 15:08:12 +00002236QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002237ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002238 const TemplateArgumentListInfo &Args,
Jay Foad39c79802011-01-12 09:06:06 +00002239 QualType Canon) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002240 assert(!Template.getAsDependentTemplateName() &&
2241 "No dependent template names here!");
2242
John McCall6b51f282009-11-23 01:53:49 +00002243 unsigned NumArgs = Args.size();
2244
John McCall0ad16662009-10-29 08:12:44 +00002245 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2246 ArgVec.reserve(NumArgs);
2247 for (unsigned i = 0; i != NumArgs; ++i)
2248 ArgVec.push_back(Args[i].getArgument());
2249
John McCall2408e322010-04-27 00:57:59 +00002250 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall30576cd2010-06-13 09:25:03 +00002251 Canon);
John McCall0ad16662009-10-29 08:12:44 +00002252}
2253
2254QualType
2255ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002256 const TemplateArgument *Args,
2257 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002258 QualType Canon) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002259 assert(!Template.getAsDependentTemplateName() &&
2260 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002261 // Look through qualified template names.
2262 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2263 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002264
Douglas Gregor15301382009-07-30 17:40:51 +00002265 if (!Canon.isNull())
2266 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002267 else
2268 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregord56a91e2009-02-26 22:19:44 +00002269
Douglas Gregora8e02e72009-07-28 23:00:59 +00002270 // Allocate the (non-canonical) template specialization type, but don't
2271 // try to unique it: these types typically have location information that
2272 // we don't unique and don't want to lose.
Mike Stump11289f42009-09-09 15:08:12 +00002273 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregorc40290e2009-03-09 23:48:35 +00002274 sizeof(TemplateArgument) * NumArgs),
John McCall90d1c2d2009-09-24 23:30:46 +00002275 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002276 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002277 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002278 Args, NumArgs,
Douglas Gregor00044172009-07-29 16:09:57 +00002279 Canon);
Mike Stump11289f42009-09-09 15:08:12 +00002280
Douglas Gregor8bf42052009-02-09 18:46:07 +00002281 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002282 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002283}
2284
Mike Stump11289f42009-09-09 15:08:12 +00002285QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002286ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2287 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002288 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002289 assert(!Template.getAsDependentTemplateName() &&
2290 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002291 // Look through qualified template names.
2292 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2293 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002294
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002295 // Build the canonical template specialization type.
2296 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2297 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2298 CanonArgs.reserve(NumArgs);
2299 for (unsigned I = 0; I != NumArgs; ++I)
2300 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2301
2302 // Determine whether this canonical template specialization type already
2303 // exists.
2304 llvm::FoldingSetNodeID ID;
2305 TemplateSpecializationType::Profile(ID, CanonTemplate,
2306 CanonArgs.data(), NumArgs, *this);
2307
2308 void *InsertPos = 0;
2309 TemplateSpecializationType *Spec
2310 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2311
2312 if (!Spec) {
2313 // Allocate a new canonical template specialization type.
2314 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2315 sizeof(TemplateArgument) * NumArgs),
2316 TypeAlignment);
2317 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2318 CanonArgs.data(), NumArgs,
2319 QualType());
2320 Types.push_back(Spec);
2321 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2322 }
2323
2324 assert(Spec->isDependentType() &&
2325 "Non-dependent template-id type must have a canonical type");
2326 return QualType(Spec, 0);
2327}
2328
2329QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002330ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2331 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002332 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002333 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002334 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002335
2336 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002337 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002338 if (T)
2339 return QualType(T, 0);
2340
Douglas Gregorc42075a2010-02-04 18:10:26 +00002341 QualType Canon = NamedType;
2342 if (!Canon.isCanonical()) {
2343 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002344 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2345 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002346 (void)CheckT;
2347 }
2348
Abramo Bagnara6150c882010-05-11 21:36:43 +00002349 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002350 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002351 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002352 return QualType(T, 0);
2353}
2354
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002355QualType
Jay Foad39c79802011-01-12 09:06:06 +00002356ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002357 llvm::FoldingSetNodeID ID;
2358 ParenType::Profile(ID, InnerType);
2359
2360 void *InsertPos = 0;
2361 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2362 if (T)
2363 return QualType(T, 0);
2364
2365 QualType Canon = InnerType;
2366 if (!Canon.isCanonical()) {
2367 Canon = getCanonicalType(InnerType);
2368 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2369 assert(!CheckT && "Paren canonical type broken");
2370 (void)CheckT;
2371 }
2372
2373 T = new (*this) ParenType(InnerType, Canon);
2374 Types.push_back(T);
2375 ParenTypes.InsertNode(T, InsertPos);
2376 return QualType(T, 0);
2377}
2378
Douglas Gregor02085352010-03-31 20:19:30 +00002379QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2380 NestedNameSpecifier *NNS,
2381 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002382 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002383 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2384
2385 if (Canon.isNull()) {
2386 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002387 ElaboratedTypeKeyword CanonKeyword = Keyword;
2388 if (Keyword == ETK_None)
2389 CanonKeyword = ETK_Typename;
2390
2391 if (CanonNNS != NNS || CanonKeyword != Keyword)
2392 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002393 }
2394
2395 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002396 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002397
2398 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002399 DependentNameType *T
2400 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002401 if (T)
2402 return QualType(T, 0);
2403
Douglas Gregor02085352010-03-31 20:19:30 +00002404 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002405 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002406 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002407 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002408}
2409
Mike Stump11289f42009-09-09 15:08:12 +00002410QualType
John McCallc392f372010-06-11 00:33:02 +00002411ASTContext::getDependentTemplateSpecializationType(
2412 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002413 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002414 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002415 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002416 // TODO: avoid this copy
2417 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2418 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2419 ArgCopy.push_back(Args[I].getArgument());
2420 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2421 ArgCopy.size(),
2422 ArgCopy.data());
2423}
2424
2425QualType
2426ASTContext::getDependentTemplateSpecializationType(
2427 ElaboratedTypeKeyword Keyword,
2428 NestedNameSpecifier *NNS,
2429 const IdentifierInfo *Name,
2430 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002431 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002432 assert((!NNS || NNS->isDependent()) &&
2433 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002434
Douglas Gregorc42075a2010-02-04 18:10:26 +00002435 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002436 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2437 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002438
2439 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002440 DependentTemplateSpecializationType *T
2441 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002442 if (T)
2443 return QualType(T, 0);
2444
John McCallc392f372010-06-11 00:33:02 +00002445 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002446
John McCallc392f372010-06-11 00:33:02 +00002447 ElaboratedTypeKeyword CanonKeyword = Keyword;
2448 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2449
2450 bool AnyNonCanonArgs = false;
2451 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2452 for (unsigned I = 0; I != NumArgs; ++I) {
2453 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2454 if (!CanonArgs[I].structurallyEquals(Args[I]))
2455 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002456 }
2457
John McCallc392f372010-06-11 00:33:02 +00002458 QualType Canon;
2459 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2460 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2461 Name, NumArgs,
2462 CanonArgs.data());
2463
2464 // Find the insert position again.
2465 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2466 }
2467
2468 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2469 sizeof(TemplateArgument) * NumArgs),
2470 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002471 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002472 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002473 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002474 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002475 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002476}
2477
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002478QualType ASTContext::getPackExpansionType(QualType Pattern,
2479 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002480 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002481 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002482
2483 assert(Pattern->containsUnexpandedParameterPack() &&
2484 "Pack expansions must expand one or more parameter packs");
2485 void *InsertPos = 0;
2486 PackExpansionType *T
2487 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2488 if (T)
2489 return QualType(T, 0);
2490
2491 QualType Canon;
2492 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002493 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002494
2495 // Find the insert position again.
2496 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2497 }
2498
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002499 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002500 Types.push_back(T);
2501 PackExpansionTypes.InsertNode(T, InsertPos);
2502 return QualType(T, 0);
2503}
2504
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002505/// CmpProtocolNames - Comparison predicate for sorting protocols
2506/// alphabetically.
2507static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2508 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002509 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002510}
2511
John McCall8b07ec22010-05-15 11:32:37 +00002512static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002513 unsigned NumProtocols) {
2514 if (NumProtocols == 0) return true;
2515
2516 for (unsigned i = 1; i != NumProtocols; ++i)
2517 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2518 return false;
2519 return true;
2520}
2521
2522static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002523 unsigned &NumProtocols) {
2524 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002525
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002526 // Sort protocols, keyed by name.
2527 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2528
2529 // Remove duplicates.
2530 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2531 NumProtocols = ProtocolsEnd-Protocols;
2532}
2533
John McCall8b07ec22010-05-15 11:32:37 +00002534QualType ASTContext::getObjCObjectType(QualType BaseType,
2535 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002536 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002537 // If the base type is an interface and there aren't any protocols
2538 // to add, then the interface type will do just fine.
2539 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2540 return BaseType;
2541
2542 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002543 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002544 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002545 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002546 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2547 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002548
John McCall8b07ec22010-05-15 11:32:37 +00002549 // Build the canonical type, which has the canonical base type and
2550 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002551 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002552 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2553 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2554 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002555 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2556 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002557 unsigned UniqueCount = NumProtocols;
2558
John McCallfc93cf92009-10-22 22:37:11 +00002559 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002560 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2561 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002562 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002563 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2564 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002565 }
2566
2567 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002568 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2569 }
2570
2571 unsigned Size = sizeof(ObjCObjectTypeImpl);
2572 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2573 void *Mem = Allocate(Size, TypeAlignment);
2574 ObjCObjectTypeImpl *T =
2575 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2576
2577 Types.push_back(T);
2578 ObjCObjectTypes.InsertNode(T, InsertPos);
2579 return QualType(T, 0);
2580}
2581
2582/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2583/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002584QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002585 llvm::FoldingSetNodeID ID;
2586 ObjCObjectPointerType::Profile(ID, ObjectT);
2587
2588 void *InsertPos = 0;
2589 if (ObjCObjectPointerType *QT =
2590 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2591 return QualType(QT, 0);
2592
2593 // Find the canonical object type.
2594 QualType Canonical;
2595 if (!ObjectT.isCanonical()) {
2596 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2597
2598 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002599 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2600 }
2601
Douglas Gregorf85bee62010-02-08 22:59:26 +00002602 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002603 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2604 ObjCObjectPointerType *QType =
2605 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002606
Steve Narofffb4330f2009-06-17 22:40:22 +00002607 Types.push_back(QType);
2608 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002609 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002610}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002611
Douglas Gregor1c283312010-08-11 12:19:30 +00002612/// getObjCInterfaceType - Return the unique reference to the type for the
2613/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002614QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002615 if (Decl->TypeForDecl)
2616 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002617
Douglas Gregor1c283312010-08-11 12:19:30 +00002618 // FIXME: redeclarations?
2619 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2620 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2621 Decl->TypeForDecl = T;
2622 Types.push_back(T);
2623 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002624}
2625
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002626/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2627/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002628/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002629/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002630/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002631QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002632 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002633 if (tofExpr->isTypeDependent()) {
2634 llvm::FoldingSetNodeID ID;
2635 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002636
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002637 void *InsertPos = 0;
2638 DependentTypeOfExprType *Canon
2639 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2640 if (Canon) {
2641 // We already have a "canonical" version of an identical, dependent
2642 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002643 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002644 QualType((TypeOfExprType*)Canon, 0));
2645 }
2646 else {
2647 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002648 Canon
2649 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002650 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2651 toe = Canon;
2652 }
2653 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002654 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002655 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002656 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002657 Types.push_back(toe);
2658 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002659}
2660
Steve Naroffa773cd52007-08-01 18:02:17 +00002661/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2662/// TypeOfType AST's. The only motivation to unique these nodes would be
2663/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002664/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002665/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002666QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002667 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002668 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002669 Types.push_back(tot);
2670 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002671}
2672
Anders Carlssonad6bd352009-06-24 21:24:56 +00002673/// getDecltypeForExpr - Given an expr, will return the decltype for that
2674/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002675static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002676 if (e->isTypeDependent())
2677 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002678
Anders Carlssonad6bd352009-06-24 21:24:56 +00002679 // If e is an id expression or a class member access, decltype(e) is defined
2680 // as the type of the entity named by e.
2681 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2682 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2683 return VD->getType();
2684 }
2685 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2686 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2687 return FD->getType();
2688 }
2689 // If e is a function call or an invocation of an overloaded operator,
2690 // (parentheses around e are ignored), decltype(e) is defined as the
2691 // return type of that function.
2692 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2693 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002694
Anders Carlssonad6bd352009-06-24 21:24:56 +00002695 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002696
2697 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002698 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002699 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002700 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002701
Anders Carlssonad6bd352009-06-24 21:24:56 +00002702 return T;
2703}
2704
Anders Carlsson81df7b82009-06-24 19:06:50 +00002705/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2706/// DecltypeType AST's. The only motivation to unique these nodes would be
2707/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002708/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002709/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002710QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002711 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002712 if (e->isTypeDependent()) {
2713 llvm::FoldingSetNodeID ID;
2714 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002715
Douglas Gregora21f6c32009-07-30 23:36:40 +00002716 void *InsertPos = 0;
2717 DependentDecltypeType *Canon
2718 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2719 if (Canon) {
2720 // We already have a "canonical" version of an equivalent, dependent
2721 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002722 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002723 QualType((DecltypeType*)Canon, 0));
2724 }
2725 else {
2726 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002727 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002728 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2729 dt = Canon;
2730 }
2731 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002732 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002733 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002734 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002735 Types.push_back(dt);
2736 return QualType(dt, 0);
2737}
2738
Richard Smithb2bc2e62011-02-21 20:05:19 +00002739/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002740QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002741 void *InsertPos = 0;
2742 if (!DeducedType.isNull()) {
2743 // Look in the folding set for an existing type.
2744 llvm::FoldingSetNodeID ID;
2745 AutoType::Profile(ID, DeducedType);
2746 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2747 return QualType(AT, 0);
2748 }
2749
2750 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2751 Types.push_back(AT);
2752 if (InsertPos)
2753 AutoTypes.InsertNode(AT, InsertPos);
2754 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002755}
2756
Chris Lattnerfb072462007-01-23 05:45:31 +00002757/// getTagDeclType - Return the unique reference to the type for the
2758/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002759QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002760 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002761 // FIXME: What is the design on getTagDeclType when it requires casting
2762 // away const? mutable?
2763 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002764}
2765
Mike Stump11289f42009-09-09 15:08:12 +00002766/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2767/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2768/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002769CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002770 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002771}
Chris Lattnerfb072462007-01-23 05:45:31 +00002772
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002773/// getSignedWCharType - Return the type of "signed wchar_t".
2774/// Used when in C++, as a GCC extension.
2775QualType ASTContext::getSignedWCharType() const {
2776 // FIXME: derive from "Target" ?
2777 return WCharTy;
2778}
2779
2780/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2781/// Used when in C++, as a GCC extension.
2782QualType ASTContext::getUnsignedWCharType() const {
2783 // FIXME: derive from "Target" ?
2784 return UnsignedIntTy;
2785}
2786
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002787/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2788/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2789QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002790 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002791}
2792
Chris Lattnera21ad802008-04-02 05:18:44 +00002793//===----------------------------------------------------------------------===//
2794// Type Operators
2795//===----------------------------------------------------------------------===//
2796
Jay Foad39c79802011-01-12 09:06:06 +00002797CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002798 // Push qualifiers into arrays, and then discard any remaining
2799 // qualifiers.
2800 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002801 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002802 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002803 QualType Result;
2804 if (isa<ArrayType>(Ty)) {
2805 Result = getArrayDecayedType(QualType(Ty,0));
2806 } else if (isa<FunctionType>(Ty)) {
2807 Result = getPointerType(QualType(Ty, 0));
2808 } else {
2809 Result = QualType(Ty, 0);
2810 }
2811
2812 return CanQualType::CreateUnsafe(Result);
2813}
2814
Chris Lattner7adf0762008-08-04 07:31:14 +00002815
John McCall6c9dd522011-01-18 07:41:22 +00002816QualType ASTContext::getUnqualifiedArrayType(QualType type,
2817 Qualifiers &quals) {
2818 SplitQualType splitType = type.getSplitUnqualifiedType();
2819
2820 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2821 // the unqualified desugared type and then drops it on the floor.
2822 // We then have to strip that sugar back off with
2823 // getUnqualifiedDesugaredType(), which is silly.
2824 const ArrayType *AT =
2825 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2826
2827 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002828 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002829 quals = splitType.second;
2830 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002831 }
2832
John McCall6c9dd522011-01-18 07:41:22 +00002833 // Otherwise, recurse on the array's element type.
2834 QualType elementType = AT->getElementType();
2835 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2836
2837 // If that didn't change the element type, AT has no qualifiers, so we
2838 // can just use the results in splitType.
2839 if (elementType == unqualElementType) {
2840 assert(quals.empty()); // from the recursive call
2841 quals = splitType.second;
2842 return QualType(splitType.first, 0);
2843 }
2844
2845 // Otherwise, add in the qualifiers from the outermost type, then
2846 // build the type back up.
2847 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002848
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002849 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002850 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002851 CAT->getSizeModifier(), 0);
2852 }
2853
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002854 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002855 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002856 }
2857
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002858 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002859 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002860 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002861 VAT->getSizeModifier(),
2862 VAT->getIndexTypeCVRQualifiers(),
2863 VAT->getBracketsRange());
2864 }
2865
2866 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00002867 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002868 DSAT->getSizeModifier(), 0,
2869 SourceRange());
2870}
2871
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002872/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2873/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2874/// they point to and return true. If T1 and T2 aren't pointer types
2875/// or pointer-to-member types, or if they are not similar at this
2876/// level, returns false and leaves T1 and T2 unchanged. Top-level
2877/// qualifiers on T1 and T2 are ignored. This function will typically
2878/// be called in a loop that successively "unwraps" pointer and
2879/// pointer-to-member types to compare them at each level.
2880bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2881 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2882 *T2PtrType = T2->getAs<PointerType>();
2883 if (T1PtrType && T2PtrType) {
2884 T1 = T1PtrType->getPointeeType();
2885 T2 = T2PtrType->getPointeeType();
2886 return true;
2887 }
2888
2889 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2890 *T2MPType = T2->getAs<MemberPointerType>();
2891 if (T1MPType && T2MPType &&
2892 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2893 QualType(T2MPType->getClass(), 0))) {
2894 T1 = T1MPType->getPointeeType();
2895 T2 = T2MPType->getPointeeType();
2896 return true;
2897 }
2898
2899 if (getLangOptions().ObjC1) {
2900 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2901 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2902 if (T1OPType && T2OPType) {
2903 T1 = T1OPType->getPointeeType();
2904 T2 = T2OPType->getPointeeType();
2905 return true;
2906 }
2907 }
2908
2909 // FIXME: Block pointers, too?
2910
2911 return false;
2912}
2913
Jay Foad39c79802011-01-12 09:06:06 +00002914DeclarationNameInfo
2915ASTContext::getNameForTemplate(TemplateName Name,
2916 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00002917 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002918 // DNInfo work in progress: CHECKME: what about DNLoc?
2919 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2920
John McCall847e2a12009-11-24 18:42:40 +00002921 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002922 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00002923 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002924 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2925 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002926 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002927 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2928 // DNInfo work in progress: FIXME: source locations?
2929 DeclarationNameLoc DNLoc;
2930 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2931 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2932 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00002933 }
2934 }
2935
John McCalld28ae272009-12-02 08:04:21 +00002936 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2937 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002938 // DNInfo work in progress: CHECKME: what about DNLoc?
2939 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00002940}
2941
Jay Foad39c79802011-01-12 09:06:06 +00002942TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002943 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2944 if (TemplateTemplateParmDecl *TTP
2945 = dyn_cast<TemplateTemplateParmDecl>(Template))
2946 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2947
2948 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002949 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00002950 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00002951
Douglas Gregor5590be02011-01-15 06:45:20 +00002952 if (SubstTemplateTemplateParmPackStorage *SubstPack
2953 = Name.getAsSubstTemplateTemplateParmPack()) {
2954 TemplateTemplateParmDecl *CanonParam
2955 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2956 TemplateArgument CanonArgPack
2957 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2958 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2959 }
2960
John McCalld28ae272009-12-02 08:04:21 +00002961 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00002962
Douglas Gregor6bc50582009-05-07 06:41:52 +00002963 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2964 assert(DTN && "Non-dependent template names must refer to template decls.");
2965 return DTN->CanonicalTemplateName;
2966}
2967
Douglas Gregoradee3e32009-11-11 23:06:43 +00002968bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2969 X = getCanonicalTemplateName(X);
2970 Y = getCanonicalTemplateName(Y);
2971 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2972}
2973
Mike Stump11289f42009-09-09 15:08:12 +00002974TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00002975ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00002976 switch (Arg.getKind()) {
2977 case TemplateArgument::Null:
2978 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002979
Douglas Gregora8e02e72009-07-28 23:00:59 +00002980 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00002981 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00002982
Douglas Gregora8e02e72009-07-28 23:00:59 +00002983 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00002984 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002985
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002986 case TemplateArgument::Template:
2987 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002988
2989 case TemplateArgument::TemplateExpansion:
2990 return TemplateArgument(getCanonicalTemplateName(
2991 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00002992 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002993
Douglas Gregora8e02e72009-07-28 23:00:59 +00002994 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00002995 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00002996 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00002997
Douglas Gregora8e02e72009-07-28 23:00:59 +00002998 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00002999 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003000
Douglas Gregora8e02e72009-07-28 23:00:59 +00003001 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003002 if (Arg.pack_size() == 0)
3003 return Arg;
3004
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003005 TemplateArgument *CanonArgs
3006 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003007 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003008 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003009 AEnd = Arg.pack_end();
3010 A != AEnd; (void)++A, ++Idx)
3011 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003012
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003013 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003014 }
3015 }
3016
3017 // Silence GCC warning
3018 assert(false && "Unhandled template argument kind");
3019 return TemplateArgument();
3020}
3021
Douglas Gregor333489b2009-03-27 23:10:48 +00003022NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003023ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003024 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003025 return 0;
3026
3027 switch (NNS->getKind()) {
3028 case NestedNameSpecifier::Identifier:
3029 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003030 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003031 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3032 NNS->getAsIdentifier());
3033
3034 case NestedNameSpecifier::Namespace:
3035 // A namespace is canonical; build a nested-name-specifier with
3036 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003037 return NestedNameSpecifier::Create(*this, 0,
3038 NNS->getAsNamespace()->getOriginalNamespace());
3039
3040 case NestedNameSpecifier::NamespaceAlias:
3041 // A namespace is canonical; build a nested-name-specifier with
3042 // this namespace and no prefix.
3043 return NestedNameSpecifier::Create(*this, 0,
3044 NNS->getAsNamespaceAlias()->getNamespace()
3045 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003046
3047 case NestedNameSpecifier::TypeSpec:
3048 case NestedNameSpecifier::TypeSpecWithTemplate: {
3049 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003050
3051 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3052 // break it apart into its prefix and identifier, then reconsititute those
3053 // as the canonical nested-name-specifier. This is required to canonicalize
3054 // a dependent nested-name-specifier involving typedefs of dependent-name
3055 // types, e.g.,
3056 // typedef typename T::type T1;
3057 // typedef typename T1::type T2;
3058 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3059 NestedNameSpecifier *Prefix
3060 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3061 return NestedNameSpecifier::Create(*this, Prefix,
3062 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3063 }
3064
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003065 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003066 if (const DependentTemplateSpecializationType *DTST
3067 = T->getAs<DependentTemplateSpecializationType>()) {
3068 NestedNameSpecifier *Prefix
3069 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003070
3071 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3072 Prefix, DTST->getIdentifier(),
3073 DTST->getNumArgs(),
3074 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003075 T = getCanonicalType(T);
3076 }
3077
John McCall33ddac02011-01-19 10:06:00 +00003078 return NestedNameSpecifier::Create(*this, 0, false,
3079 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003080 }
3081
3082 case NestedNameSpecifier::Global:
3083 // The global specifier is canonical and unique.
3084 return NNS;
3085 }
3086
3087 // Required to silence a GCC warning
3088 return 0;
3089}
3090
Chris Lattner7adf0762008-08-04 07:31:14 +00003091
Jay Foad39c79802011-01-12 09:06:06 +00003092const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003093 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003094 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003095 // Handle the common positive case fast.
3096 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3097 return AT;
3098 }
Mike Stump11289f42009-09-09 15:08:12 +00003099
John McCall8ccfcb52009-09-24 19:53:00 +00003100 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003101 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003102 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003103
John McCall8ccfcb52009-09-24 19:53:00 +00003104 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003105 // implements C99 6.7.3p8: "If the specification of an array type includes
3106 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003107
Chris Lattner7adf0762008-08-04 07:31:14 +00003108 // If we get here, we either have type qualifiers on the type, or we have
3109 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003110 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003111
John McCall33ddac02011-01-19 10:06:00 +00003112 SplitQualType split = T.getSplitDesugaredType();
3113 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003114
Chris Lattner7adf0762008-08-04 07:31:14 +00003115 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003116 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3117 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003118 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003119
Chris Lattner7adf0762008-08-04 07:31:14 +00003120 // Otherwise, we have an array and we have qualifiers on it. Push the
3121 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003122 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003123
Chris Lattner7adf0762008-08-04 07:31:14 +00003124 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3125 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3126 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003127 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003128 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3129 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3130 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003131 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003132
Mike Stump11289f42009-09-09 15:08:12 +00003133 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003134 = dyn_cast<DependentSizedArrayType>(ATy))
3135 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003136 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003137 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003138 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003139 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003140 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003141
Chris Lattner7adf0762008-08-04 07:31:14 +00003142 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003143 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003144 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003145 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003146 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003147 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003148}
3149
Chris Lattnera21ad802008-04-02 05:18:44 +00003150/// getArrayDecayedType - Return the properly qualified result of decaying the
3151/// specified array type to a pointer. This operation is non-trivial when
3152/// handling typedefs etc. The canonical type of "T" must be an array type,
3153/// this returns a pointer to a properly qualified element of the array.
3154///
3155/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003156QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003157 // Get the element type with 'getAsArrayType' so that we don't lose any
3158 // typedefs in the element type of the array. This also handles propagation
3159 // of type qualifiers from the array type into the element type if present
3160 // (C99 6.7.3p8).
3161 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3162 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003163
Chris Lattner7adf0762008-08-04 07:31:14 +00003164 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003165
3166 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003167 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003168}
3169
John McCall33ddac02011-01-19 10:06:00 +00003170QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3171 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003172}
3173
John McCall33ddac02011-01-19 10:06:00 +00003174QualType ASTContext::getBaseElementType(QualType type) const {
3175 Qualifiers qs;
3176 while (true) {
3177 SplitQualType split = type.getSplitDesugaredType();
3178 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3179 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003180
John McCall33ddac02011-01-19 10:06:00 +00003181 type = array->getElementType();
3182 qs.addConsistentQualifiers(split.second);
3183 }
Mike Stump11289f42009-09-09 15:08:12 +00003184
John McCall33ddac02011-01-19 10:06:00 +00003185 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003186}
3187
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003188/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003189uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003190ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3191 uint64_t ElementCount = 1;
3192 do {
3193 ElementCount *= CA->getSize().getZExtValue();
3194 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3195 } while (CA);
3196 return ElementCount;
3197}
3198
Steve Naroff0af91202007-04-27 21:51:21 +00003199/// getFloatingRank - Return a relative rank for floating point types.
3200/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003201static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003202 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003203 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003204
John McCall9dd450b2009-09-21 23:43:11 +00003205 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3206 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003207 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003208 case BuiltinType::Float: return FloatRank;
3209 case BuiltinType::Double: return DoubleRank;
3210 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003211 }
3212}
3213
Mike Stump11289f42009-09-09 15:08:12 +00003214/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3215/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003216/// 'typeDomain' is a real floating point or complex type.
3217/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003218QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3219 QualType Domain) const {
3220 FloatingRank EltRank = getFloatingRank(Size);
3221 if (Domain->isComplexType()) {
3222 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003223 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003224 case FloatRank: return FloatComplexTy;
3225 case DoubleRank: return DoubleComplexTy;
3226 case LongDoubleRank: return LongDoubleComplexTy;
3227 }
Steve Naroff0af91202007-04-27 21:51:21 +00003228 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003229
3230 assert(Domain->isRealFloatingType() && "Unknown domain!");
3231 switch (EltRank) {
3232 default: assert(0 && "getFloatingRank(): illegal value for rank");
3233 case FloatRank: return FloatTy;
3234 case DoubleRank: return DoubleTy;
3235 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003236 }
Steve Naroffe4718892007-04-27 18:30:00 +00003237}
3238
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003239/// getFloatingTypeOrder - Compare the rank of the two specified floating
3240/// point types, ignoring the domain of the type (i.e. 'double' ==
3241/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003242/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003243int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003244 FloatingRank LHSR = getFloatingRank(LHS);
3245 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003246
Chris Lattnerb90739d2008-04-06 23:38:49 +00003247 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003248 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003249 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003250 return 1;
3251 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003252}
3253
Chris Lattner76a00cf2008-04-06 22:59:24 +00003254/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3255/// routine will assert if passed a built-in type that isn't an integer or enum,
3256/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003257unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003258 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003259 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003260 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003261
Chris Lattnerad3467e2010-12-25 23:25:43 +00003262 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3263 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003264 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3265
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003266 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3267 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3268
3269 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3270 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3271
Chris Lattner76a00cf2008-04-06 22:59:24 +00003272 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003273 default: assert(0 && "getIntegerRank(): not a built-in integer");
3274 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003275 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003276 case BuiltinType::Char_S:
3277 case BuiltinType::Char_U:
3278 case BuiltinType::SChar:
3279 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003280 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003281 case BuiltinType::Short:
3282 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003283 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003284 case BuiltinType::Int:
3285 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003286 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003287 case BuiltinType::Long:
3288 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003289 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003290 case BuiltinType::LongLong:
3291 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003292 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003293 case BuiltinType::Int128:
3294 case BuiltinType::UInt128:
3295 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003296 }
3297}
3298
Eli Friedman629ffb92009-08-20 04:21:42 +00003299/// \brief Whether this is a promotable bitfield reference according
3300/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3301///
3302/// \returns the type this bit-field will promote to, or NULL if no
3303/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003304QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003305 if (E->isTypeDependent() || E->isValueDependent())
3306 return QualType();
3307
Eli Friedman629ffb92009-08-20 04:21:42 +00003308 FieldDecl *Field = E->getBitField();
3309 if (!Field)
3310 return QualType();
3311
3312 QualType FT = Field->getType();
3313
3314 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3315 uint64_t BitWidth = BitWidthAP.getZExtValue();
3316 uint64_t IntSize = getTypeSize(IntTy);
3317 // GCC extension compatibility: if the bit-field size is less than or equal
3318 // to the size of int, it gets promoted no matter what its type is.
3319 // For instance, unsigned long bf : 4 gets promoted to signed int.
3320 if (BitWidth < IntSize)
3321 return IntTy;
3322
3323 if (BitWidth == IntSize)
3324 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3325
3326 // Types bigger than int are not subject to promotions, and therefore act
3327 // like the base type.
3328 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3329 // is ridiculous.
3330 return QualType();
3331}
3332
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003333/// getPromotedIntegerType - Returns the type that Promotable will
3334/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3335/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003336QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003337 assert(!Promotable.isNull());
3338 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003339 if (const EnumType *ET = Promotable->getAs<EnumType>())
3340 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003341 if (Promotable->isSignedIntegerType())
3342 return IntTy;
3343 uint64_t PromotableSize = getTypeSize(Promotable);
3344 uint64_t IntSize = getTypeSize(IntTy);
3345 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3346 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3347}
3348
Mike Stump11289f42009-09-09 15:08:12 +00003349/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003350/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003351/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003352int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003353 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3354 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003355 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003356
Chris Lattner76a00cf2008-04-06 22:59:24 +00003357 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3358 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003359
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003360 unsigned LHSRank = getIntegerRank(LHSC);
3361 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003362
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003363 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3364 if (LHSRank == RHSRank) return 0;
3365 return LHSRank > RHSRank ? 1 : -1;
3366 }
Mike Stump11289f42009-09-09 15:08:12 +00003367
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003368 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3369 if (LHSUnsigned) {
3370 // If the unsigned [LHS] type is larger, return it.
3371 if (LHSRank >= RHSRank)
3372 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003373
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003374 // If the signed type can represent all values of the unsigned type, it
3375 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003376 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003377 return -1;
3378 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003379
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003380 // If the unsigned [RHS] type is larger, return it.
3381 if (RHSRank >= LHSRank)
3382 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003383
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003384 // If the signed type can represent all values of the unsigned type, it
3385 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003386 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003387 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003388}
Anders Carlsson98f07902007-08-17 05:31:46 +00003389
Anders Carlsson6d417272009-11-14 21:45:58 +00003390static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003391CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3392 DeclContext *DC, IdentifierInfo *Id) {
3393 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003394 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003395 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003396 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003397 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003398}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003399
Mike Stump11289f42009-09-09 15:08:12 +00003400// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003401QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003402 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003403 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003404 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003405 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003406 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003407
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003408 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003409
Anders Carlsson98f07902007-08-17 05:31:46 +00003410 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003411 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003412 // int flags;
3413 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003414 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003415 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003416 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003417 FieldTypes[3] = LongTy;
3418
Anders Carlsson98f07902007-08-17 05:31:46 +00003419 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003420 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003421 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003422 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003423 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003424 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003425 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003426 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003427 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003428 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003429 }
3430
Douglas Gregord5058122010-02-11 01:19:42 +00003431 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003432 }
Mike Stump11289f42009-09-09 15:08:12 +00003433
Anders Carlsson98f07902007-08-17 05:31:46 +00003434 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003435}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003436
Douglas Gregor512b0772009-04-23 22:29:11 +00003437void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003438 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003439 assert(Rec && "Invalid CFConstantStringType");
3440 CFConstantStringTypeDecl = Rec->getDecl();
3441}
3442
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003443// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003444QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003445 if (!NSConstantStringTypeDecl) {
3446 NSConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003447 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003448 &Idents.get("__builtin_NSString"));
3449 NSConstantStringTypeDecl->startDefinition();
3450
3451 QualType FieldTypes[3];
3452
3453 // const int *isa;
3454 FieldTypes[0] = getPointerType(IntTy.withConst());
3455 // const char *str;
3456 FieldTypes[1] = getPointerType(CharTy.withConst());
3457 // unsigned int length;
3458 FieldTypes[2] = UnsignedIntTy;
3459
3460 // Create fields
3461 for (unsigned i = 0; i < 3; ++i) {
3462 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003463 SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003464 SourceLocation(), 0,
3465 FieldTypes[i], /*TInfo=*/0,
3466 /*BitWidth=*/0,
3467 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003468 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003469 NSConstantStringTypeDecl->addDecl(Field);
3470 }
3471
3472 NSConstantStringTypeDecl->completeDefinition();
3473 }
3474
3475 return getTagDeclType(NSConstantStringTypeDecl);
3476}
3477
3478void ASTContext::setNSConstantStringType(QualType T) {
3479 const RecordType *Rec = T->getAs<RecordType>();
3480 assert(Rec && "Invalid NSConstantStringType");
3481 NSConstantStringTypeDecl = Rec->getDecl();
3482}
3483
Jay Foad39c79802011-01-12 09:06:06 +00003484QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003485 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003486 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003487 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003488 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003489 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003490
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003491 QualType FieldTypes[] = {
3492 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003493 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003494 getPointerType(UnsignedLongTy),
3495 getConstantArrayType(UnsignedLongTy,
3496 llvm::APInt(32, 5), ArrayType::Normal, 0)
3497 };
Mike Stump11289f42009-09-09 15:08:12 +00003498
Douglas Gregor91f84212008-12-11 16:49:14 +00003499 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003500 FieldDecl *Field = FieldDecl::Create(*this,
3501 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003502 SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003503 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003504 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003505 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003506 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003507 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003508 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003509 }
Mike Stump11289f42009-09-09 15:08:12 +00003510
Douglas Gregord5058122010-02-11 01:19:42 +00003511 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003512 }
Mike Stump11289f42009-09-09 15:08:12 +00003513
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003514 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3515}
3516
Jay Foad39c79802011-01-12 09:06:06 +00003517QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003518 if (BlockDescriptorType)
3519 return getTagDeclType(BlockDescriptorType);
3520
3521 RecordDecl *T;
3522 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003523 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003524 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003525 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003526
3527 QualType FieldTypes[] = {
3528 UnsignedLongTy,
3529 UnsignedLongTy,
3530 };
3531
3532 const char *FieldNames[] = {
3533 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003534 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003535 };
3536
3537 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003538 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003539 SourceLocation(),
3540 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003541 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003542 /*BitWidth=*/0,
3543 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003544 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003545 T->addDecl(Field);
3546 }
3547
Douglas Gregord5058122010-02-11 01:19:42 +00003548 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003549
3550 BlockDescriptorType = T;
3551
3552 return getTagDeclType(BlockDescriptorType);
3553}
3554
3555void ASTContext::setBlockDescriptorType(QualType T) {
3556 const RecordType *Rec = T->getAs<RecordType>();
3557 assert(Rec && "Invalid BlockDescriptorType");
3558 BlockDescriptorType = Rec->getDecl();
3559}
3560
Jay Foad39c79802011-01-12 09:06:06 +00003561QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003562 if (BlockDescriptorExtendedType)
3563 return getTagDeclType(BlockDescriptorExtendedType);
3564
3565 RecordDecl *T;
3566 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003567 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003568 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003569 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003570
3571 QualType FieldTypes[] = {
3572 UnsignedLongTy,
3573 UnsignedLongTy,
3574 getPointerType(VoidPtrTy),
3575 getPointerType(VoidPtrTy)
3576 };
3577
3578 const char *FieldNames[] = {
3579 "reserved",
3580 "Size",
3581 "CopyFuncPtr",
3582 "DestroyFuncPtr"
3583 };
3584
3585 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003586 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003587 SourceLocation(),
3588 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003589 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003590 /*BitWidth=*/0,
3591 /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003592 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003593 T->addDecl(Field);
3594 }
3595
Douglas Gregord5058122010-02-11 01:19:42 +00003596 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003597
3598 BlockDescriptorExtendedType = T;
3599
3600 return getTagDeclType(BlockDescriptorExtendedType);
3601}
3602
3603void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3604 const RecordType *Rec = T->getAs<RecordType>();
3605 assert(Rec && "Invalid BlockDescriptorType");
3606 BlockDescriptorExtendedType = Rec->getDecl();
3607}
3608
Jay Foad39c79802011-01-12 09:06:06 +00003609bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003610 if (Ty->isBlockPointerType())
3611 return true;
3612 if (isObjCNSObjectType(Ty))
3613 return true;
3614 if (Ty->isObjCObjectPointerType())
3615 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003616 if (getLangOptions().CPlusPlus) {
3617 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3618 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3619 return RD->hasConstCopyConstructor(*this);
3620
3621 }
3622 }
Mike Stump94967902009-10-21 18:16:27 +00003623 return false;
3624}
3625
Jay Foad39c79802011-01-12 09:06:06 +00003626QualType
3627ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003628 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003629 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003630 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003631 // unsigned int __flags;
3632 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003633 // void *__copy_helper; // as needed
3634 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003635 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003636 // } *
3637
Mike Stump94967902009-10-21 18:16:27 +00003638 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3639
3640 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003641 llvm::SmallString<36> Name;
3642 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3643 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003644 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003645 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003646 T->startDefinition();
3647 QualType Int32Ty = IntTy;
3648 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3649 QualType FieldTypes[] = {
3650 getPointerType(VoidPtrTy),
3651 getPointerType(getTagDeclType(T)),
3652 Int32Ty,
3653 Int32Ty,
3654 getPointerType(VoidPtrTy),
3655 getPointerType(VoidPtrTy),
3656 Ty
3657 };
3658
Daniel Dunbar56df9772010-08-17 22:39:59 +00003659 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003660 "__isa",
3661 "__forwarding",
3662 "__flags",
3663 "__size",
3664 "__copy_helper",
3665 "__destroy_helper",
3666 DeclName,
3667 };
3668
3669 for (size_t i = 0; i < 7; ++i) {
3670 if (!HasCopyAndDispose && i >=4 && i <= 5)
3671 continue;
3672 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003673 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003674 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003675 FieldTypes[i], /*TInfo=*/0,
Mike Stump94967902009-10-21 18:16:27 +00003676 /*BitWidth=*/0, /*Mutable=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003677 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003678 T->addDecl(Field);
3679 }
3680
Douglas Gregord5058122010-02-11 01:19:42 +00003681 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003682
3683 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003684}
3685
Douglas Gregor512b0772009-04-23 22:29:11 +00003686void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003687 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003688 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3689 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3690}
3691
Anders Carlsson18acd442007-10-29 06:33:42 +00003692// This returns true if a type has been typedefed to BOOL:
3693// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003694static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003695 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003696 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3697 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003698
Anders Carlssond8499822007-10-29 05:01:08 +00003699 return false;
3700}
3701
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003702/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003703/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003704CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck40775002010-01-11 17:06:35 +00003705 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003706
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003707 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003708 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003709 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003710 // Treat arrays as pointers, since that's how they're passed in.
3711 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003712 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003713 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003714}
3715
3716static inline
3717std::string charUnitsToString(const CharUnits &CU) {
3718 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003719}
3720
John McCall351762c2011-02-07 10:33:21 +00003721/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003722/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003723std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3724 std::string S;
3725
David Chisnall950a9512009-11-17 19:33:30 +00003726 const BlockDecl *Decl = Expr->getBlockDecl();
3727 QualType BlockTy =
3728 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3729 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003730 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003731 // Compute size of all parameters.
3732 // Start with computing size of a pointer in number of bytes.
3733 // FIXME: There might(should) be a better way of doing this computation!
3734 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003735 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3736 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003737 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003738 E = Decl->param_end(); PI != E; ++PI) {
3739 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003740 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003741 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003742 ParmOffset += sz;
3743 }
3744 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003745 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003746 // Block pointer and offset.
3747 S += "@?0";
3748 ParmOffset = PtrSize;
3749
3750 // Argument types.
3751 ParmOffset = PtrSize;
3752 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3753 Decl->param_end(); PI != E; ++PI) {
3754 ParmVarDecl *PVDecl = *PI;
3755 QualType PType = PVDecl->getOriginalType();
3756 if (const ArrayType *AT =
3757 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3758 // Use array's original type only if it has known number of
3759 // elements.
3760 if (!isa<ConstantArrayType>(AT))
3761 PType = PVDecl->getType();
3762 } else if (PType->isFunctionType())
3763 PType = PVDecl->getType();
3764 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003765 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003766 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003767 }
John McCall351762c2011-02-07 10:33:21 +00003768
3769 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003770}
3771
David Chisnall50e4eba2010-12-30 14:05:53 +00003772void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3773 std::string& S) {
3774 // Encode result type.
3775 getObjCEncodingForType(Decl->getResultType(), S);
3776 CharUnits ParmOffset;
3777 // Compute size of all parameters.
3778 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3779 E = Decl->param_end(); PI != E; ++PI) {
3780 QualType PType = (*PI)->getType();
3781 CharUnits sz = getObjCEncodingTypeSize(PType);
3782 assert (sz.isPositive() &&
3783 "getObjCEncodingForMethodDecl - Incomplete param type");
3784 ParmOffset += sz;
3785 }
3786 S += charUnitsToString(ParmOffset);
3787 ParmOffset = CharUnits::Zero();
3788
3789 // Argument types.
3790 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3791 E = Decl->param_end(); PI != E; ++PI) {
3792 ParmVarDecl *PVDecl = *PI;
3793 QualType PType = PVDecl->getOriginalType();
3794 if (const ArrayType *AT =
3795 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3796 // Use array's original type only if it has known number of
3797 // elements.
3798 if (!isa<ConstantArrayType>(AT))
3799 PType = PVDecl->getType();
3800 } else if (PType->isFunctionType())
3801 PType = PVDecl->getType();
3802 getObjCEncodingForType(PType, S);
3803 S += charUnitsToString(ParmOffset);
3804 ParmOffset += getObjCEncodingTypeSize(PType);
3805 }
3806}
3807
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003808/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003809/// declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003810void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003811 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003812 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003813 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003814 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003815 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003816 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003817 // Compute size of all parameters.
3818 // Start with computing size of a pointer in number of bytes.
3819 // FIXME: There might(should) be a better way of doing this computation!
3820 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003821 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003822 // The first two arguments (self and _cmd) are pointers; account for
3823 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003824 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003825 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003826 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003827 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003828 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003829 assert (sz.isPositive() &&
3830 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003831 ParmOffset += sz;
3832 }
Ken Dyck40775002010-01-11 17:06:35 +00003833 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003834 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003835 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003836
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003837 // Argument types.
3838 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003839 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003840 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003841 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003842 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003843 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003844 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3845 // Use array's original type only if it has known number of
3846 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003847 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003848 PType = PVDecl->getType();
3849 } else if (PType->isFunctionType())
3850 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003851 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003852 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003853 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003854 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003855 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003856 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003857 }
3858}
3859
Daniel Dunbar4932b362008-08-28 04:38:10 +00003860/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003861/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003862/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3863/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003864/// Property attributes are stored as a comma-delimited C string. The simple
3865/// attributes readonly and bycopy are encoded as single characters. The
3866/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3867/// encoded as single characters, followed by an identifier. Property types
3868/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003869/// these attributes are defined by the following enumeration:
3870/// @code
3871/// enum PropertyAttributes {
3872/// kPropertyReadOnly = 'R', // property is read-only.
3873/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3874/// kPropertyByref = '&', // property is a reference to the value last assigned
3875/// kPropertyDynamic = 'D', // property is dynamic
3876/// kPropertyGetter = 'G', // followed by getter selector name
3877/// kPropertySetter = 'S', // followed by setter selector name
3878/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3879/// kPropertyType = 't' // followed by old-style type encoding.
3880/// kPropertyWeak = 'W' // 'weak' property
3881/// kPropertyStrong = 'P' // property GC'able
3882/// kPropertyNonAtomic = 'N' // property non-atomic
3883/// };
3884/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00003885void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00003886 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00003887 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003888 // Collect information from the property implementation decl(s).
3889 bool Dynamic = false;
3890 ObjCPropertyImplDecl *SynthesizePID = 0;
3891
3892 // FIXME: Duplicated code due to poor abstraction.
3893 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00003894 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00003895 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3896 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003897 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003898 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003899 ObjCPropertyImplDecl *PID = *i;
3900 if (PID->getPropertyDecl() == PD) {
3901 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3902 Dynamic = true;
3903 } else {
3904 SynthesizePID = PID;
3905 }
3906 }
3907 }
3908 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00003909 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003910 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003911 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003912 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003913 ObjCPropertyImplDecl *PID = *i;
3914 if (PID->getPropertyDecl() == PD) {
3915 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3916 Dynamic = true;
3917 } else {
3918 SynthesizePID = PID;
3919 }
3920 }
Mike Stump11289f42009-09-09 15:08:12 +00003921 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00003922 }
3923 }
3924
3925 // FIXME: This is not very efficient.
3926 S = "T";
3927
3928 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003929 // GCC has some special rules regarding encoding of properties which
3930 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00003931 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003932 true /* outermost type */,
3933 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00003934
3935 if (PD->isReadOnly()) {
3936 S += ",R";
3937 } else {
3938 switch (PD->getSetterKind()) {
3939 case ObjCPropertyDecl::Assign: break;
3940 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00003941 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00003942 }
3943 }
3944
3945 // It really isn't clear at all what this means, since properties
3946 // are "dynamic by default".
3947 if (Dynamic)
3948 S += ",D";
3949
Fariborz Jahanian218c6302009-01-20 19:14:18 +00003950 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3951 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00003952
Daniel Dunbar4932b362008-08-28 04:38:10 +00003953 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3954 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00003955 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003956 }
3957
3958 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3959 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00003960 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003961 }
3962
3963 if (SynthesizePID) {
3964 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3965 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00003966 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00003967 }
3968
3969 // FIXME: OBJCGC: weak & strong
3970}
3971
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003972/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00003973/// Another legacy compatibility encoding: 32-bit longs are encoded as
3974/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003975/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3976///
3977void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00003978 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00003979 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00003980 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003981 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00003982 else
Jay Foad39c79802011-01-12 09:06:06 +00003983 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00003984 PointeeTy = IntTy;
3985 }
3986 }
3987}
3988
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00003989void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00003990 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003991 // We follow the behavior of gcc, expanding structures which are
3992 // directly pointed to, and expanding embedded structures. Note that
3993 // these rules are sufficient to prevent recursive encoding of the
3994 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00003995 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00003996 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00003997}
3998
David Chisnallb190a2c2010-06-04 01:10:52 +00003999static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4000 switch (T->getAs<BuiltinType>()->getKind()) {
4001 default: assert(0 && "Unhandled builtin type kind");
4002 case BuiltinType::Void: return 'v';
4003 case BuiltinType::Bool: return 'B';
4004 case BuiltinType::Char_U:
4005 case BuiltinType::UChar: return 'C';
4006 case BuiltinType::UShort: return 'S';
4007 case BuiltinType::UInt: return 'I';
4008 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004009 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004010 case BuiltinType::UInt128: return 'T';
4011 case BuiltinType::ULongLong: return 'Q';
4012 case BuiltinType::Char_S:
4013 case BuiltinType::SChar: return 'c';
4014 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004015 case BuiltinType::WChar_S:
4016 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004017 case BuiltinType::Int: return 'i';
4018 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004019 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004020 case BuiltinType::LongLong: return 'q';
4021 case BuiltinType::Int128: return 't';
4022 case BuiltinType::Float: return 'f';
4023 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004024 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004025 }
4026}
4027
Jay Foad39c79802011-01-12 09:06:06 +00004028static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004029 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004030 const Expr *E = FD->getBitWidth();
4031 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004032 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004033 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4034 // The GNU runtime requires more information; bitfields are encoded as b,
4035 // then the offset (in bits) of the first element, then the type of the
4036 // bitfield, then the size in bits. For example, in this structure:
4037 //
4038 // struct
4039 // {
4040 // int integer;
4041 // int flags:2;
4042 // };
4043 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4044 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4045 // information is not especially sensible, but we're stuck with it for
4046 // compatibility with GCC, although providing it breaks anything that
4047 // actually uses runtime introspection and wants to work on both runtimes...
4048 if (!Ctx->getLangOptions().NeXTRuntime) {
4049 const RecordDecl *RD = FD->getParent();
4050 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4051 // FIXME: This same linear search is also used in ExprConstant - it might
4052 // be better if the FieldDecl stored its offset. We'd be increasing the
4053 // size of the object slightly, but saving some time every time it is used.
4054 unsigned i = 0;
4055 for (RecordDecl::field_iterator Field = RD->field_begin(),
4056 FieldEnd = RD->field_end();
4057 Field != FieldEnd; (void)++Field, ++i) {
4058 if (*Field == FD)
4059 break;
4060 }
4061 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004062 if (T->isEnumeralType())
4063 S += 'i';
4064 else
Jay Foad39c79802011-01-12 09:06:06 +00004065 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004066 }
4067 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004068 S += llvm::utostr(N);
4069}
4070
Daniel Dunbar07d07852009-10-18 21:17:35 +00004071// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004072void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4073 bool ExpandPointedToStructures,
4074 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004075 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004076 bool OutermostType,
Jay Foad39c79802011-01-12 09:06:06 +00004077 bool EncodingProperty) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004078 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004079 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004080 return EncodeBitField(this, S, T, FD);
4081 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004082 return;
4083 }
Mike Stump11289f42009-09-09 15:08:12 +00004084
John McCall9dd450b2009-09-21 23:43:11 +00004085 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004086 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004087 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004088 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004089 return;
4090 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004091
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004092 // encoding for pointer or r3eference types.
4093 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004094 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004095 if (PT->isObjCSelType()) {
4096 S += ':';
4097 return;
4098 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004099 PointeeTy = PT->getPointeeType();
4100 }
4101 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4102 PointeeTy = RT->getPointeeType();
4103 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004104 bool isReadOnly = false;
4105 // For historical/compatibility reasons, the read-only qualifier of the
4106 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4107 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004108 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004109 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004110 if (OutermostType && T.isConstQualified()) {
4111 isReadOnly = true;
4112 S += 'r';
4113 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004114 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004115 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004116 while (P->getAs<PointerType>())
4117 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004118 if (P.isConstQualified()) {
4119 isReadOnly = true;
4120 S += 'r';
4121 }
4122 }
4123 if (isReadOnly) {
4124 // Another legacy compatibility encoding. Some ObjC qualifier and type
4125 // combinations need to be rearranged.
4126 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004127 if (llvm::StringRef(S).endswith("nr"))
4128 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004129 }
Mike Stump11289f42009-09-09 15:08:12 +00004130
Anders Carlssond8499822007-10-29 05:01:08 +00004131 if (PointeeTy->isCharType()) {
4132 // char pointer types should be encoded as '*' unless it is a
4133 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004134 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004135 S += '*';
4136 return;
4137 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004138 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004139 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4140 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4141 S += '#';
4142 return;
4143 }
4144 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4145 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4146 S += '@';
4147 return;
4148 }
4149 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004150 }
Anders Carlssond8499822007-10-29 05:01:08 +00004151 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004152 getLegacyIntegralTypeEncoding(PointeeTy);
4153
Mike Stump11289f42009-09-09 15:08:12 +00004154 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004155 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004156 return;
4157 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004158
Chris Lattnere7cabb92009-07-13 00:10:46 +00004159 if (const ArrayType *AT =
4160 // Ignore type qualifiers etc.
4161 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004162 if (isa<IncompleteArrayType>(AT)) {
4163 // Incomplete arrays are encoded as a pointer to the array element.
4164 S += '^';
4165
Mike Stump11289f42009-09-09 15:08:12 +00004166 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004167 false, ExpandStructures, FD);
4168 } else {
4169 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004170
Anders Carlssond05f44b2009-02-22 01:38:57 +00004171 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4172 S += llvm::utostr(CAT->getSize().getZExtValue());
4173 else {
4174 //Variable length arrays are encoded as a regular array with 0 elements.
4175 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4176 S += '0';
4177 }
Mike Stump11289f42009-09-09 15:08:12 +00004178
4179 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004180 false, ExpandStructures, FD);
4181 S += ']';
4182 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004183 return;
4184 }
Mike Stump11289f42009-09-09 15:08:12 +00004185
John McCall9dd450b2009-09-21 23:43:11 +00004186 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004187 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004188 return;
4189 }
Mike Stump11289f42009-09-09 15:08:12 +00004190
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004191 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004192 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004193 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004194 // Anonymous structures print as '?'
4195 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4196 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004197 if (ClassTemplateSpecializationDecl *Spec
4198 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4199 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4200 std::string TemplateArgsStr
4201 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004202 TemplateArgs.data(),
4203 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004204 (*this).PrintingPolicy);
4205
4206 S += TemplateArgsStr;
4207 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004208 } else {
4209 S += '?';
4210 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004211 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004212 S += '=';
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004213 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4214 FieldEnd = RDecl->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +00004215 Field != FieldEnd; ++Field) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004216 if (FD) {
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004217 S += '"';
Douglas Gregor91f84212008-12-11 16:49:14 +00004218 S += Field->getNameAsString();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004219 S += '"';
4220 }
Mike Stump11289f42009-09-09 15:08:12 +00004221
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004222 // Special case bit-fields.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004223 if (Field->isBitField()) {
Mike Stump11289f42009-09-09 15:08:12 +00004224 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004225 (*Field));
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004226 } else {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004227 QualType qt = Field->getType();
4228 getLegacyIntegralTypeEncoding(qt);
Mike Stump11289f42009-09-09 15:08:12 +00004229 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004230 FD);
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004231 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004232 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004233 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004234 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004235 return;
4236 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004237
Chris Lattnere7cabb92009-07-13 00:10:46 +00004238 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004239 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004240 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004241 else
4242 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004243 return;
4244 }
Mike Stump11289f42009-09-09 15:08:12 +00004245
Chris Lattnere7cabb92009-07-13 00:10:46 +00004246 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004247 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004248 return;
4249 }
Mike Stump11289f42009-09-09 15:08:12 +00004250
John McCall8b07ec22010-05-15 11:32:37 +00004251 // Ignore protocol qualifiers when mangling at this level.
4252 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4253 T = OT->getBaseType();
4254
John McCall8ccfcb52009-09-24 19:53:00 +00004255 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004256 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004257 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004258 S += '{';
4259 const IdentifierInfo *II = OI->getIdentifier();
4260 S += II->getName();
4261 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004262 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4263 DeepCollectObjCIvars(OI, true, Ivars);
4264 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4265 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4266 if (Field->isBitField())
4267 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004268 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004269 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004270 }
4271 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004272 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004273 }
Mike Stump11289f42009-09-09 15:08:12 +00004274
John McCall9dd450b2009-09-21 23:43:11 +00004275 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004276 if (OPT->isObjCIdType()) {
4277 S += '@';
4278 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004279 }
Mike Stump11289f42009-09-09 15:08:12 +00004280
Steve Narofff0c86112009-10-28 22:03:49 +00004281 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4282 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4283 // Since this is a binary compatibility issue, need to consult with runtime
4284 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004285 S += '#';
4286 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004287 }
Mike Stump11289f42009-09-09 15:08:12 +00004288
Chris Lattnere7cabb92009-07-13 00:10:46 +00004289 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004290 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004291 ExpandPointedToStructures,
4292 ExpandStructures, FD);
4293 if (FD || EncodingProperty) {
4294 // Note that we do extended encoding of protocol qualifer list
4295 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004296 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004297 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4298 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004299 S += '<';
4300 S += (*I)->getNameAsString();
4301 S += '>';
4302 }
4303 S += '"';
4304 }
4305 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004306 }
Mike Stump11289f42009-09-09 15:08:12 +00004307
Chris Lattnere7cabb92009-07-13 00:10:46 +00004308 QualType PointeeTy = OPT->getPointeeType();
4309 if (!EncodingProperty &&
4310 isa<TypedefType>(PointeeTy.getTypePtr())) {
4311 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004312 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004313 // {...};
4314 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004315 getObjCEncodingForTypeImpl(PointeeTy, S,
4316 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004317 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004318 return;
4319 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004320
4321 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004322 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004323 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004324 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004325 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4326 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004327 S += '<';
4328 S += (*I)->getNameAsString();
4329 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004330 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004331 S += '"';
4332 }
4333 return;
4334 }
Mike Stump11289f42009-09-09 15:08:12 +00004335
John McCalla9e6e8d2010-05-17 23:56:34 +00004336 // gcc just blithely ignores member pointers.
4337 // TODO: maybe there should be a mangling for these
4338 if (T->getAs<MemberPointerType>())
4339 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004340
4341 if (T->isVectorType()) {
4342 // This matches gcc's encoding, even though technically it is
4343 // insufficient.
4344 // FIXME. We should do a better job than gcc.
4345 return;
4346 }
4347
Chris Lattnere7cabb92009-07-13 00:10:46 +00004348 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004349}
4350
Mike Stump11289f42009-09-09 15:08:12 +00004351void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004352 std::string& S) const {
4353 if (QT & Decl::OBJC_TQ_In)
4354 S += 'n';
4355 if (QT & Decl::OBJC_TQ_Inout)
4356 S += 'N';
4357 if (QT & Decl::OBJC_TQ_Out)
4358 S += 'o';
4359 if (QT & Decl::OBJC_TQ_Bycopy)
4360 S += 'O';
4361 if (QT & Decl::OBJC_TQ_Byref)
4362 S += 'R';
4363 if (QT & Decl::OBJC_TQ_Oneway)
4364 S += 'V';
4365}
4366
Chris Lattnere7cabb92009-07-13 00:10:46 +00004367void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004368 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004369
Anders Carlsson87c149b2007-10-11 01:00:40 +00004370 BuiltinVaListType = T;
4371}
4372
Chris Lattnere7cabb92009-07-13 00:10:46 +00004373void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004374 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004375}
4376
Chris Lattnere7cabb92009-07-13 00:10:46 +00004377void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004378 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004379}
4380
Chris Lattnere7cabb92009-07-13 00:10:46 +00004381void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004382 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004383}
4384
Chris Lattnere7cabb92009-07-13 00:10:46 +00004385void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004386 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004387}
4388
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004389void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004390 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004391 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004392
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004393 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004394}
4395
John McCalld28ae272009-12-02 08:04:21 +00004396/// \brief Retrieve the template name that corresponds to a non-empty
4397/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004398TemplateName
4399ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4400 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004401 unsigned size = End - Begin;
4402 assert(size > 1 && "set is not overloaded!");
4403
4404 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4405 size * sizeof(FunctionTemplateDecl*));
4406 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4407
4408 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004409 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004410 NamedDecl *D = *I;
4411 assert(isa<FunctionTemplateDecl>(D) ||
4412 (isa<UsingShadowDecl>(D) &&
4413 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4414 *Storage++ = D;
4415 }
4416
4417 return TemplateName(OT);
4418}
4419
Douglas Gregordc572a32009-03-30 22:58:21 +00004420/// \brief Retrieve the template name that represents a qualified
4421/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004422TemplateName
4423ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4424 bool TemplateKeyword,
4425 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004426 assert(NNS && "Missing nested-name-specifier in qualified template name");
4427
Douglas Gregorc42075a2010-02-04 18:10:26 +00004428 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004429 llvm::FoldingSetNodeID ID;
4430 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4431
4432 void *InsertPos = 0;
4433 QualifiedTemplateName *QTN =
4434 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4435 if (!QTN) {
4436 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4437 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4438 }
4439
4440 return TemplateName(QTN);
4441}
4442
4443/// \brief Retrieve the template name that represents a dependent
4444/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004445TemplateName
4446ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4447 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004448 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004449 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004450
4451 llvm::FoldingSetNodeID ID;
4452 DependentTemplateName::Profile(ID, NNS, Name);
4453
4454 void *InsertPos = 0;
4455 DependentTemplateName *QTN =
4456 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4457
4458 if (QTN)
4459 return TemplateName(QTN);
4460
4461 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4462 if (CanonNNS == NNS) {
4463 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4464 } else {
4465 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4466 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004467 DependentTemplateName *CheckQTN =
4468 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4469 assert(!CheckQTN && "Dependent type name canonicalization broken");
4470 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004471 }
4472
4473 DependentTemplateNames.InsertNode(QTN, InsertPos);
4474 return TemplateName(QTN);
4475}
4476
Douglas Gregor71395fa2009-11-04 00:56:37 +00004477/// \brief Retrieve the template name that represents a dependent
4478/// template name such as \c MetaFun::template operator+.
4479TemplateName
4480ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004481 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004482 assert((!NNS || NNS->isDependent()) &&
4483 "Nested name specifier must be dependent");
4484
4485 llvm::FoldingSetNodeID ID;
4486 DependentTemplateName::Profile(ID, NNS, Operator);
4487
4488 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004489 DependentTemplateName *QTN
4490 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004491
4492 if (QTN)
4493 return TemplateName(QTN);
4494
4495 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4496 if (CanonNNS == NNS) {
4497 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4498 } else {
4499 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4500 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004501
4502 DependentTemplateName *CheckQTN
4503 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4504 assert(!CheckQTN && "Dependent template name canonicalization broken");
4505 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004506 }
4507
4508 DependentTemplateNames.InsertNode(QTN, InsertPos);
4509 return TemplateName(QTN);
4510}
4511
Douglas Gregor5590be02011-01-15 06:45:20 +00004512TemplateName
4513ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4514 const TemplateArgument &ArgPack) const {
4515 ASTContext &Self = const_cast<ASTContext &>(*this);
4516 llvm::FoldingSetNodeID ID;
4517 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4518
4519 void *InsertPos = 0;
4520 SubstTemplateTemplateParmPackStorage *Subst
4521 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4522
4523 if (!Subst) {
4524 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4525 ArgPack.pack_size(),
4526 ArgPack.pack_begin());
4527 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4528 }
4529
4530 return TemplateName(Subst);
4531}
4532
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004533/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004534/// TargetInfo, produce the corresponding type. The unsigned @p Type
4535/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004536CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004537 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004538 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004539 case TargetInfo::SignedShort: return ShortTy;
4540 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4541 case TargetInfo::SignedInt: return IntTy;
4542 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4543 case TargetInfo::SignedLong: return LongTy;
4544 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4545 case TargetInfo::SignedLongLong: return LongLongTy;
4546 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4547 }
4548
4549 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004550 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004551}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004552
4553//===----------------------------------------------------------------------===//
4554// Type Predicates.
4555//===----------------------------------------------------------------------===//
4556
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004557/// isObjCNSObjectType - Return true if this is an NSObject object using
4558/// NSObject attribute on a c-style pointer type.
4559/// FIXME - Make it work directly on types.
Steve Naroff79d12152009-07-16 15:41:00 +00004560/// FIXME: Move to Type.
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004561///
4562bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCall424cec92011-01-19 06:33:43 +00004563 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004564 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004565 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004566 return true;
4567 }
Mike Stump11289f42009-09-09 15:08:12 +00004568 return false;
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004569}
4570
Fariborz Jahanian96207692009-02-18 21:49:28 +00004571/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4572/// garbage collection attribute.
4573///
John McCall553d45a2011-01-12 00:34:59 +00004574Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4575 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4576 return Qualifiers::GCNone;
4577
4578 assert(getLangOptions().ObjC1);
4579 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4580
4581 // Default behaviour under objective-C's gc is for ObjC pointers
4582 // (or pointers to them) be treated as though they were declared
4583 // as __strong.
4584 if (GCAttrs == Qualifiers::GCNone) {
4585 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4586 return Qualifiers::Strong;
4587 else if (Ty->isPointerType())
4588 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4589 } else {
4590 // It's not valid to set GC attributes on anything that isn't a
4591 // pointer.
4592#ifndef NDEBUG
4593 QualType CT = Ty->getCanonicalTypeInternal();
4594 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4595 CT = AT->getElementType();
4596 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4597#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004598 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004599 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004600}
4601
Chris Lattner49af6a42008-04-07 06:51:04 +00004602//===----------------------------------------------------------------------===//
4603// Type Compatibility Testing
4604//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004605
Mike Stump11289f42009-09-09 15:08:12 +00004606/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004607/// compatible.
4608static bool areCompatVectorTypes(const VectorType *LHS,
4609 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004610 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004611 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004612 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004613}
4614
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004615bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4616 QualType SecondVec) {
4617 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4618 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4619
4620 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4621 return true;
4622
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004623 // Treat Neon vector types and most AltiVec vector types as if they are the
4624 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004625 const VectorType *First = FirstVec->getAs<VectorType>();
4626 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004627 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004628 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004629 First->getVectorKind() != VectorType::AltiVecPixel &&
4630 First->getVectorKind() != VectorType::AltiVecBool &&
4631 Second->getVectorKind() != VectorType::AltiVecPixel &&
4632 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004633 return true;
4634
4635 return false;
4636}
4637
Steve Naroff8e6aee52009-07-23 01:01:38 +00004638//===----------------------------------------------------------------------===//
4639// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4640//===----------------------------------------------------------------------===//
4641
4642/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4643/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004644bool
4645ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4646 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004647 if (lProto == rProto)
4648 return true;
4649 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4650 E = rProto->protocol_end(); PI != E; ++PI)
4651 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4652 return true;
4653 return false;
4654}
4655
Steve Naroff8e6aee52009-07-23 01:01:38 +00004656/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4657/// return true if lhs's protocols conform to rhs's protocol; false
4658/// otherwise.
4659bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4660 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4661 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4662 return false;
4663}
4664
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004665/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4666/// Class<p1, ...>.
4667bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4668 QualType rhs) {
4669 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4670 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4671 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4672
4673 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4674 E = lhsQID->qual_end(); I != E; ++I) {
4675 bool match = false;
4676 ObjCProtocolDecl *lhsProto = *I;
4677 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4678 E = rhsOPT->qual_end(); J != E; ++J) {
4679 ObjCProtocolDecl *rhsProto = *J;
4680 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4681 match = true;
4682 break;
4683 }
4684 }
4685 if (!match)
4686 return false;
4687 }
4688 return true;
4689}
4690
Steve Naroff8e6aee52009-07-23 01:01:38 +00004691/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4692/// ObjCQualifiedIDType.
4693bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4694 bool compare) {
4695 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004696 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004697 lhs->isObjCIdType() || lhs->isObjCClassType())
4698 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004699 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004700 rhs->isObjCIdType() || rhs->isObjCClassType())
4701 return true;
4702
4703 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004704 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004705
Steve Naroff8e6aee52009-07-23 01:01:38 +00004706 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004707
Steve Naroff8e6aee52009-07-23 01:01:38 +00004708 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004709 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004710 // make sure we check the class hierarchy.
4711 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4712 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4713 E = lhsQID->qual_end(); I != E; ++I) {
4714 // when comparing an id<P> on lhs with a static type on rhs,
4715 // see if static class implements all of id's protocols, directly or
4716 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004717 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004718 return false;
4719 }
4720 }
4721 // If there are no qualifiers and no interface, we have an 'id'.
4722 return true;
4723 }
Mike Stump11289f42009-09-09 15:08:12 +00004724 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004725 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4726 E = lhsQID->qual_end(); I != E; ++I) {
4727 ObjCProtocolDecl *lhsProto = *I;
4728 bool match = false;
4729
4730 // when comparing an id<P> on lhs with a static type on rhs,
4731 // see if static class implements all of id's protocols, directly or
4732 // through its super class and categories.
4733 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4734 E = rhsOPT->qual_end(); J != E; ++J) {
4735 ObjCProtocolDecl *rhsProto = *J;
4736 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4737 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4738 match = true;
4739 break;
4740 }
4741 }
Mike Stump11289f42009-09-09 15:08:12 +00004742 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004743 // make sure we check the class hierarchy.
4744 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4745 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4746 E = lhsQID->qual_end(); I != E; ++I) {
4747 // when comparing an id<P> on lhs with a static type on rhs,
4748 // see if static class implements all of id's protocols, directly or
4749 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004750 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004751 match = true;
4752 break;
4753 }
4754 }
4755 }
4756 if (!match)
4757 return false;
4758 }
Mike Stump11289f42009-09-09 15:08:12 +00004759
Steve Naroff8e6aee52009-07-23 01:01:38 +00004760 return true;
4761 }
Mike Stump11289f42009-09-09 15:08:12 +00004762
Steve Naroff8e6aee52009-07-23 01:01:38 +00004763 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4764 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4765
Mike Stump11289f42009-09-09 15:08:12 +00004766 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00004767 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004768 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004769 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4770 E = lhsOPT->qual_end(); I != E; ++I) {
4771 ObjCProtocolDecl *lhsProto = *I;
4772 bool match = false;
4773
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004774 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00004775 // see if static class implements all of id's protocols, directly or
4776 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004777 // First, lhs protocols in the qualifier list must be found, direct
4778 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004779 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4780 E = rhsQID->qual_end(); J != E; ++J) {
4781 ObjCProtocolDecl *rhsProto = *J;
4782 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4783 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4784 match = true;
4785 break;
4786 }
4787 }
4788 if (!match)
4789 return false;
4790 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00004791
4792 // Static class's protocols, or its super class or category protocols
4793 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4794 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4795 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4796 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4797 // This is rather dubious but matches gcc's behavior. If lhs has
4798 // no type qualifier and its class has no static protocol(s)
4799 // assume that it is mismatch.
4800 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4801 return false;
4802 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4803 LHSInheritedProtocols.begin(),
4804 E = LHSInheritedProtocols.end(); I != E; ++I) {
4805 bool match = false;
4806 ObjCProtocolDecl *lhsProto = (*I);
4807 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4808 E = rhsQID->qual_end(); J != E; ++J) {
4809 ObjCProtocolDecl *rhsProto = *J;
4810 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4811 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4812 match = true;
4813 break;
4814 }
4815 }
4816 if (!match)
4817 return false;
4818 }
4819 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00004820 return true;
4821 }
4822 return false;
4823}
4824
Eli Friedman47f77112008-08-22 00:56:42 +00004825/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004826/// compatible for assignment from RHS to LHS. This handles validation of any
4827/// protocol qualifiers on the LHS or RHS.
4828///
Steve Naroff7cae42b2009-07-10 23:34:53 +00004829bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4830 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00004831 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4832 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4833
Steve Naroff1329fa02009-07-15 18:40:39 +00004834 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00004835 if (LHS->isObjCUnqualifiedIdOrClass() ||
4836 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004837 return true;
4838
John McCall8b07ec22010-05-15 11:32:37 +00004839 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00004840 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4841 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00004842 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004843
4844 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4845 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4846 QualType(RHSOPT,0));
4847
John McCall8b07ec22010-05-15 11:32:37 +00004848 // If we have 2 user-defined types, fall into that path.
4849 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00004850 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00004851
Steve Naroff8e6aee52009-07-23 01:01:38 +00004852 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004853}
4854
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004855/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4856/// for providing type-safty for objective-c pointers used to pass/return
4857/// arguments in block literals. When passed as arguments, passing 'A*' where
4858/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4859/// not OK. For the return type, the opposite is not OK.
4860bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4861 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00004862 const ObjCObjectPointerType *RHSOPT,
4863 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004864 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004865 return true;
4866
4867 if (LHSOPT->isObjCBuiltinType()) {
4868 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4869 }
4870
Fariborz Jahanian440a6832010-04-06 17:23:39 +00004871 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004872 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4873 QualType(RHSOPT,0),
4874 false);
4875
4876 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4877 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4878 if (LHS && RHS) { // We have 2 user-defined types.
4879 if (LHS != RHS) {
4880 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00004881 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004882 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00004883 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00004884 }
4885 else
4886 return true;
4887 }
4888 return false;
4889}
4890
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004891/// getIntersectionOfProtocols - This routine finds the intersection of set
4892/// of protocols inherited from two distinct objective-c pointer objects.
4893/// It is used to build composite qualifier list of the composite type of
4894/// the conditional expression involving two objective-c pointer objects.
4895static
4896void getIntersectionOfProtocols(ASTContext &Context,
4897 const ObjCObjectPointerType *LHSOPT,
4898 const ObjCObjectPointerType *RHSOPT,
4899 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4900
John McCall8b07ec22010-05-15 11:32:37 +00004901 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4902 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4903 assert(LHS->getInterface() && "LHS must have an interface base");
4904 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004905
4906 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4907 unsigned LHSNumProtocols = LHS->getNumProtocols();
4908 if (LHSNumProtocols > 0)
4909 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4910 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004911 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004912 Context.CollectInheritedProtocols(LHS->getInterface(),
4913 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004914 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4915 LHSInheritedProtocols.end());
4916 }
4917
4918 unsigned RHSNumProtocols = RHS->getNumProtocols();
4919 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00004920 ObjCProtocolDecl **RHSProtocols =
4921 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004922 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4923 if (InheritedProtocolSet.count(RHSProtocols[i]))
4924 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4925 }
4926 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004927 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00004928 Context.CollectInheritedProtocols(RHS->getInterface(),
4929 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00004930 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4931 RHSInheritedProtocols.begin(),
4932 E = RHSInheritedProtocols.end(); I != E; ++I)
4933 if (InheritedProtocolSet.count((*I)))
4934 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004935 }
4936}
4937
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004938/// areCommonBaseCompatible - Returns common base class of the two classes if
4939/// one found. Note that this is O'2 algorithm. But it will be called as the
4940/// last type comparison in a ?-exp of ObjC pointer types before a
4941/// warning is issued. So, its invokation is extremely rare.
4942QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00004943 const ObjCObjectPointerType *Lptr,
4944 const ObjCObjectPointerType *Rptr) {
4945 const ObjCObjectType *LHS = Lptr->getObjectType();
4946 const ObjCObjectType *RHS = Rptr->getObjectType();
4947 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4948 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4949 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004950 return QualType();
4951
John McCall8b07ec22010-05-15 11:32:37 +00004952 while ((LDecl = LDecl->getSuperClass())) {
4953 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004954 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00004955 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4956 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4957
4958 QualType Result = QualType(LHS, 0);
4959 if (!Protocols.empty())
4960 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4961 Result = getObjCObjectPointerType(Result);
4962 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00004963 }
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004964 }
4965
4966 return QualType();
4967}
4968
John McCall8b07ec22010-05-15 11:32:37 +00004969bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4970 const ObjCObjectType *RHS) {
4971 assert(LHS->getInterface() && "LHS is not an interface type");
4972 assert(RHS->getInterface() && "RHS is not an interface type");
4973
Chris Lattner49af6a42008-04-07 06:51:04 +00004974 // Verify that the base decls are compatible: the RHS must be a subclass of
4975 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00004976 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00004977 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004978
Chris Lattner49af6a42008-04-07 06:51:04 +00004979 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4980 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00004981 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00004982 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004983
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00004984 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
4985 // more detailed analysis is required.
4986 if (RHS->getNumProtocols() == 0) {
4987 // OK, if LHS is a superclass of RHS *and*
4988 // this superclass is assignment compatible with LHS.
4989 // false otherwise.
4990 ObjCInterfaceDecl *SuperClass =
4991 RHS->getInterface()->getImmSubClassOf(LHS->getInterface());
4992 if (SuperClass) {
4993 // OK if conversion of LHS to SuperClass results in narrowing of types
4994 // ; i.e., SuperClass may implement at least one of the protocols
4995 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
4996 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
4997 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
4998 CollectInheritedProtocols(SuperClass, SuperClassInheritedProtocols);
4999 // If super class has no protocols, it is not a match.
5000 if (SuperClassInheritedProtocols.empty())
5001 return false;
5002
5003 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5004 LHSPE = LHS->qual_end();
5005 LHSPI != LHSPE; LHSPI++) {
5006 bool SuperImplementsProtocol = false;
5007 ObjCProtocolDecl *LHSProto = (*LHSPI);
5008
5009 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5010 SuperClassInheritedProtocols.begin(),
5011 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5012 ObjCProtocolDecl *SuperClassProto = (*I);
5013 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5014 SuperImplementsProtocol = true;
5015 break;
5016 }
5017 }
5018 if (!SuperImplementsProtocol)
5019 return false;
5020 }
5021 return true;
5022 }
5023 return false;
5024 }
Mike Stump11289f42009-09-09 15:08:12 +00005025
John McCall8b07ec22010-05-15 11:32:37 +00005026 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5027 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005028 LHSPI != LHSPE; LHSPI++) {
5029 bool RHSImplementsProtocol = false;
5030
5031 // If the RHS doesn't implement the protocol on the left, the types
5032 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005033 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5034 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005035 RHSPI != RHSPE; RHSPI++) {
5036 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005037 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005038 break;
5039 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005040 }
5041 // FIXME: For better diagnostics, consider passing back the protocol name.
5042 if (!RHSImplementsProtocol)
5043 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005044 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005045 // The RHS implements all protocols listed on the LHS.
5046 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005047}
5048
Steve Naroffb7605152009-02-12 17:52:19 +00005049bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5050 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005051 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5052 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005053
Steve Naroff7cae42b2009-07-10 23:34:53 +00005054 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005055 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005056
5057 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5058 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005059}
5060
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005061bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5062 return canAssignObjCInterfaces(
5063 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5064 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5065}
5066
Mike Stump11289f42009-09-09 15:08:12 +00005067/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005068/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005069/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005070/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005071bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5072 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005073 if (getLangOptions().CPlusPlus)
5074 return hasSameType(LHS, RHS);
5075
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005076 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005077}
5078
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005079bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5080 return !mergeTypes(LHS, RHS, true).isNull();
5081}
5082
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005083/// mergeTransparentUnionType - if T is a transparent union type and a member
5084/// of T is compatible with SubType, return the merged type, else return
5085/// QualType()
5086QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5087 bool OfBlockPointer,
5088 bool Unqualified) {
5089 if (const RecordType *UT = T->getAsUnionType()) {
5090 RecordDecl *UD = UT->getDecl();
5091 if (UD->hasAttr<TransparentUnionAttr>()) {
5092 for (RecordDecl::field_iterator it = UD->field_begin(),
5093 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005094 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005095 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5096 if (!MT.isNull())
5097 return MT;
5098 }
5099 }
5100 }
5101
5102 return QualType();
5103}
5104
5105/// mergeFunctionArgumentTypes - merge two types which appear as function
5106/// argument types
5107QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5108 bool OfBlockPointer,
5109 bool Unqualified) {
5110 // GNU extension: two types are compatible if they appear as a function
5111 // argument, one of the types is a transparent union type and the other
5112 // type is compatible with a union member
5113 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5114 Unqualified);
5115 if (!lmerge.isNull())
5116 return lmerge;
5117
5118 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5119 Unqualified);
5120 if (!rmerge.isNull())
5121 return rmerge;
5122
5123 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5124}
5125
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005126QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005127 bool OfBlockPointer,
5128 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005129 const FunctionType *lbase = lhs->getAs<FunctionType>();
5130 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005131 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5132 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005133 bool allLTypes = true;
5134 bool allRTypes = true;
5135
5136 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005137 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005138 if (OfBlockPointer) {
5139 QualType RHS = rbase->getResultType();
5140 QualType LHS = lbase->getResultType();
5141 bool UnqualifiedResult = Unqualified;
5142 if (!UnqualifiedResult)
5143 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005144 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005145 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005146 else
John McCall8c6b56f2010-12-15 01:06:38 +00005147 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5148 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005149 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005150
5151 if (Unqualified)
5152 retType = retType.getUnqualifiedType();
5153
5154 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5155 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5156 if (Unqualified) {
5157 LRetType = LRetType.getUnqualifiedType();
5158 RRetType = RRetType.getUnqualifiedType();
5159 }
5160
5161 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005162 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005163 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005164 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005165
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005166 // FIXME: double check this
5167 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5168 // rbase->getRegParmAttr() != 0 &&
5169 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005170 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5171 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005172
Douglas Gregor8c940862010-01-18 17:14:39 +00005173 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005174 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005175 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005176
John McCall8c6b56f2010-12-15 01:06:38 +00005177 // Regparm is part of the calling convention.
5178 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5179 return QualType();
5180
5181 // It's noreturn if either type is.
5182 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5183 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5184 if (NoReturn != lbaseInfo.getNoReturn())
5185 allLTypes = false;
5186 if (NoReturn != rbaseInfo.getNoReturn())
5187 allRTypes = false;
5188
5189 FunctionType::ExtInfo einfo(NoReturn,
5190 lbaseInfo.getRegParm(),
5191 lbaseInfo.getCC());
John McCalldb40c7f2010-12-14 08:05:40 +00005192
Eli Friedman47f77112008-08-22 00:56:42 +00005193 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005194 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5195 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005196 unsigned lproto_nargs = lproto->getNumArgs();
5197 unsigned rproto_nargs = rproto->getNumArgs();
5198
5199 // Compatible functions must have the same number of arguments
5200 if (lproto_nargs != rproto_nargs)
5201 return QualType();
5202
5203 // Variadic and non-variadic functions aren't compatible
5204 if (lproto->isVariadic() != rproto->isVariadic())
5205 return QualType();
5206
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005207 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5208 return QualType();
5209
Eli Friedman47f77112008-08-22 00:56:42 +00005210 // Check argument compatibility
5211 llvm::SmallVector<QualType, 10> types;
5212 for (unsigned i = 0; i < lproto_nargs; i++) {
5213 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5214 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005215 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5216 OfBlockPointer,
5217 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005218 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005219
5220 if (Unqualified)
5221 argtype = argtype.getUnqualifiedType();
5222
Eli Friedman47f77112008-08-22 00:56:42 +00005223 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005224 if (Unqualified) {
5225 largtype = largtype.getUnqualifiedType();
5226 rargtype = rargtype.getUnqualifiedType();
5227 }
5228
Chris Lattner465fa322008-10-05 17:34:18 +00005229 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5230 allLTypes = false;
5231 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5232 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005233 }
5234 if (allLTypes) return lhs;
5235 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005236
5237 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5238 EPI.ExtInfo = einfo;
5239 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005240 }
5241
5242 if (lproto) allRTypes = false;
5243 if (rproto) allLTypes = false;
5244
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005245 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005246 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005247 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005248 if (proto->isVariadic()) return QualType();
5249 // Check that the types are compatible with the types that
5250 // would result from default argument promotions (C99 6.7.5.3p15).
5251 // The only types actually affected are promotable integer
5252 // types and floats, which would be passed as a different
5253 // type depending on whether the prototype is visible.
5254 unsigned proto_nargs = proto->getNumArgs();
5255 for (unsigned i = 0; i < proto_nargs; ++i) {
5256 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005257
5258 // Look at the promotion type of enum types, since that is the type used
5259 // to pass enum values.
5260 if (const EnumType *Enum = argTy->getAs<EnumType>())
5261 argTy = Enum->getDecl()->getPromotionType();
5262
Eli Friedman47f77112008-08-22 00:56:42 +00005263 if (argTy->isPromotableIntegerType() ||
5264 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5265 return QualType();
5266 }
5267
5268 if (allLTypes) return lhs;
5269 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005270
5271 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5272 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005273 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005274 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005275 }
5276
5277 if (allLTypes) return lhs;
5278 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005279 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005280}
5281
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005282QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005283 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005284 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005285 // C++ [expr]: If an expression initially has the type "reference to T", the
5286 // type is adjusted to "T" prior to any further analysis, the expression
5287 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005288 // expression is an lvalue unless the reference is an rvalue reference and
5289 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005290 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5291 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005292
5293 if (Unqualified) {
5294 LHS = LHS.getUnqualifiedType();
5295 RHS = RHS.getUnqualifiedType();
5296 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005297
Eli Friedman47f77112008-08-22 00:56:42 +00005298 QualType LHSCan = getCanonicalType(LHS),
5299 RHSCan = getCanonicalType(RHS);
5300
5301 // If two types are identical, they are compatible.
5302 if (LHSCan == RHSCan)
5303 return LHS;
5304
John McCall8ccfcb52009-09-24 19:53:00 +00005305 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005306 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5307 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005308 if (LQuals != RQuals) {
5309 // If any of these qualifiers are different, we have a type
5310 // mismatch.
5311 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5312 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5313 return QualType();
5314
5315 // Exactly one GC qualifier difference is allowed: __strong is
5316 // okay if the other type has no GC qualifier but is an Objective
5317 // C object pointer (i.e. implicitly strong by default). We fix
5318 // this by pretending that the unqualified type was actually
5319 // qualified __strong.
5320 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5321 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5322 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5323
5324 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5325 return QualType();
5326
5327 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5328 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5329 }
5330 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5331 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5332 }
Eli Friedman47f77112008-08-22 00:56:42 +00005333 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005334 }
5335
5336 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005337
Eli Friedmandcca6332009-06-01 01:22:52 +00005338 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5339 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005340
Chris Lattnerfd652912008-01-14 05:45:46 +00005341 // We want to consider the two function types to be the same for these
5342 // comparisons, just force one to the other.
5343 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5344 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005345
5346 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005347 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5348 LHSClass = Type::ConstantArray;
5349 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5350 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005351
John McCall8b07ec22010-05-15 11:32:37 +00005352 // ObjCInterfaces are just specialized ObjCObjects.
5353 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5354 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5355
Nate Begemance4d7fc2008-04-18 23:10:10 +00005356 // Canonicalize ExtVector -> Vector.
5357 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5358 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005359
Chris Lattner95554662008-04-07 05:43:21 +00005360 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005361 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005362 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005363 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005364 // Compatibility is based on the underlying type, not the promotion
5365 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005366 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005367 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5368 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005369 }
John McCall9dd450b2009-09-21 23:43:11 +00005370 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005371 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5372 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005373 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005374
Eli Friedman47f77112008-08-22 00:56:42 +00005375 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005376 }
Eli Friedman47f77112008-08-22 00:56:42 +00005377
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005378 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005379 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005380#define TYPE(Class, Base)
5381#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005382#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005383#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5384#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5385#include "clang/AST/TypeNodes.def"
5386 assert(false && "Non-canonical and dependent types shouldn't get here");
5387 return QualType();
5388
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005389 case Type::LValueReference:
5390 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005391 case Type::MemberPointer:
5392 assert(false && "C++ should never be in mergeTypes");
5393 return QualType();
5394
John McCall8b07ec22010-05-15 11:32:37 +00005395 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005396 case Type::IncompleteArray:
5397 case Type::VariableArray:
5398 case Type::FunctionProto:
5399 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005400 assert(false && "Types are eliminated above");
5401 return QualType();
5402
Chris Lattnerfd652912008-01-14 05:45:46 +00005403 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005404 {
5405 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005406 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5407 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005408 if (Unqualified) {
5409 LHSPointee = LHSPointee.getUnqualifiedType();
5410 RHSPointee = RHSPointee.getUnqualifiedType();
5411 }
5412 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5413 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005414 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005415 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005416 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005417 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005418 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005419 return getPointerType(ResultType);
5420 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005421 case Type::BlockPointer:
5422 {
5423 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005424 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5425 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005426 if (Unqualified) {
5427 LHSPointee = LHSPointee.getUnqualifiedType();
5428 RHSPointee = RHSPointee.getUnqualifiedType();
5429 }
5430 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5431 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005432 if (ResultType.isNull()) return QualType();
5433 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5434 return LHS;
5435 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5436 return RHS;
5437 return getBlockPointerType(ResultType);
5438 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005439 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005440 {
5441 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5442 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5443 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5444 return QualType();
5445
5446 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5447 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005448 if (Unqualified) {
5449 LHSElem = LHSElem.getUnqualifiedType();
5450 RHSElem = RHSElem.getUnqualifiedType();
5451 }
5452
5453 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005454 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005455 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5456 return LHS;
5457 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5458 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005459 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5460 ArrayType::ArraySizeModifier(), 0);
5461 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5462 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005463 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5464 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005465 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5466 return LHS;
5467 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5468 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005469 if (LVAT) {
5470 // FIXME: This isn't correct! But tricky to implement because
5471 // the array's size has to be the size of LHS, but the type
5472 // has to be different.
5473 return LHS;
5474 }
5475 if (RVAT) {
5476 // FIXME: This isn't correct! But tricky to implement because
5477 // the array's size has to be the size of RHS, but the type
5478 // has to be different.
5479 return RHS;
5480 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005481 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5482 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005483 return getIncompleteArrayType(ResultType,
5484 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005485 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005486 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005487 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005488 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005489 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005490 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005491 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005492 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005493 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005494 case Type::Complex:
5495 // Distinct complex types are incompatible.
5496 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005497 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005498 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005499 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5500 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005501 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005502 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005503 case Type::ObjCObject: {
5504 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005505 // FIXME: This should be type compatibility, e.g. whether
5506 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005507 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5508 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5509 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005510 return LHS;
5511
Eli Friedman47f77112008-08-22 00:56:42 +00005512 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005513 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005514 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005515 if (OfBlockPointer) {
5516 if (canAssignObjCInterfacesInBlockPointer(
5517 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005518 RHS->getAs<ObjCObjectPointerType>(),
5519 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005520 return LHS;
5521 return QualType();
5522 }
John McCall9dd450b2009-09-21 23:43:11 +00005523 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5524 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005525 return LHS;
5526
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005527 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005528 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005529 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005530
5531 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005532}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005533
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005534/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5535/// 'RHS' attributes and returns the merged version; including for function
5536/// return types.
5537QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5538 QualType LHSCan = getCanonicalType(LHS),
5539 RHSCan = getCanonicalType(RHS);
5540 // If two types are identical, they are compatible.
5541 if (LHSCan == RHSCan)
5542 return LHS;
5543 if (RHSCan->isFunctionType()) {
5544 if (!LHSCan->isFunctionType())
5545 return QualType();
5546 QualType OldReturnType =
5547 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5548 QualType NewReturnType =
5549 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5550 QualType ResReturnType =
5551 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5552 if (ResReturnType.isNull())
5553 return QualType();
5554 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5555 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5556 // In either case, use OldReturnType to build the new function type.
5557 const FunctionType *F = LHS->getAs<FunctionType>();
5558 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005559 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5560 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005561 QualType ResultType
5562 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005563 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005564 return ResultType;
5565 }
5566 }
5567 return QualType();
5568 }
5569
5570 // If the qualifiers are different, the types can still be merged.
5571 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5572 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5573 if (LQuals != RQuals) {
5574 // If any of these qualifiers are different, we have a type mismatch.
5575 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5576 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5577 return QualType();
5578
5579 // Exactly one GC qualifier difference is allowed: __strong is
5580 // okay if the other type has no GC qualifier but is an Objective
5581 // C object pointer (i.e. implicitly strong by default). We fix
5582 // this by pretending that the unqualified type was actually
5583 // qualified __strong.
5584 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5585 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5586 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5587
5588 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5589 return QualType();
5590
5591 if (GC_L == Qualifiers::Strong)
5592 return LHS;
5593 if (GC_R == Qualifiers::Strong)
5594 return RHS;
5595 return QualType();
5596 }
5597
5598 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5599 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5600 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5601 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5602 if (ResQT == LHSBaseQT)
5603 return LHS;
5604 if (ResQT == RHSBaseQT)
5605 return RHS;
5606 }
5607 return QualType();
5608}
5609
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005610//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005611// Integer Predicates
5612//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005613
Jay Foad39c79802011-01-12 09:06:06 +00005614unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005615 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005616 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005617 if (T->isBooleanType())
5618 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005619 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005620 return (unsigned)getTypeSize(T);
5621}
5622
5623QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005624 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005625
5626 // Turn <4 x signed int> -> <4 x unsigned int>
5627 if (const VectorType *VTy = T->getAs<VectorType>())
5628 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005629 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005630
5631 // For enums, we return the unsigned version of the base type.
5632 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005633 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005634
5635 const BuiltinType *BTy = T->getAs<BuiltinType>();
5636 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005637 switch (BTy->getKind()) {
5638 case BuiltinType::Char_S:
5639 case BuiltinType::SChar:
5640 return UnsignedCharTy;
5641 case BuiltinType::Short:
5642 return UnsignedShortTy;
5643 case BuiltinType::Int:
5644 return UnsignedIntTy;
5645 case BuiltinType::Long:
5646 return UnsignedLongTy;
5647 case BuiltinType::LongLong:
5648 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005649 case BuiltinType::Int128:
5650 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005651 default:
5652 assert(0 && "Unexpected signed integer type");
5653 return QualType();
5654 }
5655}
5656
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005657ASTMutationListener::~ASTMutationListener() { }
5658
Chris Lattnerecd79c62009-06-14 00:45:47 +00005659
5660//===----------------------------------------------------------------------===//
5661// Builtin Type Computation
5662//===----------------------------------------------------------------------===//
5663
5664/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005665/// pointer over the consumed characters. This returns the resultant type. If
5666/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5667/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5668/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005669///
5670/// RequiresICE is filled in on return to indicate whether the value is required
5671/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005672static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005673 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005674 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005675 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005676 // Modifiers.
5677 int HowLong = 0;
5678 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005679 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005680
Chris Lattnerdc226c22010-10-01 22:42:38 +00005681 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005682 bool Done = false;
5683 while (!Done) {
5684 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005685 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005686 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005687 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005688 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005689 case 'S':
5690 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5691 assert(!Signed && "Can't use 'S' modifier multiple times!");
5692 Signed = true;
5693 break;
5694 case 'U':
5695 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5696 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5697 Unsigned = true;
5698 break;
5699 case 'L':
5700 assert(HowLong <= 2 && "Can't have LLLL modifier");
5701 ++HowLong;
5702 break;
5703 }
5704 }
5705
5706 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005707
Chris Lattnerecd79c62009-06-14 00:45:47 +00005708 // Read the base type.
5709 switch (*Str++) {
5710 default: assert(0 && "Unknown builtin type letter!");
5711 case 'v':
5712 assert(HowLong == 0 && !Signed && !Unsigned &&
5713 "Bad modifiers used with 'v'!");
5714 Type = Context.VoidTy;
5715 break;
5716 case 'f':
5717 assert(HowLong == 0 && !Signed && !Unsigned &&
5718 "Bad modifiers used with 'f'!");
5719 Type = Context.FloatTy;
5720 break;
5721 case 'd':
5722 assert(HowLong < 2 && !Signed && !Unsigned &&
5723 "Bad modifiers used with 'd'!");
5724 if (HowLong)
5725 Type = Context.LongDoubleTy;
5726 else
5727 Type = Context.DoubleTy;
5728 break;
5729 case 's':
5730 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5731 if (Unsigned)
5732 Type = Context.UnsignedShortTy;
5733 else
5734 Type = Context.ShortTy;
5735 break;
5736 case 'i':
5737 if (HowLong == 3)
5738 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5739 else if (HowLong == 2)
5740 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5741 else if (HowLong == 1)
5742 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5743 else
5744 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5745 break;
5746 case 'c':
5747 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5748 if (Signed)
5749 Type = Context.SignedCharTy;
5750 else if (Unsigned)
5751 Type = Context.UnsignedCharTy;
5752 else
5753 Type = Context.CharTy;
5754 break;
5755 case 'b': // boolean
5756 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5757 Type = Context.BoolTy;
5758 break;
5759 case 'z': // size_t.
5760 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5761 Type = Context.getSizeType();
5762 break;
5763 case 'F':
5764 Type = Context.getCFConstantStringType();
5765 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00005766 case 'G':
5767 Type = Context.getObjCIdType();
5768 break;
5769 case 'H':
5770 Type = Context.getObjCSelType();
5771 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005772 case 'a':
5773 Type = Context.getBuiltinVaListType();
5774 assert(!Type.isNull() && "builtin va list type not initialized!");
5775 break;
5776 case 'A':
5777 // This is a "reference" to a va_list; however, what exactly
5778 // this means depends on how va_list is defined. There are two
5779 // different kinds of va_list: ones passed by value, and ones
5780 // passed by reference. An example of a by-value va_list is
5781 // x86, where va_list is a char*. An example of by-ref va_list
5782 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5783 // we want this argument to be a char*&; for x86-64, we want
5784 // it to be a __va_list_tag*.
5785 Type = Context.getBuiltinVaListType();
5786 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005787 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00005788 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005789 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00005790 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005791 break;
5792 case 'V': {
5793 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005794 unsigned NumElements = strtoul(Str, &End, 10);
5795 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00005796 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00005797
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005798 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5799 RequiresICE, false);
5800 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00005801
5802 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00005803 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00005804 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005805 break;
5806 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005807 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005808 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5809 false);
5810 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00005811 Type = Context.getComplexType(ElementType);
5812 break;
5813 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00005814 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00005815 Type = Context.getFILEType();
5816 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005817 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005818 return QualType();
5819 }
Mike Stump2adb4da2009-07-28 23:47:15 +00005820 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00005821 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00005822 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00005823 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00005824 else
5825 Type = Context.getjmp_bufType();
5826
Mike Stump2adb4da2009-07-28 23:47:15 +00005827 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00005828 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00005829 return QualType();
5830 }
5831 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00005832 }
Mike Stump11289f42009-09-09 15:08:12 +00005833
Chris Lattnerdc226c22010-10-01 22:42:38 +00005834 // If there are modifiers and if we're allowed to parse them, go for it.
5835 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005836 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00005837 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005838 default: Done = true; --Str; break;
5839 case '*':
5840 case '&': {
5841 // Both pointers and references can have their pointee types
5842 // qualified with an address space.
5843 char *End;
5844 unsigned AddrSpace = strtoul(Str, &End, 10);
5845 if (End != Str && AddrSpace != 0) {
5846 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5847 Str = End;
5848 }
5849 if (c == '*')
5850 Type = Context.getPointerType(Type);
5851 else
5852 Type = Context.getLValueReferenceType(Type);
5853 break;
5854 }
5855 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5856 case 'C':
5857 Type = Type.withConst();
5858 break;
5859 case 'D':
5860 Type = Context.getVolatileType(Type);
5861 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005862 }
5863 }
Chris Lattner84733392010-10-01 07:13:18 +00005864
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005865 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00005866 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00005867
Chris Lattnerecd79c62009-06-14 00:45:47 +00005868 return Type;
5869}
5870
5871/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00005872QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005873 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00005874 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00005875 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00005876
Chris Lattnerecd79c62009-06-14 00:45:47 +00005877 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00005878
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005879 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005880 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005881 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5882 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005883 if (Error != GE_None)
5884 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005885
5886 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5887
Chris Lattnerecd79c62009-06-14 00:45:47 +00005888 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005889 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005890 if (Error != GE_None)
5891 return QualType();
5892
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005893 // If this argument is required to be an IntegerConstantExpression and the
5894 // caller cares, fill in the bitmask we return.
5895 if (RequiresICE && IntegerConstantArgs)
5896 *IntegerConstantArgs |= 1 << ArgTypes.size();
5897
Chris Lattnerecd79c62009-06-14 00:45:47 +00005898 // Do array -> pointer decay. The builtin should use the decayed type.
5899 if (Ty->isArrayType())
5900 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00005901
Chris Lattnerecd79c62009-06-14 00:45:47 +00005902 ArgTypes.push_back(Ty);
5903 }
5904
5905 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5906 "'.' should only occur at end of builtin type list!");
5907
John McCall991eb4b2010-12-21 00:44:39 +00005908 FunctionType::ExtInfo EI;
5909 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5910
5911 bool Variadic = (TypeStr[0] == '.');
5912
5913 // We really shouldn't be making a no-proto type here, especially in C++.
5914 if (ArgTypes.empty() && Variadic)
5915 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00005916
John McCalldb40c7f2010-12-14 08:05:40 +00005917 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00005918 EPI.ExtInfo = EI;
5919 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00005920
5921 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00005922}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005923
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005924GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5925 GVALinkage External = GVA_StrongExternal;
5926
5927 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00005928 switch (L) {
5929 case NoLinkage:
5930 case InternalLinkage:
5931 case UniqueExternalLinkage:
5932 return GVA_Internal;
5933
5934 case ExternalLinkage:
5935 switch (FD->getTemplateSpecializationKind()) {
5936 case TSK_Undeclared:
5937 case TSK_ExplicitSpecialization:
5938 External = GVA_StrongExternal;
5939 break;
5940
5941 case TSK_ExplicitInstantiationDefinition:
5942 return GVA_ExplicitTemplateInstantiation;
5943
5944 case TSK_ExplicitInstantiationDeclaration:
5945 case TSK_ImplicitInstantiation:
5946 External = GVA_TemplateInstantiation;
5947 break;
5948 }
5949 }
5950
5951 if (!FD->isInlined())
5952 return External;
5953
5954 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5955 // GNU or C99 inline semantics. Determine whether this symbol should be
5956 // externally visible.
5957 if (FD->isInlineDefinitionExternallyVisible())
5958 return External;
5959
5960 // C99 inline semantics, where the symbol is not externally visible.
5961 return GVA_C99Inline;
5962 }
5963
5964 // C++0x [temp.explicit]p9:
5965 // [ Note: The intent is that an inline function that is the subject of
5966 // an explicit instantiation declaration will still be implicitly
5967 // instantiated when used so that the body can be considered for
5968 // inlining, but that no out-of-line copy of the inline function would be
5969 // generated in the translation unit. -- end note ]
5970 if (FD->getTemplateSpecializationKind()
5971 == TSK_ExplicitInstantiationDeclaration)
5972 return GVA_C99Inline;
5973
5974 return GVA_CXXInline;
5975}
5976
5977GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5978 // If this is a static data member, compute the kind of template
5979 // specialization. Otherwise, this variable is not part of a
5980 // template.
5981 TemplateSpecializationKind TSK = TSK_Undeclared;
5982 if (VD->isStaticDataMember())
5983 TSK = VD->getTemplateSpecializationKind();
5984
5985 Linkage L = VD->getLinkage();
5986 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5987 VD->getType()->getLinkage() == UniqueExternalLinkage)
5988 L = UniqueExternalLinkage;
5989
5990 switch (L) {
5991 case NoLinkage:
5992 case InternalLinkage:
5993 case UniqueExternalLinkage:
5994 return GVA_Internal;
5995
5996 case ExternalLinkage:
5997 switch (TSK) {
5998 case TSK_Undeclared:
5999 case TSK_ExplicitSpecialization:
6000 return GVA_StrongExternal;
6001
6002 case TSK_ExplicitInstantiationDeclaration:
6003 llvm_unreachable("Variable should not be instantiated");
6004 // Fall through to treat this like any other instantiation.
6005
6006 case TSK_ExplicitInstantiationDefinition:
6007 return GVA_ExplicitTemplateInstantiation;
6008
6009 case TSK_ImplicitInstantiation:
6010 return GVA_TemplateInstantiation;
6011 }
6012 }
6013
6014 return GVA_StrongExternal;
6015}
6016
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006017bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006018 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6019 if (!VD->isFileVarDecl())
6020 return false;
6021 } else if (!isa<FunctionDecl>(D))
6022 return false;
6023
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006024 // Weak references don't produce any output by themselves.
6025 if (D->hasAttr<WeakRefAttr>())
6026 return false;
6027
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006028 // Aliases and used decls are required.
6029 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6030 return true;
6031
6032 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6033 // Forward declarations aren't required.
6034 if (!FD->isThisDeclarationADefinition())
6035 return false;
6036
6037 // Constructors and destructors are required.
6038 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6039 return true;
6040
6041 // The key function for a class is required.
6042 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6043 const CXXRecordDecl *RD = MD->getParent();
6044 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6045 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6046 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6047 return true;
6048 }
6049 }
6050
6051 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6052
6053 // static, static inline, always_inline, and extern inline functions can
6054 // always be deferred. Normal inline functions can be deferred in C99/C++.
6055 // Implicit template instantiations can also be deferred in C++.
6056 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6057 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6058 return false;
6059 return true;
6060 }
6061
6062 const VarDecl *VD = cast<VarDecl>(D);
6063 assert(VD->isFileVarDecl() && "Expected file scoped var");
6064
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006065 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6066 return false;
6067
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006068 // Structs that have non-trivial constructors or destructors are required.
6069
6070 // FIXME: Handle references.
6071 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6072 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +00006073 if (RD->hasDefinition() &&
6074 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006075 return true;
6076 }
6077 }
6078
6079 GVALinkage L = GetGVALinkageForVariable(VD);
6080 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6081 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6082 return false;
6083 }
6084
6085 return true;
6086}
Charles Davis53c59df2010-08-16 03:33:14 +00006087
Charles Davis99202b32010-11-09 18:04:24 +00006088CallingConv ASTContext::getDefaultMethodCallConv() {
6089 // Pass through to the C++ ABI object
6090 return ABI->getDefaultMethodCallConv();
6091}
6092
Jay Foad39c79802011-01-12 09:06:06 +00006093bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006094 // Pass through to the C++ ABI object
6095 return ABI->isNearlyEmpty(RD);
6096}
6097
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006098MangleContext *ASTContext::createMangleContext() {
6099 switch (Target.getCXXABI()) {
6100 case CXXABI_ARM:
6101 case CXXABI_Itanium:
6102 return createItaniumMangleContext(*this, getDiagnostics());
6103 case CXXABI_Microsoft:
6104 return createMicrosoftMangleContext(*this, getDiagnostics());
6105 }
6106 assert(0 && "Unsupported ABI");
6107 return 0;
6108}
6109
Charles Davis53c59df2010-08-16 03:33:14 +00006110CXXABI::~CXXABI() {}