blob: c6e2c20df7d63fdee3a387998d125ec25441c62d [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"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000034#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000035
Chris Lattnerddc135e2006-11-10 06:34:16 +000036using namespace clang;
37
Douglas Gregor9672f922010-07-03 00:47:00 +000038unsigned ASTContext::NumImplicitDefaultConstructors;
39unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000040unsigned ASTContext::NumImplicitCopyConstructors;
41unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000042unsigned ASTContext::NumImplicitMoveConstructors;
43unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000044unsigned ASTContext::NumImplicitCopyAssignmentOperators;
45unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000046unsigned ASTContext::NumImplicitMoveAssignmentOperators;
47unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000048unsigned ASTContext::NumImplicitDestructors;
49unsigned ASTContext::NumImplicitDestructorsDeclared;
50
Steve Naroff0af91202007-04-27 21:51:21 +000051enum FloatingRank {
52 FloatRank, DoubleRank, LongDoubleRank
53};
54
Douglas Gregor7dbfb462010-06-16 21:09:37 +000055void
56ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
57 TemplateTemplateParmDecl *Parm) {
58 ID.AddInteger(Parm->getDepth());
59 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +000060 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000061
62 TemplateParameterList *Params = Parm->getTemplateParameters();
63 ID.AddInteger(Params->size());
64 for (TemplateParameterList::const_iterator P = Params->begin(),
65 PEnd = Params->end();
66 P != PEnd; ++P) {
67 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
68 ID.AddInteger(0);
69 ID.AddBoolean(TTP->isParameterPack());
70 continue;
71 }
72
73 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
74 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +000075 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000076 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +000077 if (NTTP->isExpandedParameterPack()) {
78 ID.AddBoolean(true);
79 ID.AddInteger(NTTP->getNumExpansionTypes());
80 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
81 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
82 } else
83 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +000084 continue;
85 }
86
87 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
88 ID.AddInteger(2);
89 Profile(ID, TTP);
90 }
91}
92
93TemplateTemplateParmDecl *
94ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000095 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000096 // Check if we already have a canonical template template parameter.
97 llvm::FoldingSetNodeID ID;
98 CanonicalTemplateTemplateParm::Profile(ID, TTP);
99 void *InsertPos = 0;
100 CanonicalTemplateTemplateParm *Canonical
101 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
102 if (Canonical)
103 return Canonical->getParam();
104
105 // Build a canonical template parameter list.
106 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000107 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000108 CanonParams.reserve(Params->size());
109 for (TemplateParameterList::const_iterator P = Params->begin(),
110 PEnd = Params->end();
111 P != PEnd; ++P) {
112 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
113 CanonParams.push_back(
114 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000115 SourceLocation(),
116 SourceLocation(),
117 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000118 TTP->getIndex(), 0, false,
119 TTP->isParameterPack()));
120 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000121 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
122 QualType T = getCanonicalType(NTTP->getType());
123 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
124 NonTypeTemplateParmDecl *Param;
125 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000126 SmallVector<QualType, 2> ExpandedTypes;
127 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000128 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
129 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
130 ExpandedTInfos.push_back(
131 getTrivialTypeSourceInfo(ExpandedTypes.back()));
132 }
133
134 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000135 SourceLocation(),
136 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000137 NTTP->getDepth(),
138 NTTP->getPosition(), 0,
139 T,
140 TInfo,
141 ExpandedTypes.data(),
142 ExpandedTypes.size(),
143 ExpandedTInfos.data());
144 } else {
145 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000146 SourceLocation(),
147 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000148 NTTP->getDepth(),
149 NTTP->getPosition(), 0,
150 T,
151 NTTP->isParameterPack(),
152 TInfo);
153 }
154 CanonParams.push_back(Param);
155
156 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000157 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
158 cast<TemplateTemplateParmDecl>(*P)));
159 }
160
161 TemplateTemplateParmDecl *CanonTTP
162 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
163 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000164 TTP->getPosition(),
165 TTP->isParameterPack(),
166 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000167 TemplateParameterList::Create(*this, SourceLocation(),
168 SourceLocation(),
169 CanonParams.data(),
170 CanonParams.size(),
171 SourceLocation()));
172
173 // Get the new insert position for the node we care about.
174 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
175 assert(Canonical == 0 && "Shouldn't be in the map!");
176 (void)Canonical;
177
178 // Create the canonical template template parameter entry.
179 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
180 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
181 return CanonTTP;
182}
183
Charles Davis53c59df2010-08-16 03:33:14 +0000184CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000185 if (!LangOpts.CPlusPlus) return 0;
186
Charles Davis6bcb07a2010-08-19 02:18:14 +0000187 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000188 case CXXABI_ARM:
189 return CreateARMCXXABI(*this);
190 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000191 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000192 case CXXABI_Microsoft:
193 return CreateMicrosoftCXXABI(*this);
194 }
John McCall86353412010-08-21 22:46:04 +0000195 return 0;
Charles Davis53c59df2010-08-16 03:33:14 +0000196}
197
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000198static const LangAS::Map &getAddressSpaceMap(const TargetInfo &T,
199 const LangOptions &LOpts) {
200 if (LOpts.FakeAddressSpaceMap) {
201 // The fake address space map must have a distinct entry for each
202 // language-specific address space.
203 static const unsigned FakeAddrSpaceMap[] = {
204 1, // opencl_global
205 2, // opencl_local
206 3 // opencl_constant
207 };
208 return FakeAddrSpaceMap;
209 } else {
210 return T.getAddressSpaceMap();
211 }
212}
213
Chris Lattner465fa322008-10-05 17:34:18 +0000214ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar1b444192009-11-13 05:51:54 +0000215 const TargetInfo &t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000216 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000217 Builtin::Context &builtins,
Douglas Gregor5b11d492010-07-25 17:53:33 +0000218 unsigned size_reserve) :
Sebastian Redl31ad7542011-03-13 17:09:40 +0000219 FunctionProtoTypes(this_()),
John McCall773cc982010-06-11 11:07:21 +0000220 TemplateSpecializationTypes(this_()),
221 DependentTemplateSpecializationTypes(this_()),
John McCalld9dfe3a2011-06-30 08:33:18 +0000222 SubstTemplateTemplateParmPacks(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000223 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
224 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
John McCall31168b02011-06-15 23:02:42 +0000225 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0),
226 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
227 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000228 NullTypeSourceInfo(QualType()),
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000229 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
230 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000231 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000232 BuiltinInfo(builtins),
233 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000234 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000235 LastSDM(0, 0),
John McCall147d0212011-02-22 22:38:33 +0000236 UniqueBlockByRefTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000237 ObjCIdRedefinitionType = QualType();
238 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000239 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000240 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000241 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000242 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000243}
244
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000245ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000246 // Release the DenseMaps associated with DeclContext objects.
247 // FIXME: Is this the ideal solution?
248 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000249
Douglas Gregor5b11d492010-07-25 17:53:33 +0000250 // Call all of the deallocation functions.
251 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
252 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000253
Douglas Gregor832940b2010-03-02 23:58:15 +0000254 // Release all of the memory associated with overridden C++ methods.
255 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
256 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
257 OM != OMEnd; ++OM)
258 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000259
Ted Kremenek076baeb2010-06-08 23:00:58 +0000260 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000261 // because they can contain DenseMaps.
262 for (llvm::DenseMap<const ObjCContainerDecl*,
263 const ASTRecordLayout*>::iterator
264 I = ObjCLayouts.begin(), E = ObjCLayouts.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
Ted Kremenek076baeb2010-06-08 23:00:58 +0000269 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
270 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
271 // Increment in loop to prevent using deallocated memory.
272 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
273 R->Destroy(*this);
274 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000275
276 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
277 AEnd = DeclAttrs.end();
278 A != AEnd; ++A)
279 A->second->~AttrVec();
280}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000281
Douglas Gregor1a809332010-05-23 18:26:36 +0000282void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
283 Deallocations.push_back(std::make_pair(Callback, Data));
284}
285
Mike Stump11289f42009-09-09 15:08:12 +0000286void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000287ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
288 ExternalSource.reset(Source.take());
289}
290
Chris Lattner4eb445d2007-01-26 01:27:23 +0000291void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000292 llvm::errs() << "\n*** AST Context Stats:\n";
293 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000294
Douglas Gregora30d0462009-05-26 14:40:08 +0000295 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000296#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000297#define ABSTRACT_TYPE(Name, Parent)
298#include "clang/AST/TypeNodes.def"
299 0 // Extra
300 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000301
Chris Lattner4eb445d2007-01-26 01:27:23 +0000302 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
303 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000304 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000305 }
306
Douglas Gregora30d0462009-05-26 14:40:08 +0000307 unsigned Idx = 0;
308 unsigned TotalBytes = 0;
309#define TYPE(Name, Parent) \
310 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000311 llvm::errs() << " " << counts[Idx] << " " << #Name \
312 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000313 TotalBytes += counts[Idx] * sizeof(Name##Type); \
314 ++Idx;
315#define ABSTRACT_TYPE(Name, Parent)
316#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000317
Chandler Carruth3c147a72011-07-04 05:32:14 +0000318 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
319
Douglas Gregor7454c562010-07-02 20:37:36 +0000320 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000321 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
322 << NumImplicitDefaultConstructors
323 << " implicit default constructors created\n";
324 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
325 << NumImplicitCopyConstructors
326 << " implicit copy constructors created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000327 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000328 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
329 << NumImplicitMoveConstructors
330 << " implicit move constructors created\n";
331 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
332 << NumImplicitCopyAssignmentOperators
333 << " implicit copy assignment operators created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000334 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000335 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
336 << NumImplicitMoveAssignmentOperators
337 << " implicit move assignment operators created\n";
338 llvm::errs() << NumImplicitDestructorsDeclared << "/"
339 << NumImplicitDestructors
340 << " implicit destructors created\n";
341
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000342 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000343 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000344 ExternalSource->PrintStats();
345 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000346
Douglas Gregor5b11d492010-07-25 17:53:33 +0000347 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000348}
349
350
John McCall48f2d582009-10-23 23:03:21 +0000351void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000352 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000353 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000354 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000355}
356
Chris Lattner970e54e2006-11-12 00:37:36 +0000357void ASTContext::InitBuiltinTypes() {
358 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000359
Chris Lattner970e54e2006-11-12 00:37:36 +0000360 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000361 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000362
Chris Lattner970e54e2006-11-12 00:37:36 +0000363 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000364 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000365 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000366 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000367 InitBuiltinType(CharTy, BuiltinType::Char_S);
368 else
369 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000370 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000371 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
372 InitBuiltinType(ShortTy, BuiltinType::Short);
373 InitBuiltinType(IntTy, BuiltinType::Int);
374 InitBuiltinType(LongTy, BuiltinType::Long);
375 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000376
Chris Lattner970e54e2006-11-12 00:37:36 +0000377 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000378 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
379 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
380 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
381 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
382 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000383
Chris Lattner970e54e2006-11-12 00:37:36 +0000384 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000385 InitBuiltinType(FloatTy, BuiltinType::Float);
386 InitBuiltinType(DoubleTy, BuiltinType::Double);
387 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000388
Chris Lattnerf122cef2009-04-30 02:43:43 +0000389 // GNU extension, 128-bit integers.
390 InitBuiltinType(Int128Ty, BuiltinType::Int128);
391 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
392
Chris Lattnerad3467e2010-12-25 23:25:43 +0000393 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000394 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000395 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
396 else // -fshort-wchar makes wchar_t be unsigned.
397 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
398 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000399 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000400
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000401 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
402 InitBuiltinType(Char16Ty, BuiltinType::Char16);
403 else // C99
404 Char16Ty = getFromTargetType(Target.getChar16Type());
405
406 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
407 InitBuiltinType(Char32Ty, BuiltinType::Char32);
408 else // C99
409 Char32Ty = getFromTargetType(Target.getChar32Type());
410
Douglas Gregor4619e432008-12-05 23:32:09 +0000411 // Placeholder type for type-dependent expressions whose type is
412 // completely unknown. No code should ever check a type against
413 // DependentTy and users should never see it; however, it is here to
414 // help diagnose failures to properly check for type-dependent
415 // expressions.
416 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000417
John McCall36e7fe32010-10-12 00:20:44 +0000418 // Placeholder type for functions.
419 InitBuiltinType(OverloadTy, BuiltinType::Overload);
420
John McCall0009fcc2011-04-26 20:42:42 +0000421 // Placeholder type for bound members.
422 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
423
John McCall31996342011-04-07 08:22:57 +0000424 // "any" type; useful for debugger-like clients.
425 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
426
Chris Lattner970e54e2006-11-12 00:37:36 +0000427 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000428 FloatComplexTy = getComplexType(FloatTy);
429 DoubleComplexTy = getComplexType(DoubleTy);
430 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000431
Steve Naroff66e9f332007-10-15 14:41:52 +0000432 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000433
Steve Naroff1329fa02009-07-15 18:40:39 +0000434 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
435 ObjCIdTypedefType = QualType();
436 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000437 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000438
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000439 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000440 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
441 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000442 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000443
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000444 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000445
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000446 // void * type
447 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000448
449 // nullptr type (C++0x 2.14.7)
450 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000451}
452
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000453Diagnostic &ASTContext::getDiagnostics() const {
454 return SourceMgr.getDiagnostics();
455}
456
Douglas Gregor561eceb2010-08-30 16:49:28 +0000457AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
458 AttrVec *&Result = DeclAttrs[D];
459 if (!Result) {
460 void *Mem = Allocate(sizeof(AttrVec));
461 Result = new (Mem) AttrVec;
462 }
463
464 return *Result;
465}
466
467/// \brief Erase the attributes corresponding to the given declaration.
468void ASTContext::eraseDeclAttrs(const Decl *D) {
469 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
470 if (Pos != DeclAttrs.end()) {
471 Pos->second->~AttrVec();
472 DeclAttrs.erase(Pos);
473 }
474}
475
Douglas Gregor86d142a2009-10-08 07:24:58 +0000476MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000477ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000478 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000479 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000480 = InstantiatedFromStaticDataMember.find(Var);
481 if (Pos == InstantiatedFromStaticDataMember.end())
482 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000483
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000484 return Pos->second;
485}
486
Mike Stump11289f42009-09-09 15:08:12 +0000487void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000488ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000489 TemplateSpecializationKind TSK,
490 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000491 assert(Inst->isStaticDataMember() && "Not a static data member");
492 assert(Tmpl->isStaticDataMember() && "Not a static data member");
493 assert(!InstantiatedFromStaticDataMember[Inst] &&
494 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000495 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000496 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000497}
498
John McCalle61f2ba2009-11-18 02:36:19 +0000499NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000500ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000501 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000502 = InstantiatedFromUsingDecl.find(UUD);
503 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000504 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000505
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000506 return Pos->second;
507}
508
509void
John McCallb96ec562009-12-04 22:46:56 +0000510ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
511 assert((isa<UsingDecl>(Pattern) ||
512 isa<UnresolvedUsingValueDecl>(Pattern) ||
513 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
514 "pattern decl is not a using decl");
515 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
516 InstantiatedFromUsingDecl[Inst] = Pattern;
517}
518
519UsingShadowDecl *
520ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
521 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
522 = InstantiatedFromUsingShadowDecl.find(Inst);
523 if (Pos == InstantiatedFromUsingShadowDecl.end())
524 return 0;
525
526 return Pos->second;
527}
528
529void
530ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
531 UsingShadowDecl *Pattern) {
532 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
533 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000534}
535
Anders Carlsson5da84842009-09-01 04:26:58 +0000536FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
537 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
538 = InstantiatedFromUnnamedFieldDecl.find(Field);
539 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
540 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000541
Anders Carlsson5da84842009-09-01 04:26:58 +0000542 return Pos->second;
543}
544
545void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
546 FieldDecl *Tmpl) {
547 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
548 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
549 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
550 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000551
Anders Carlsson5da84842009-09-01 04:26:58 +0000552 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
553}
554
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000555bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
556 const FieldDecl *LastFD) const {
557 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
558 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0);
559
560}
561
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000562bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
563 const FieldDecl *LastFD) const {
564 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Fariborz Jahanian759e4a12011-05-03 22:07:14 +0000565 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0 &&
566 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000567
568}
569
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000570bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
571 const FieldDecl *LastFD) const {
572 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
573 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() &&
574 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
575}
576
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000577bool ASTContext::NoneBitfieldFollowsBitfield(const FieldDecl *FD,
578 const FieldDecl *LastFD) const {
579 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
580 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
581}
582
583bool ASTContext::BitfieldFollowsNoneBitfield(const FieldDecl *FD,
584 const FieldDecl *LastFD) const {
585 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
586 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
587}
588
Douglas Gregor832940b2010-03-02 23:58:15 +0000589ASTContext::overridden_cxx_method_iterator
590ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
591 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
592 = OverriddenMethods.find(Method);
593 if (Pos == OverriddenMethods.end())
594 return 0;
595
596 return Pos->second.begin();
597}
598
599ASTContext::overridden_cxx_method_iterator
600ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
601 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
602 = OverriddenMethods.find(Method);
603 if (Pos == OverriddenMethods.end())
604 return 0;
605
606 return Pos->second.end();
607}
608
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000609unsigned
610ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
611 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
612 = OverriddenMethods.find(Method);
613 if (Pos == OverriddenMethods.end())
614 return 0;
615
616 return Pos->second.size();
617}
618
Douglas Gregor832940b2010-03-02 23:58:15 +0000619void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
620 const CXXMethodDecl *Overridden) {
621 OverriddenMethods[Method].push_back(Overridden);
622}
623
Chris Lattner53cfe802007-07-18 17:52:12 +0000624//===----------------------------------------------------------------------===//
625// Type Sizing and Analysis
626//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000627
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000628/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
629/// scalar floating point type.
630const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000631 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000632 assert(BT && "Not a floating point type!");
633 switch (BT->getKind()) {
634 default: assert(0 && "Not a floating point type!");
635 case BuiltinType::Float: return Target.getFloatFormat();
636 case BuiltinType::Double: return Target.getDoubleFormat();
637 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
638 }
639}
640
Ken Dyck160146e2010-01-27 17:10:57 +0000641/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000642/// specified decl. Note that bitfields do not have a valid alignment, so
643/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000644/// If @p RefAsPointee, references are treated like their underlying type
645/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000646CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000647 unsigned Align = Target.getCharWidth();
648
John McCall94268702010-10-08 18:24:19 +0000649 bool UseAlignAttrOnly = false;
650 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
651 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000652
John McCall94268702010-10-08 18:24:19 +0000653 // __attribute__((aligned)) can increase or decrease alignment
654 // *except* on a struct or struct member, where it only increases
655 // alignment unless 'packed' is also specified.
656 //
657 // It is an error for [[align]] to decrease alignment, so we can
658 // ignore that possibility; Sema should diagnose it.
659 if (isa<FieldDecl>(D)) {
660 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
661 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
662 } else {
663 UseAlignAttrOnly = true;
664 }
665 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000666 else if (isa<FieldDecl>(D))
667 UseAlignAttrOnly =
668 D->hasAttr<PackedAttr>() ||
669 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000670
John McCall4e819612011-01-20 07:57:12 +0000671 // If we're using the align attribute only, just ignore everything
672 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000673 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000674 // do nothing
675
John McCall94268702010-10-08 18:24:19 +0000676 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000677 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000678 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000679 if (RefAsPointee)
680 T = RT->getPointeeType();
681 else
682 T = getPointerType(RT->getPointeeType());
683 }
684 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000685 // Adjust alignments of declarations with array type by the
686 // large-array alignment on the target.
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000687 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000688 const ArrayType *arrayType;
689 if (MinWidth && (arrayType = getAsArrayType(T))) {
690 if (isa<VariableArrayType>(arrayType))
691 Align = std::max(Align, Target.getLargeArrayAlign());
692 else if (isa<ConstantArrayType>(arrayType) &&
693 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
694 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000695
John McCall33ddac02011-01-19 10:06:00 +0000696 // Walk through any array types while we're at it.
697 T = getBaseElementType(arrayType);
698 }
Chad Rosierb23ee962011-07-25 19:39:39 +0000699 if (Target.usePreferredTypeAlign())
700 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
701 else
702 Align = std::max(Align, getTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000703 }
John McCall4e819612011-01-20 07:57:12 +0000704
705 // Fields can be subject to extra alignment constraints, like if
706 // the field is packed, the struct is packed, or the struct has a
707 // a max-field-alignment constraint (#pragma pack). So calculate
708 // the actual alignment of the field within the struct, and then
709 // (as we're expected to) constrain that by the alignment of the type.
710 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
711 // So calculate the alignment of the field.
712 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
713
714 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000715 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000716
717 // Use the GCD of that and the offset within the record.
718 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
719 if (offset > 0) {
720 // Alignment is always a power of 2, so the GCD will be a power of 2,
721 // which means we get to do this crazy thing instead of Euclid's.
722 uint64_t lowBitOfOffset = offset & (~offset + 1);
723 if (lowBitOfOffset < fieldAlign)
724 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
725 }
726
727 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000728 }
Chris Lattner68061312009-01-24 21:53:27 +0000729 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000730
Ken Dyckcc56c542011-01-15 18:38:59 +0000731 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000732}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000733
John McCall87fe5d52010-05-20 01:18:31 +0000734std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000735ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000736 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000737 return std::make_pair(toCharUnitsFromBits(Info.first),
738 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000739}
740
741std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000742ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000743 return getTypeInfoInChars(T.getTypePtr());
744}
745
Chris Lattner983a8bb2007-07-13 22:13:22 +0000746/// getTypeSize - Return the size of the specified type, in bits. This method
747/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000748///
749/// FIXME: Pointers into different addr spaces could have different sizes and
750/// alignment requirements: getPointerInfo should take an AddrSpace, this
751/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000752std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000753ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000754 uint64_t Width=0;
755 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000756 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000757#define TYPE(Class, Base)
758#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000759#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000760#define DEPENDENT_TYPE(Class, Base) case Type::Class:
761#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000762 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000763 break;
764
Chris Lattner355332d2007-07-13 22:27:08 +0000765 case Type::FunctionNoProto:
766 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000767 // GCC extension: alignof(function) = 32 bits
768 Width = 0;
769 Align = 32;
770 break;
771
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000772 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000773 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000774 Width = 0;
775 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
776 break;
777
Steve Naroff5c131802007-08-30 01:06:46 +0000778 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000779 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000780
Chris Lattner37e05872008-03-05 18:54:05 +0000781 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000782 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000783 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000784 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000785 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000786 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000787 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000788 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000789 const VectorType *VT = cast<VectorType>(T);
790 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
791 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000792 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000793 // If the alignment is not a power of 2, round up to the next power of 2.
794 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000795 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000796 Align = llvm::NextPowerOf2(Align);
797 Width = llvm::RoundUpToAlignment(Width, Align);
798 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000799 break;
800 }
Chris Lattner647fb222007-07-18 18:26:58 +0000801
Chris Lattner7570e9c2008-03-08 08:52:55 +0000802 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000803 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000804 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000805 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000806 // GCC extension: alignof(void) = 8 bits.
807 Width = 0;
808 Align = 8;
809 break;
810
Chris Lattner6a4f7452007-12-19 19:23:28 +0000811 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000812 Width = Target.getBoolWidth();
813 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000814 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000815 case BuiltinType::Char_S:
816 case BuiltinType::Char_U:
817 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000818 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000819 Width = Target.getCharWidth();
820 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000821 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000822 case BuiltinType::WChar_S:
823 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000824 Width = Target.getWCharWidth();
825 Align = Target.getWCharAlign();
826 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000827 case BuiltinType::Char16:
828 Width = Target.getChar16Width();
829 Align = Target.getChar16Align();
830 break;
831 case BuiltinType::Char32:
832 Width = Target.getChar32Width();
833 Align = Target.getChar32Align();
834 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000835 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000836 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000837 Width = Target.getShortWidth();
838 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000839 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000840 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000841 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000842 Width = Target.getIntWidth();
843 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000844 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000845 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000846 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000847 Width = Target.getLongWidth();
848 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000849 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000850 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000851 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000852 Width = Target.getLongLongWidth();
853 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000854 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000855 case BuiltinType::Int128:
856 case BuiltinType::UInt128:
857 Width = 128;
858 Align = 128; // int128_t is 128-bit aligned on all targets.
859 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000860 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000861 Width = Target.getFloatWidth();
862 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000863 break;
864 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000865 Width = Target.getDoubleWidth();
866 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000867 break;
868 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000869 Width = Target.getLongDoubleWidth();
870 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000871 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000872 case BuiltinType::NullPtr:
873 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
874 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000875 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000876 case BuiltinType::ObjCId:
877 case BuiltinType::ObjCClass:
878 case BuiltinType::ObjCSel:
879 Width = Target.getPointerWidth(0);
880 Align = Target.getPointerAlign(0);
881 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000882 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000883 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000884 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000885 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000886 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000887 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000888 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000889 unsigned AS = getTargetAddressSpace(
890 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff921a45c2008-09-24 15:05:44 +0000891 Width = Target.getPointerWidth(AS);
892 Align = Target.getPointerAlign(AS);
893 break;
894 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000895 case Type::LValueReference:
896 case Type::RValueReference: {
897 // alignof and sizeof should never enter this code path here, so we go
898 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000899 unsigned AS = getTargetAddressSpace(
900 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000901 Width = Target.getPointerWidth(AS);
902 Align = Target.getPointerAlign(AS);
903 break;
904 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000905 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000906 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000907 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000908 Align = Target.getPointerAlign(AS);
909 break;
910 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000911 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000912 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000913 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000914 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000915 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000916 Align = PtrDiffInfo.second;
917 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000918 }
Chris Lattner647fb222007-07-18 18:26:58 +0000919 case Type::Complex: {
920 // Complex types have the same alignment as their elements, but twice the
921 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000922 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000923 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000924 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000925 Align = EltInfo.second;
926 break;
927 }
John McCall8b07ec22010-05-15 11:32:37 +0000928 case Type::ObjCObject:
929 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000930 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000931 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000932 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000933 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000934 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000935 break;
936 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000937 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000938 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000939 const TagType *TT = cast<TagType>(T);
940
941 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +0000942 Width = 8;
943 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +0000944 break;
945 }
Mike Stump11289f42009-09-09 15:08:12 +0000946
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000947 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000948 return getTypeInfo(ET->getDecl()->getIntegerType());
949
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000950 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000951 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000952 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000953 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +0000954 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000955 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000956
Chris Lattner63d2b362009-10-22 05:17:15 +0000957 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000958 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
959 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000960
Richard Smith30482bc2011-02-20 03:19:35 +0000961 case Type::Auto: {
962 const AutoType *A = cast<AutoType>(T);
963 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +0000964 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +0000965 }
966
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000967 case Type::Paren:
968 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
969
Douglas Gregoref462e62009-04-30 17:32:17 +0000970 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +0000971 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000972 std::pair<uint64_t, unsigned> Info
973 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +0000974 // If the typedef has an aligned attribute on it, it overrides any computed
975 // alignment we have. This violates the GCC documentation (which says that
976 // attribute(aligned) can only round up) but matches its implementation.
977 if (unsigned AttrAlign = Typedef->getMaxAlignment())
978 Align = AttrAlign;
979 else
980 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +0000981 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000982 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000983 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000984
985 case Type::TypeOfExpr:
986 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
987 .getTypePtr());
988
989 case Type::TypeOf:
990 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
991
Anders Carlsson81df7b82009-06-24 19:06:50 +0000992 case Type::Decltype:
993 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
994 .getTypePtr());
995
Alexis Hunte852b102011-05-24 22:41:36 +0000996 case Type::UnaryTransform:
997 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
998
Abramo Bagnara6150c882010-05-11 21:36:43 +0000999 case Type::Elaborated:
1000 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001001
John McCall81904512011-01-06 01:58:22 +00001002 case Type::Attributed:
1003 return getTypeInfo(
1004 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1005
Richard Smith3f1b5d02011-05-05 21:57:07 +00001006 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001007 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001008 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001009 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1010 // A type alias template specialization may refer to a typedef with the
1011 // aligned attribute on it.
1012 if (TST->isTypeAlias())
1013 return getTypeInfo(TST->getAliasedType().getTypePtr());
1014 else
1015 return getTypeInfo(getCanonicalType(T));
1016 }
1017
Douglas Gregoref462e62009-04-30 17:32:17 +00001018 }
Mike Stump11289f42009-09-09 15:08:12 +00001019
Chris Lattner53cfe802007-07-18 17:52:12 +00001020 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001021 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001022}
1023
Ken Dyckcc56c542011-01-15 18:38:59 +00001024/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1025CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1026 return CharUnits::fromQuantity(BitSize / getCharWidth());
1027}
1028
Ken Dyckb0fcc592011-02-11 01:54:29 +00001029/// toBits - Convert a size in characters to a size in characters.
1030int64_t ASTContext::toBits(CharUnits CharSize) const {
1031 return CharSize.getQuantity() * getCharWidth();
1032}
1033
Ken Dyck8c89d592009-12-22 14:23:30 +00001034/// getTypeSizeInChars - Return the size of the specified type, in characters.
1035/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001036CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001037 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001038}
Jay Foad39c79802011-01-12 09:06:06 +00001039CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001040 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001041}
1042
Ken Dycka6046ab2010-01-26 17:25:18 +00001043/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001044/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001045CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001046 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001047}
Jay Foad39c79802011-01-12 09:06:06 +00001048CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001049 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001050}
1051
Chris Lattnera3402cd2009-01-27 18:08:34 +00001052/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1053/// type for the current target in bits. This can be different than the ABI
1054/// alignment in cases where it is beneficial for performance to overalign
1055/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001056unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001057 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001058
1059 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001060 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001061 T = CT->getElementType().getTypePtr();
1062 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1063 T->isSpecificBuiltinType(BuiltinType::LongLong))
1064 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1065
Chris Lattnera3402cd2009-01-27 18:08:34 +00001066 return ABIAlign;
1067}
1068
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001069/// DeepCollectObjCIvars -
1070/// This routine first collects all declared, but not synthesized, ivars in
1071/// super class and then collects all ivars, including those synthesized for
1072/// current class. This routine is used for implementation of current class
1073/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001074///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001075void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1076 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001077 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001078 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1079 DeepCollectObjCIvars(SuperClass, false, Ivars);
1080 if (!leafClass) {
1081 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1082 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001083 Ivars.push_back(*I);
1084 }
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001085 else {
1086 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001087 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001088 Iv= Iv->getNextIvar())
1089 Ivars.push_back(Iv);
1090 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001091}
1092
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001093/// CollectInheritedProtocols - Collect all protocols in current class and
1094/// those inherited by it.
1095void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001096 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001097 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001098 // We can use protocol_iterator here instead of
1099 // all_referenced_protocol_iterator since we are walking all categories.
1100 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1101 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001102 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001103 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001104 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001105 PE = Proto->protocol_end(); P != PE; ++P) {
1106 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001107 CollectInheritedProtocols(*P, Protocols);
1108 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001109 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001110
1111 // Categories of this Interface.
1112 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1113 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1114 CollectInheritedProtocols(CDeclChain, Protocols);
1115 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1116 while (SD) {
1117 CollectInheritedProtocols(SD, Protocols);
1118 SD = SD->getSuperClass();
1119 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001120 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001121 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001122 PE = OC->protocol_end(); P != PE; ++P) {
1123 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001124 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001125 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1126 PE = Proto->protocol_end(); P != PE; ++P)
1127 CollectInheritedProtocols(*P, Protocols);
1128 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001129 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001130 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1131 PE = OP->protocol_end(); P != PE; ++P) {
1132 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001133 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001134 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1135 PE = Proto->protocol_end(); P != PE; ++P)
1136 CollectInheritedProtocols(*P, Protocols);
1137 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001138 }
1139}
1140
Jay Foad39c79802011-01-12 09:06:06 +00001141unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001142 unsigned count = 0;
1143 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001144 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1145 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001146 count += CDecl->ivar_size();
1147
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001148 // Count ivar defined in this class's implementation. This
1149 // includes synthesized ivars.
1150 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001151 count += ImplDecl->ivar_size();
1152
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001153 return count;
1154}
1155
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001156/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1157ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1158 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1159 I = ObjCImpls.find(D);
1160 if (I != ObjCImpls.end())
1161 return cast<ObjCImplementationDecl>(I->second);
1162 return 0;
1163}
1164/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1165ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1166 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1167 I = ObjCImpls.find(D);
1168 if (I != ObjCImpls.end())
1169 return cast<ObjCCategoryImplDecl>(I->second);
1170 return 0;
1171}
1172
1173/// \brief Set the implementation of ObjCInterfaceDecl.
1174void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1175 ObjCImplementationDecl *ImplD) {
1176 assert(IFaceD && ImplD && "Passed null params");
1177 ObjCImpls[IFaceD] = ImplD;
1178}
1179/// \brief Set the implementation of ObjCCategoryDecl.
1180void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1181 ObjCCategoryImplDecl *ImplD) {
1182 assert(CatD && ImplD && "Passed null params");
1183 ObjCImpls[CatD] = ImplD;
1184}
1185
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001186/// \brief Get the copy initialization expression of VarDecl,or NULL if
1187/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001188Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001189 assert(VD && "Passed null params");
1190 assert(VD->hasAttr<BlocksAttr>() &&
1191 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001192 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001193 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001194 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1195}
1196
1197/// \brief Set the copy inialization expression of a block var decl.
1198void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1199 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001200 assert(VD->hasAttr<BlocksAttr>() &&
1201 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001202 BlockVarCopyInits[VD] = Init;
1203}
1204
John McCallbcd03502009-12-07 02:54:59 +00001205/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001206///
John McCallbcd03502009-12-07 02:54:59 +00001207/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001208/// the TypeLoc wrappers.
1209///
1210/// \param T the type that will be the basis for type source info. This type
1211/// should refer to how the declarator was written in source code, not to
1212/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001213TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001214 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001215 if (!DataSize)
1216 DataSize = TypeLoc::getFullDataSizeForType(T);
1217 else
1218 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001219 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001220
John McCallbcd03502009-12-07 02:54:59 +00001221 TypeSourceInfo *TInfo =
1222 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1223 new (TInfo) TypeSourceInfo(T);
1224 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001225}
1226
John McCallbcd03502009-12-07 02:54:59 +00001227TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001228 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001229 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001230 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001231 return DI;
1232}
1233
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001234const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001235ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001236 return getObjCLayout(D, 0);
1237}
1238
1239const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001240ASTContext::getASTObjCImplementationLayout(
1241 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001242 return getObjCLayout(D->getClassInterface(), D);
1243}
1244
Chris Lattner983a8bb2007-07-13 22:13:22 +00001245//===----------------------------------------------------------------------===//
1246// Type creation/memoization methods
1247//===----------------------------------------------------------------------===//
1248
Jay Foad39c79802011-01-12 09:06:06 +00001249QualType
John McCall33ddac02011-01-19 10:06:00 +00001250ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1251 unsigned fastQuals = quals.getFastQualifiers();
1252 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001253
1254 // Check if we've already instantiated this type.
1255 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001256 ExtQuals::Profile(ID, baseType, quals);
1257 void *insertPos = 0;
1258 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1259 assert(eq->getQualifiers() == quals);
1260 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001261 }
1262
John McCall33ddac02011-01-19 10:06:00 +00001263 // If the base type is not canonical, make the appropriate canonical type.
1264 QualType canon;
1265 if (!baseType->isCanonicalUnqualified()) {
1266 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1267 canonSplit.second.addConsistentQualifiers(quals);
1268 canon = getExtQualType(canonSplit.first, canonSplit.second);
1269
1270 // Re-find the insert position.
1271 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1272 }
1273
1274 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1275 ExtQualNodes.InsertNode(eq, insertPos);
1276 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001277}
1278
Jay Foad39c79802011-01-12 09:06:06 +00001279QualType
1280ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001281 QualType CanT = getCanonicalType(T);
1282 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001283 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001284
John McCall8ccfcb52009-09-24 19:53:00 +00001285 // If we are composing extended qualifiers together, merge together
1286 // into one ExtQuals node.
1287 QualifierCollector Quals;
1288 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001289
John McCall8ccfcb52009-09-24 19:53:00 +00001290 // If this type already has an address space specified, it cannot get
1291 // another one.
1292 assert(!Quals.hasAddressSpace() &&
1293 "Type cannot be in multiple addr spaces!");
1294 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001295
John McCall8ccfcb52009-09-24 19:53:00 +00001296 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001297}
1298
Chris Lattnerd60183d2009-02-18 22:53:11 +00001299QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001300 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001301 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001302 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001303 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001304
John McCall53fa7142010-12-24 02:08:15 +00001305 if (const PointerType *ptr = T->getAs<PointerType>()) {
1306 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001307 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001308 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1309 return getPointerType(ResultType);
1310 }
1311 }
Mike Stump11289f42009-09-09 15:08:12 +00001312
John McCall8ccfcb52009-09-24 19:53:00 +00001313 // If we are composing extended qualifiers together, merge together
1314 // into one ExtQuals node.
1315 QualifierCollector Quals;
1316 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001317
John McCall8ccfcb52009-09-24 19:53:00 +00001318 // If this type already has an ObjCGC specified, it cannot get
1319 // another one.
1320 assert(!Quals.hasObjCGCAttr() &&
1321 "Type cannot have multiple ObjCGCs!");
1322 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001323
John McCall8ccfcb52009-09-24 19:53:00 +00001324 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001325}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001326
John McCall4f5019e2010-12-19 02:44:49 +00001327const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1328 FunctionType::ExtInfo Info) {
1329 if (T->getExtInfo() == Info)
1330 return T;
1331
1332 QualType Result;
1333 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1334 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1335 } else {
1336 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1337 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1338 EPI.ExtInfo = Info;
1339 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1340 FPT->getNumArgs(), EPI);
1341 }
1342
1343 return cast<FunctionType>(Result.getTypePtr());
1344}
1345
Chris Lattnerc6395932007-06-22 20:56:16 +00001346/// getComplexType - Return the uniqued reference to the type for a complex
1347/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001348QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001349 // Unique pointers, to guarantee there is only one pointer of a particular
1350 // structure.
1351 llvm::FoldingSetNodeID ID;
1352 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001353
Chris Lattnerc6395932007-06-22 20:56:16 +00001354 void *InsertPos = 0;
1355 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1356 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001357
Chris Lattnerc6395932007-06-22 20:56:16 +00001358 // If the pointee type isn't canonical, this won't be a canonical type either,
1359 // so fill in the canonical type field.
1360 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001361 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001362 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001363
Chris Lattnerc6395932007-06-22 20:56:16 +00001364 // Get the new insert position for the node we care about.
1365 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001366 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001367 }
John McCall90d1c2d2009-09-24 23:30:46 +00001368 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001369 Types.push_back(New);
1370 ComplexTypes.InsertNode(New, InsertPos);
1371 return QualType(New, 0);
1372}
1373
Chris Lattner970e54e2006-11-12 00:37:36 +00001374/// getPointerType - Return the uniqued reference to the type for a pointer to
1375/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001376QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001377 // Unique pointers, to guarantee there is only one pointer of a particular
1378 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001379 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001380 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001381
Chris Lattner67521df2007-01-27 01:29:36 +00001382 void *InsertPos = 0;
1383 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001384 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001385
Chris Lattner7ccecb92006-11-12 08:50:50 +00001386 // If the pointee type isn't canonical, this won't be a canonical type either,
1387 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001388 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001389 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001390 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001391
Chris Lattner67521df2007-01-27 01:29:36 +00001392 // Get the new insert position for the node we care about.
1393 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001394 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001395 }
John McCall90d1c2d2009-09-24 23:30:46 +00001396 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001397 Types.push_back(New);
1398 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001399 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001400}
1401
Mike Stump11289f42009-09-09 15:08:12 +00001402/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001403/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001404QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001405 assert(T->isFunctionType() && "block of function types only");
1406 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001407 // structure.
1408 llvm::FoldingSetNodeID ID;
1409 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001410
Steve Naroffec33ed92008-08-27 16:04:49 +00001411 void *InsertPos = 0;
1412 if (BlockPointerType *PT =
1413 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1414 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001415
1416 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001417 // type either so fill in the canonical type field.
1418 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001419 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001420 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001421
Steve Naroffec33ed92008-08-27 16:04:49 +00001422 // Get the new insert position for the node we care about.
1423 BlockPointerType *NewIP =
1424 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001425 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001426 }
John McCall90d1c2d2009-09-24 23:30:46 +00001427 BlockPointerType *New
1428 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001429 Types.push_back(New);
1430 BlockPointerTypes.InsertNode(New, InsertPos);
1431 return QualType(New, 0);
1432}
1433
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001434/// getLValueReferenceType - Return the uniqued reference to the type for an
1435/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001436QualType
1437ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001438 assert(getCanonicalType(T) != OverloadTy &&
1439 "Unresolved overloaded function type");
1440
Bill Wendling3708c182007-05-27 10:15:43 +00001441 // Unique pointers, to guarantee there is only one pointer of a particular
1442 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001443 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001444 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001445
1446 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001447 if (LValueReferenceType *RT =
1448 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001449 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001450
John McCallfc93cf92009-10-22 22:37:11 +00001451 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1452
Bill Wendling3708c182007-05-27 10:15:43 +00001453 // If the referencee type isn't canonical, this won't be a canonical type
1454 // either, so fill in the canonical type field.
1455 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001456 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1457 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1458 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001459
Bill Wendling3708c182007-05-27 10:15:43 +00001460 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001461 LValueReferenceType *NewIP =
1462 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001463 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001464 }
1465
John McCall90d1c2d2009-09-24 23:30:46 +00001466 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001467 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1468 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001469 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001470 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001471
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001472 return QualType(New, 0);
1473}
1474
1475/// getRValueReferenceType - Return the uniqued reference to the type for an
1476/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001477QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001478 // Unique pointers, to guarantee there is only one pointer of a particular
1479 // structure.
1480 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001481 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001482
1483 void *InsertPos = 0;
1484 if (RValueReferenceType *RT =
1485 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1486 return QualType(RT, 0);
1487
John McCallfc93cf92009-10-22 22:37:11 +00001488 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1489
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001490 // If the referencee type isn't canonical, this won't be a canonical type
1491 // either, so fill in the canonical type field.
1492 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001493 if (InnerRef || !T.isCanonical()) {
1494 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1495 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001496
1497 // Get the new insert position for the node we care about.
1498 RValueReferenceType *NewIP =
1499 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001500 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001501 }
1502
John McCall90d1c2d2009-09-24 23:30:46 +00001503 RValueReferenceType *New
1504 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001505 Types.push_back(New);
1506 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001507 return QualType(New, 0);
1508}
1509
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001510/// getMemberPointerType - Return the uniqued reference to the type for a
1511/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001512QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001513 // Unique pointers, to guarantee there is only one pointer of a particular
1514 // structure.
1515 llvm::FoldingSetNodeID ID;
1516 MemberPointerType::Profile(ID, T, Cls);
1517
1518 void *InsertPos = 0;
1519 if (MemberPointerType *PT =
1520 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1521 return QualType(PT, 0);
1522
1523 // If the pointee or class type isn't canonical, this won't be a canonical
1524 // type either, so fill in the canonical type field.
1525 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001526 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001527 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1528
1529 // Get the new insert position for the node we care about.
1530 MemberPointerType *NewIP =
1531 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001532 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001533 }
John McCall90d1c2d2009-09-24 23:30:46 +00001534 MemberPointerType *New
1535 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001536 Types.push_back(New);
1537 MemberPointerTypes.InsertNode(New, InsertPos);
1538 return QualType(New, 0);
1539}
1540
Mike Stump11289f42009-09-09 15:08:12 +00001541/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001542/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001543QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001544 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001545 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001546 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001547 assert((EltTy->isDependentType() ||
1548 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001549 "Constant array of VLAs is illegal!");
1550
Chris Lattnere2df3f92009-05-13 04:12:56 +00001551 // Convert the array size into a canonical width matching the pointer size for
1552 // the target.
1553 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001554 ArySize =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001555 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001556
Chris Lattner23b7eb62007-06-15 23:05:46 +00001557 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001558 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001559
Chris Lattner36f8e652007-01-27 08:31:04 +00001560 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001561 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001562 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001563 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001564
John McCall33ddac02011-01-19 10:06:00 +00001565 // If the element type isn't canonical or has qualifiers, this won't
1566 // be a canonical type either, so fill in the canonical type field.
1567 QualType Canon;
1568 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1569 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1570 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001571 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001572 Canon = getQualifiedType(Canon, canonSplit.second);
1573
Chris Lattner36f8e652007-01-27 08:31:04 +00001574 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001575 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001576 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001577 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001578 }
Mike Stump11289f42009-09-09 15:08:12 +00001579
John McCall90d1c2d2009-09-24 23:30:46 +00001580 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001581 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001582 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001583 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001584 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001585}
1586
John McCall06549462011-01-18 08:40:38 +00001587/// getVariableArrayDecayedType - Turns the given type, which may be
1588/// variably-modified, into the corresponding type with all the known
1589/// sizes replaced with [*].
1590QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1591 // Vastly most common case.
1592 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001593
John McCall06549462011-01-18 08:40:38 +00001594 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001595
John McCall06549462011-01-18 08:40:38 +00001596 SplitQualType split = type.getSplitDesugaredType();
1597 const Type *ty = split.first;
1598 switch (ty->getTypeClass()) {
1599#define TYPE(Class, Base)
1600#define ABSTRACT_TYPE(Class, Base)
1601#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1602#include "clang/AST/TypeNodes.def"
1603 llvm_unreachable("didn't desugar past all non-canonical types?");
1604
1605 // These types should never be variably-modified.
1606 case Type::Builtin:
1607 case Type::Complex:
1608 case Type::Vector:
1609 case Type::ExtVector:
1610 case Type::DependentSizedExtVector:
1611 case Type::ObjCObject:
1612 case Type::ObjCInterface:
1613 case Type::ObjCObjectPointer:
1614 case Type::Record:
1615 case Type::Enum:
1616 case Type::UnresolvedUsing:
1617 case Type::TypeOfExpr:
1618 case Type::TypeOf:
1619 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001620 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001621 case Type::DependentName:
1622 case Type::InjectedClassName:
1623 case Type::TemplateSpecialization:
1624 case Type::DependentTemplateSpecialization:
1625 case Type::TemplateTypeParm:
1626 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001627 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001628 case Type::PackExpansion:
1629 llvm_unreachable("type should never be variably-modified");
1630
1631 // These types can be variably-modified but should never need to
1632 // further decay.
1633 case Type::FunctionNoProto:
1634 case Type::FunctionProto:
1635 case Type::BlockPointer:
1636 case Type::MemberPointer:
1637 return type;
1638
1639 // These types can be variably-modified. All these modifications
1640 // preserve structure except as noted by comments.
1641 // TODO: if we ever care about optimizing VLAs, there are no-op
1642 // optimizations available here.
1643 case Type::Pointer:
1644 result = getPointerType(getVariableArrayDecayedType(
1645 cast<PointerType>(ty)->getPointeeType()));
1646 break;
1647
1648 case Type::LValueReference: {
1649 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1650 result = getLValueReferenceType(
1651 getVariableArrayDecayedType(lv->getPointeeType()),
1652 lv->isSpelledAsLValue());
1653 break;
1654 }
1655
1656 case Type::RValueReference: {
1657 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1658 result = getRValueReferenceType(
1659 getVariableArrayDecayedType(lv->getPointeeType()));
1660 break;
1661 }
1662
1663 case Type::ConstantArray: {
1664 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1665 result = getConstantArrayType(
1666 getVariableArrayDecayedType(cat->getElementType()),
1667 cat->getSize(),
1668 cat->getSizeModifier(),
1669 cat->getIndexTypeCVRQualifiers());
1670 break;
1671 }
1672
1673 case Type::DependentSizedArray: {
1674 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1675 result = getDependentSizedArrayType(
1676 getVariableArrayDecayedType(dat->getElementType()),
1677 dat->getSizeExpr(),
1678 dat->getSizeModifier(),
1679 dat->getIndexTypeCVRQualifiers(),
1680 dat->getBracketsRange());
1681 break;
1682 }
1683
1684 // Turn incomplete types into [*] types.
1685 case Type::IncompleteArray: {
1686 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1687 result = getVariableArrayType(
1688 getVariableArrayDecayedType(iat->getElementType()),
1689 /*size*/ 0,
1690 ArrayType::Normal,
1691 iat->getIndexTypeCVRQualifiers(),
1692 SourceRange());
1693 break;
1694 }
1695
1696 // Turn VLA types into [*] types.
1697 case Type::VariableArray: {
1698 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1699 result = getVariableArrayType(
1700 getVariableArrayDecayedType(vat->getElementType()),
1701 /*size*/ 0,
1702 ArrayType::Star,
1703 vat->getIndexTypeCVRQualifiers(),
1704 vat->getBracketsRange());
1705 break;
1706 }
1707 }
1708
1709 // Apply the top-level qualifiers from the original.
1710 return getQualifiedType(result, split.second);
1711}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001712
Steve Naroffcadebd02007-08-30 18:14:25 +00001713/// getVariableArrayType - Returns a non-unique reference to the type for a
1714/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001715QualType ASTContext::getVariableArrayType(QualType EltTy,
1716 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001717 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001718 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001719 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001720 // Since we don't unique expressions, it isn't possible to unique VLA's
1721 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001722 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001723
John McCall33ddac02011-01-19 10:06:00 +00001724 // Be sure to pull qualifiers off the element type.
1725 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1726 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1727 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001728 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001729 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001730 }
1731
John McCall90d1c2d2009-09-24 23:30:46 +00001732 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001733 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001734
1735 VariableArrayTypes.push_back(New);
1736 Types.push_back(New);
1737 return QualType(New, 0);
1738}
1739
Douglas Gregor4619e432008-12-05 23:32:09 +00001740/// getDependentSizedArrayType - Returns a non-unique reference to
1741/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001742/// type.
John McCall33ddac02011-01-19 10:06:00 +00001743QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1744 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001745 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001746 unsigned elementTypeQuals,
1747 SourceRange brackets) const {
1748 assert((!numElements || numElements->isTypeDependent() ||
1749 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001750 "Size must be type- or value-dependent!");
1751
John McCall33ddac02011-01-19 10:06:00 +00001752 // Dependently-sized array types that do not have a specified number
1753 // of elements will have their sizes deduced from a dependent
1754 // initializer. We do no canonicalization here at all, which is okay
1755 // because they can't be used in most locations.
1756 if (!numElements) {
1757 DependentSizedArrayType *newType
1758 = new (*this, TypeAlignment)
1759 DependentSizedArrayType(*this, elementType, QualType(),
1760 numElements, ASM, elementTypeQuals,
1761 brackets);
1762 Types.push_back(newType);
1763 return QualType(newType, 0);
1764 }
1765
1766 // Otherwise, we actually build a new type every time, but we
1767 // also build a canonical type.
1768
1769 SplitQualType canonElementType = getCanonicalType(elementType).split();
1770
1771 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001772 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001773 DependentSizedArrayType::Profile(ID, *this,
1774 QualType(canonElementType.first, 0),
1775 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001776
John McCall33ddac02011-01-19 10:06:00 +00001777 // Look for an existing type with these properties.
1778 DependentSizedArrayType *canonTy =
1779 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001780
John McCall33ddac02011-01-19 10:06:00 +00001781 // If we don't have one, build one.
1782 if (!canonTy) {
1783 canonTy = new (*this, TypeAlignment)
1784 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1785 QualType(), numElements, ASM, elementTypeQuals,
1786 brackets);
1787 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1788 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001789 }
1790
John McCall33ddac02011-01-19 10:06:00 +00001791 // Apply qualifiers from the element type to the array.
1792 QualType canon = getQualifiedType(QualType(canonTy,0),
1793 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001794
John McCall33ddac02011-01-19 10:06:00 +00001795 // If we didn't need extra canonicalization for the element type,
1796 // then just use that as our result.
1797 if (QualType(canonElementType.first, 0) == elementType)
1798 return canon;
1799
1800 // Otherwise, we need to build a type which follows the spelling
1801 // of the element type.
1802 DependentSizedArrayType *sugaredType
1803 = new (*this, TypeAlignment)
1804 DependentSizedArrayType(*this, elementType, canon, numElements,
1805 ASM, elementTypeQuals, brackets);
1806 Types.push_back(sugaredType);
1807 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001808}
1809
John McCall33ddac02011-01-19 10:06:00 +00001810QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001811 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001812 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001813 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001814 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001815
John McCall33ddac02011-01-19 10:06:00 +00001816 void *insertPos = 0;
1817 if (IncompleteArrayType *iat =
1818 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1819 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001820
1821 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001822 // either, so fill in the canonical type field. We also have to pull
1823 // qualifiers off the element type.
1824 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001825
John McCall33ddac02011-01-19 10:06:00 +00001826 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1827 SplitQualType canonSplit = getCanonicalType(elementType).split();
1828 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1829 ASM, elementTypeQuals);
1830 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001831
1832 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001833 IncompleteArrayType *existing =
1834 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1835 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001836 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001837
John McCall33ddac02011-01-19 10:06:00 +00001838 IncompleteArrayType *newType = new (*this, TypeAlignment)
1839 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001840
John McCall33ddac02011-01-19 10:06:00 +00001841 IncompleteArrayTypes.InsertNode(newType, insertPos);
1842 Types.push_back(newType);
1843 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001844}
1845
Steve Naroff91fcddb2007-07-18 18:00:27 +00001846/// getVectorType - Return the unique reference to a vector type of
1847/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001848QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001849 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001850 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001851
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001852 // Check if we've already instantiated a vector of this type.
1853 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001854 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001855
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001856 void *InsertPos = 0;
1857 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1858 return QualType(VTP, 0);
1859
1860 // If the element type isn't canonical, this won't be a canonical type either,
1861 // so fill in the canonical type field.
1862 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001863 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001864 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001865
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001866 // Get the new insert position for the node we care about.
1867 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001868 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001869 }
John McCall90d1c2d2009-09-24 23:30:46 +00001870 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001871 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001872 VectorTypes.InsertNode(New, InsertPos);
1873 Types.push_back(New);
1874 return QualType(New, 0);
1875}
1876
Nate Begemance4d7fc2008-04-18 23:10:10 +00001877/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001878/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001879QualType
1880ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00001881 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00001882
Steve Naroff91fcddb2007-07-18 18:00:27 +00001883 // Check if we've already instantiated a vector of this type.
1884 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001885 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001886 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001887 void *InsertPos = 0;
1888 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1889 return QualType(VTP, 0);
1890
1891 // If the element type isn't canonical, this won't be a canonical type either,
1892 // so fill in the canonical type field.
1893 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001894 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001895 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001896
Steve Naroff91fcddb2007-07-18 18:00:27 +00001897 // Get the new insert position for the node we care about.
1898 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001899 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001900 }
John McCall90d1c2d2009-09-24 23:30:46 +00001901 ExtVectorType *New = new (*this, TypeAlignment)
1902 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001903 VectorTypes.InsertNode(New, InsertPos);
1904 Types.push_back(New);
1905 return QualType(New, 0);
1906}
1907
Jay Foad39c79802011-01-12 09:06:06 +00001908QualType
1909ASTContext::getDependentSizedExtVectorType(QualType vecType,
1910 Expr *SizeExpr,
1911 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001912 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001913 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001914 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001915
Douglas Gregor352169a2009-07-31 03:54:25 +00001916 void *InsertPos = 0;
1917 DependentSizedExtVectorType *Canon
1918 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1919 DependentSizedExtVectorType *New;
1920 if (Canon) {
1921 // We already have a canonical version of this array type; use it as
1922 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001923 New = new (*this, TypeAlignment)
1924 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1925 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001926 } else {
1927 QualType CanonVecTy = getCanonicalType(vecType);
1928 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001929 New = new (*this, TypeAlignment)
1930 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1931 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001932
1933 DependentSizedExtVectorType *CanonCheck
1934 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1935 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1936 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001937 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1938 } else {
1939 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1940 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001941 New = new (*this, TypeAlignment)
1942 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001943 }
1944 }
Mike Stump11289f42009-09-09 15:08:12 +00001945
Douglas Gregor758a8692009-06-17 21:51:59 +00001946 Types.push_back(New);
1947 return QualType(New, 0);
1948}
1949
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001950/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001951///
Jay Foad39c79802011-01-12 09:06:06 +00001952QualType
1953ASTContext::getFunctionNoProtoType(QualType ResultTy,
1954 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00001955 const CallingConv DefaultCC = Info.getCC();
1956 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1957 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001958 // Unique functions, to guarantee there is only one function of a particular
1959 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001960 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001961 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001962
Chris Lattner47955de2007-01-27 08:37:20 +00001963 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001964 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001965 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001966 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001967
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001968 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001969 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001970 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001971 Canonical =
1972 getFunctionNoProtoType(getCanonicalType(ResultTy),
1973 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001974
Chris Lattner47955de2007-01-27 08:37:20 +00001975 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001976 FunctionNoProtoType *NewIP =
1977 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001978 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001979 }
Mike Stump11289f42009-09-09 15:08:12 +00001980
Roman Divacky65b88cd2011-03-01 17:40:53 +00001981 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00001982 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00001983 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00001984 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001985 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001986 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001987}
1988
1989/// getFunctionType - Return a normal function type with a typed argument
1990/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001991QualType
1992ASTContext::getFunctionType(QualType ResultTy,
1993 const QualType *ArgArray, unsigned NumArgs,
1994 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001995 // Unique functions, to guarantee there is only one function of a particular
1996 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001997 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00001998 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00001999
2000 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002001 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002002 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002003 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002004
2005 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002006 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002007 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002008 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002009 isCanonical = false;
2010
Roman Divacky65b88cd2011-03-01 17:40:53 +00002011 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2012 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2013 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002014
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002015 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002016 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002017 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002018 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002019 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002020 CanonicalArgs.reserve(NumArgs);
2021 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002022 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002023
John McCalldb40c7f2010-12-14 08:05:40 +00002024 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002025 CanonicalEPI.ExceptionSpecType = EST_None;
2026 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002027 CanonicalEPI.ExtInfo
2028 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2029
Chris Lattner76a00cf2008-04-06 22:59:24 +00002030 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002031 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002032 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002033
Chris Lattnerfd4de792007-01-27 01:15:32 +00002034 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002035 FunctionProtoType *NewIP =
2036 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002037 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002038 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002039
John McCall31168b02011-06-15 23:02:42 +00002040 // FunctionProtoType objects are allocated with extra bytes after
2041 // them for three variable size arrays at the end:
2042 // - parameter types
2043 // - exception types
2044 // - consumed-arguments flags
2045 // Instead of the exception types, there could be a noexcept
2046 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002047 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002048 NumArgs * sizeof(QualType);
2049 if (EPI.ExceptionSpecType == EST_Dynamic)
2050 Size += EPI.NumExceptions * sizeof(QualType);
2051 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002052 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002053 }
John McCall31168b02011-06-15 23:02:42 +00002054 if (EPI.ConsumedArguments)
2055 Size += NumArgs * sizeof(bool);
2056
John McCalldb40c7f2010-12-14 08:05:40 +00002057 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002058 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2059 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002060 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002061 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002062 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002063 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002064}
Chris Lattneref51c202006-11-10 07:17:23 +00002065
John McCalle78aac42010-03-10 03:28:59 +00002066#ifndef NDEBUG
2067static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2068 if (!isa<CXXRecordDecl>(D)) return false;
2069 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2070 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2071 return true;
2072 if (RD->getDescribedClassTemplate() &&
2073 !isa<ClassTemplateSpecializationDecl>(RD))
2074 return true;
2075 return false;
2076}
2077#endif
2078
2079/// getInjectedClassNameType - Return the unique reference to the
2080/// injected class name type for the specified templated declaration.
2081QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002082 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002083 assert(NeedsInjectedClassNameType(Decl));
2084 if (Decl->TypeForDecl) {
2085 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00002086 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00002087 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2088 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2089 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2090 } else {
John McCall424cec92011-01-19 06:33:43 +00002091 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002092 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002093 Decl->TypeForDecl = newType;
2094 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002095 }
2096 return QualType(Decl->TypeForDecl, 0);
2097}
2098
Douglas Gregor83a586e2008-04-13 21:07:44 +00002099/// getTypeDeclType - Return the unique reference to the type for the
2100/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002101QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002102 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002103 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002104
Richard Smithdda56e42011-04-15 14:24:37 +00002105 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002106 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002107
John McCall96f0b5f2010-03-10 06:48:02 +00002108 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2109 "Template type parameter types are always available.");
2110
John McCall81e38502010-02-16 03:57:14 +00002111 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002112 assert(!Record->getPreviousDeclaration() &&
2113 "struct/union has previous declaration");
2114 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002115 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002116 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002117 assert(!Enum->getPreviousDeclaration() &&
2118 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002119 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002120 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002121 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002122 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2123 Decl->TypeForDecl = newType;
2124 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002125 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002126 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002127
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002128 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002129}
2130
Chris Lattner32d920b2007-01-26 02:01:53 +00002131/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002132/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002133QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002134ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2135 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002136 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002137
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002138 if (Canonical.isNull())
2139 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002140 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002141 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002142 Decl->TypeForDecl = newType;
2143 Types.push_back(newType);
2144 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002145}
2146
Jay Foad39c79802011-01-12 09:06:06 +00002147QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002148 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2149
2150 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2151 if (PrevDecl->TypeForDecl)
2152 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2153
John McCall424cec92011-01-19 06:33:43 +00002154 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2155 Decl->TypeForDecl = newType;
2156 Types.push_back(newType);
2157 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002158}
2159
Jay Foad39c79802011-01-12 09:06:06 +00002160QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002161 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2162
2163 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2164 if (PrevDecl->TypeForDecl)
2165 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2166
John McCall424cec92011-01-19 06:33:43 +00002167 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2168 Decl->TypeForDecl = newType;
2169 Types.push_back(newType);
2170 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002171}
2172
John McCall81904512011-01-06 01:58:22 +00002173QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2174 QualType modifiedType,
2175 QualType equivalentType) {
2176 llvm::FoldingSetNodeID id;
2177 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2178
2179 void *insertPos = 0;
2180 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2181 if (type) return QualType(type, 0);
2182
2183 QualType canon = getCanonicalType(equivalentType);
2184 type = new (*this, TypeAlignment)
2185 AttributedType(canon, attrKind, modifiedType, equivalentType);
2186
2187 Types.push_back(type);
2188 AttributedTypes.InsertNode(type, insertPos);
2189
2190 return QualType(type, 0);
2191}
2192
2193
John McCallcebee162009-10-18 09:09:24 +00002194/// \brief Retrieve a substitution-result type.
2195QualType
2196ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002197 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002198 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002199 && "replacement types must always be canonical");
2200
2201 llvm::FoldingSetNodeID ID;
2202 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2203 void *InsertPos = 0;
2204 SubstTemplateTypeParmType *SubstParm
2205 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2206
2207 if (!SubstParm) {
2208 SubstParm = new (*this, TypeAlignment)
2209 SubstTemplateTypeParmType(Parm, Replacement);
2210 Types.push_back(SubstParm);
2211 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2212 }
2213
2214 return QualType(SubstParm, 0);
2215}
2216
Douglas Gregorada4b792011-01-14 02:55:32 +00002217/// \brief Retrieve a
2218QualType ASTContext::getSubstTemplateTypeParmPackType(
2219 const TemplateTypeParmType *Parm,
2220 const TemplateArgument &ArgPack) {
2221#ifndef NDEBUG
2222 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2223 PEnd = ArgPack.pack_end();
2224 P != PEnd; ++P) {
2225 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2226 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2227 }
2228#endif
2229
2230 llvm::FoldingSetNodeID ID;
2231 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2232 void *InsertPos = 0;
2233 if (SubstTemplateTypeParmPackType *SubstParm
2234 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2235 return QualType(SubstParm, 0);
2236
2237 QualType Canon;
2238 if (!Parm->isCanonicalUnqualified()) {
2239 Canon = getCanonicalType(QualType(Parm, 0));
2240 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2241 ArgPack);
2242 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2243 }
2244
2245 SubstTemplateTypeParmPackType *SubstParm
2246 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2247 ArgPack);
2248 Types.push_back(SubstParm);
2249 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2250 return QualType(SubstParm, 0);
2251}
2252
Douglas Gregoreff93e02009-02-05 23:33:38 +00002253/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002254/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002255/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002256QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002257 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002258 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002259 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002260 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002261 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002262 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002263 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2264
2265 if (TypeParm)
2266 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002267
Chandler Carruth08836322011-05-01 00:51:33 +00002268 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002269 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002270 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002271
2272 TemplateTypeParmType *TypeCheck
2273 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2274 assert(!TypeCheck && "Template type parameter canonical type broken");
2275 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002276 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002277 TypeParm = new (*this, TypeAlignment)
2278 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002279
2280 Types.push_back(TypeParm);
2281 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2282
2283 return QualType(TypeParm, 0);
2284}
2285
John McCalle78aac42010-03-10 03:28:59 +00002286TypeSourceInfo *
2287ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2288 SourceLocation NameLoc,
2289 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002290 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002291 assert(!Name.getAsDependentTemplateName() &&
2292 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002293 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002294
2295 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2296 TemplateSpecializationTypeLoc TL
2297 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2298 TL.setTemplateNameLoc(NameLoc);
2299 TL.setLAngleLoc(Args.getLAngleLoc());
2300 TL.setRAngleLoc(Args.getRAngleLoc());
2301 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2302 TL.setArgLocInfo(i, Args[i].getLocInfo());
2303 return DI;
2304}
2305
Mike Stump11289f42009-09-09 15:08:12 +00002306QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002307ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002308 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002309 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002310 assert(!Template.getAsDependentTemplateName() &&
2311 "No dependent template names here!");
2312
John McCall6b51f282009-11-23 01:53:49 +00002313 unsigned NumArgs = Args.size();
2314
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002315 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002316 ArgVec.reserve(NumArgs);
2317 for (unsigned i = 0; i != NumArgs; ++i)
2318 ArgVec.push_back(Args[i].getArgument());
2319
John McCall2408e322010-04-27 00:57:59 +00002320 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002321 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002322}
2323
2324QualType
2325ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002326 const TemplateArgument *Args,
2327 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002328 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002329 assert(!Template.getAsDependentTemplateName() &&
2330 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002331 // Look through qualified template names.
2332 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2333 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002334
Richard Smith3f1b5d02011-05-05 21:57:07 +00002335 bool isTypeAlias =
2336 Template.getAsTemplateDecl() &&
2337 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2338
2339 QualType CanonType;
2340 if (!Underlying.isNull())
2341 CanonType = getCanonicalType(Underlying);
2342 else {
2343 assert(!isTypeAlias &&
2344 "Underlying type for template alias must be computed by caller");
2345 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2346 NumArgs);
2347 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002348
Douglas Gregora8e02e72009-07-28 23:00:59 +00002349 // Allocate the (non-canonical) template specialization type, but don't
2350 // try to unique it: these types typically have location information that
2351 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002352 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2353 sizeof(TemplateArgument) * NumArgs +
2354 (isTypeAlias ? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002355 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002356 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002357 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002358 Args, NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002359 CanonType,
2360 isTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002361
Douglas Gregor8bf42052009-02-09 18:46:07 +00002362 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002363 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002364}
2365
Mike Stump11289f42009-09-09 15:08:12 +00002366QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002367ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2368 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002369 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002370 assert(!Template.getAsDependentTemplateName() &&
2371 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002372 assert((!Template.getAsTemplateDecl() ||
2373 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2374 "Underlying type for template alias must be computed by caller");
2375
Douglas Gregore29139c2011-03-03 17:04:51 +00002376 // Look through qualified template names.
2377 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2378 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002379
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002380 // Build the canonical template specialization type.
2381 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002382 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002383 CanonArgs.reserve(NumArgs);
2384 for (unsigned I = 0; I != NumArgs; ++I)
2385 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2386
2387 // Determine whether this canonical template specialization type already
2388 // exists.
2389 llvm::FoldingSetNodeID ID;
2390 TemplateSpecializationType::Profile(ID, CanonTemplate,
2391 CanonArgs.data(), NumArgs, *this);
2392
2393 void *InsertPos = 0;
2394 TemplateSpecializationType *Spec
2395 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2396
2397 if (!Spec) {
2398 // Allocate a new canonical template specialization type.
2399 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2400 sizeof(TemplateArgument) * NumArgs),
2401 TypeAlignment);
2402 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2403 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002404 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002405 Types.push_back(Spec);
2406 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2407 }
2408
2409 assert(Spec->isDependentType() &&
2410 "Non-dependent template-id type must have a canonical type");
2411 return QualType(Spec, 0);
2412}
2413
2414QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002415ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2416 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002417 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002418 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002419 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002420
2421 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002422 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002423 if (T)
2424 return QualType(T, 0);
2425
Douglas Gregorc42075a2010-02-04 18:10:26 +00002426 QualType Canon = NamedType;
2427 if (!Canon.isCanonical()) {
2428 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002429 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2430 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002431 (void)CheckT;
2432 }
2433
Abramo Bagnara6150c882010-05-11 21:36:43 +00002434 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002435 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002436 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002437 return QualType(T, 0);
2438}
2439
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002440QualType
Jay Foad39c79802011-01-12 09:06:06 +00002441ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002442 llvm::FoldingSetNodeID ID;
2443 ParenType::Profile(ID, InnerType);
2444
2445 void *InsertPos = 0;
2446 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2447 if (T)
2448 return QualType(T, 0);
2449
2450 QualType Canon = InnerType;
2451 if (!Canon.isCanonical()) {
2452 Canon = getCanonicalType(InnerType);
2453 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2454 assert(!CheckT && "Paren canonical type broken");
2455 (void)CheckT;
2456 }
2457
2458 T = new (*this) ParenType(InnerType, Canon);
2459 Types.push_back(T);
2460 ParenTypes.InsertNode(T, InsertPos);
2461 return QualType(T, 0);
2462}
2463
Douglas Gregor02085352010-03-31 20:19:30 +00002464QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2465 NestedNameSpecifier *NNS,
2466 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002467 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002468 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2469
2470 if (Canon.isNull()) {
2471 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002472 ElaboratedTypeKeyword CanonKeyword = Keyword;
2473 if (Keyword == ETK_None)
2474 CanonKeyword = ETK_Typename;
2475
2476 if (CanonNNS != NNS || CanonKeyword != Keyword)
2477 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002478 }
2479
2480 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002481 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002482
2483 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002484 DependentNameType *T
2485 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002486 if (T)
2487 return QualType(T, 0);
2488
Douglas Gregor02085352010-03-31 20:19:30 +00002489 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002490 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002491 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002492 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002493}
2494
Mike Stump11289f42009-09-09 15:08:12 +00002495QualType
John McCallc392f372010-06-11 00:33:02 +00002496ASTContext::getDependentTemplateSpecializationType(
2497 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002498 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002499 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002500 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002501 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002502 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002503 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2504 ArgCopy.push_back(Args[I].getArgument());
2505 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2506 ArgCopy.size(),
2507 ArgCopy.data());
2508}
2509
2510QualType
2511ASTContext::getDependentTemplateSpecializationType(
2512 ElaboratedTypeKeyword Keyword,
2513 NestedNameSpecifier *NNS,
2514 const IdentifierInfo *Name,
2515 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002516 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002517 assert((!NNS || NNS->isDependent()) &&
2518 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002519
Douglas Gregorc42075a2010-02-04 18:10:26 +00002520 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002521 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2522 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002523
2524 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002525 DependentTemplateSpecializationType *T
2526 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002527 if (T)
2528 return QualType(T, 0);
2529
John McCallc392f372010-06-11 00:33:02 +00002530 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002531
John McCallc392f372010-06-11 00:33:02 +00002532 ElaboratedTypeKeyword CanonKeyword = Keyword;
2533 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2534
2535 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002536 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002537 for (unsigned I = 0; I != NumArgs; ++I) {
2538 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2539 if (!CanonArgs[I].structurallyEquals(Args[I]))
2540 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002541 }
2542
John McCallc392f372010-06-11 00:33:02 +00002543 QualType Canon;
2544 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2545 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2546 Name, NumArgs,
2547 CanonArgs.data());
2548
2549 // Find the insert position again.
2550 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2551 }
2552
2553 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2554 sizeof(TemplateArgument) * NumArgs),
2555 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002556 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002557 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002558 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002559 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002560 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002561}
2562
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002563QualType ASTContext::getPackExpansionType(QualType Pattern,
2564 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002565 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002566 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002567
2568 assert(Pattern->containsUnexpandedParameterPack() &&
2569 "Pack expansions must expand one or more parameter packs");
2570 void *InsertPos = 0;
2571 PackExpansionType *T
2572 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2573 if (T)
2574 return QualType(T, 0);
2575
2576 QualType Canon;
2577 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002578 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002579
2580 // Find the insert position again.
2581 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2582 }
2583
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002584 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002585 Types.push_back(T);
2586 PackExpansionTypes.InsertNode(T, InsertPos);
2587 return QualType(T, 0);
2588}
2589
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002590/// CmpProtocolNames - Comparison predicate for sorting protocols
2591/// alphabetically.
2592static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2593 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002594 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002595}
2596
John McCall8b07ec22010-05-15 11:32:37 +00002597static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002598 unsigned NumProtocols) {
2599 if (NumProtocols == 0) return true;
2600
2601 for (unsigned i = 1; i != NumProtocols; ++i)
2602 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2603 return false;
2604 return true;
2605}
2606
2607static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002608 unsigned &NumProtocols) {
2609 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002610
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002611 // Sort protocols, keyed by name.
2612 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2613
2614 // Remove duplicates.
2615 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2616 NumProtocols = ProtocolsEnd-Protocols;
2617}
2618
John McCall8b07ec22010-05-15 11:32:37 +00002619QualType ASTContext::getObjCObjectType(QualType BaseType,
2620 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002621 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002622 // If the base type is an interface and there aren't any protocols
2623 // to add, then the interface type will do just fine.
2624 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2625 return BaseType;
2626
2627 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002628 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002629 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002630 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002631 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2632 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002633
John McCall8b07ec22010-05-15 11:32:37 +00002634 // Build the canonical type, which has the canonical base type and
2635 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002636 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002637 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2638 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2639 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002640 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002641 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002642 unsigned UniqueCount = NumProtocols;
2643
John McCallfc93cf92009-10-22 22:37:11 +00002644 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002645 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2646 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002647 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002648 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2649 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002650 }
2651
2652 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002653 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2654 }
2655
2656 unsigned Size = sizeof(ObjCObjectTypeImpl);
2657 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2658 void *Mem = Allocate(Size, TypeAlignment);
2659 ObjCObjectTypeImpl *T =
2660 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2661
2662 Types.push_back(T);
2663 ObjCObjectTypes.InsertNode(T, InsertPos);
2664 return QualType(T, 0);
2665}
2666
2667/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2668/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002669QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002670 llvm::FoldingSetNodeID ID;
2671 ObjCObjectPointerType::Profile(ID, ObjectT);
2672
2673 void *InsertPos = 0;
2674 if (ObjCObjectPointerType *QT =
2675 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2676 return QualType(QT, 0);
2677
2678 // Find the canonical object type.
2679 QualType Canonical;
2680 if (!ObjectT.isCanonical()) {
2681 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2682
2683 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002684 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2685 }
2686
Douglas Gregorf85bee62010-02-08 22:59:26 +00002687 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002688 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2689 ObjCObjectPointerType *QType =
2690 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002691
Steve Narofffb4330f2009-06-17 22:40:22 +00002692 Types.push_back(QType);
2693 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002694 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002695}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002696
Douglas Gregor1c283312010-08-11 12:19:30 +00002697/// getObjCInterfaceType - Return the unique reference to the type for the
2698/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002699QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002700 if (Decl->TypeForDecl)
2701 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002702
Douglas Gregor1c283312010-08-11 12:19:30 +00002703 // FIXME: redeclarations?
2704 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2705 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2706 Decl->TypeForDecl = T;
2707 Types.push_back(T);
2708 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002709}
2710
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002711/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2712/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002713/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002714/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002715/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002716QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002717 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002718 if (tofExpr->isTypeDependent()) {
2719 llvm::FoldingSetNodeID ID;
2720 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002721
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002722 void *InsertPos = 0;
2723 DependentTypeOfExprType *Canon
2724 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2725 if (Canon) {
2726 // We already have a "canonical" version of an identical, dependent
2727 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002728 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002729 QualType((TypeOfExprType*)Canon, 0));
2730 }
2731 else {
2732 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002733 Canon
2734 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002735 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2736 toe = Canon;
2737 }
2738 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002739 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002740 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002741 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002742 Types.push_back(toe);
2743 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002744}
2745
Steve Naroffa773cd52007-08-01 18:02:17 +00002746/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2747/// TypeOfType AST's. The only motivation to unique these nodes would be
2748/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002749/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002750/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002751QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002752 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002753 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002754 Types.push_back(tot);
2755 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002756}
2757
Anders Carlssonad6bd352009-06-24 21:24:56 +00002758/// getDecltypeForExpr - Given an expr, will return the decltype for that
2759/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002760static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002761 if (e->isTypeDependent())
2762 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002763
Anders Carlssonad6bd352009-06-24 21:24:56 +00002764 // If e is an id expression or a class member access, decltype(e) is defined
2765 // as the type of the entity named by e.
2766 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2767 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2768 return VD->getType();
2769 }
2770 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2771 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2772 return FD->getType();
2773 }
2774 // If e is a function call or an invocation of an overloaded operator,
2775 // (parentheses around e are ignored), decltype(e) is defined as the
2776 // return type of that function.
2777 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2778 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002779
Anders Carlssonad6bd352009-06-24 21:24:56 +00002780 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002781
2782 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002783 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002784 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002785 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002786
Anders Carlssonad6bd352009-06-24 21:24:56 +00002787 return T;
2788}
2789
Anders Carlsson81df7b82009-06-24 19:06:50 +00002790/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2791/// DecltypeType AST's. The only motivation to unique these nodes would be
2792/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002793/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002794/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002795QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002796 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002797
2798 // C++0x [temp.type]p2:
2799 // If an expression e involves a template parameter, decltype(e) denotes a
2800 // unique dependent type. Two such decltype-specifiers refer to the same
2801 // type only if their expressions are equivalent (14.5.6.1).
2802 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002803 llvm::FoldingSetNodeID ID;
2804 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002805
Douglas Gregora21f6c32009-07-30 23:36:40 +00002806 void *InsertPos = 0;
2807 DependentDecltypeType *Canon
2808 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2809 if (Canon) {
2810 // We already have a "canonical" version of an equivalent, dependent
2811 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002812 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002813 QualType((DecltypeType*)Canon, 0));
2814 }
2815 else {
2816 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002817 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002818 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2819 dt = Canon;
2820 }
2821 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002822 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002823 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002824 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002825 Types.push_back(dt);
2826 return QualType(dt, 0);
2827}
2828
Alexis Hunte852b102011-05-24 22:41:36 +00002829/// getUnaryTransformationType - We don't unique these, since the memory
2830/// savings are minimal and these are rare.
2831QualType ASTContext::getUnaryTransformType(QualType BaseType,
2832 QualType UnderlyingType,
2833 UnaryTransformType::UTTKind Kind)
2834 const {
2835 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002836 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2837 Kind,
2838 UnderlyingType->isDependentType() ?
2839 QualType() : UnderlyingType);
Alexis Hunte852b102011-05-24 22:41:36 +00002840 Types.push_back(Ty);
2841 return QualType(Ty, 0);
2842}
2843
Richard Smithb2bc2e62011-02-21 20:05:19 +00002844/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002845QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002846 void *InsertPos = 0;
2847 if (!DeducedType.isNull()) {
2848 // Look in the folding set for an existing type.
2849 llvm::FoldingSetNodeID ID;
2850 AutoType::Profile(ID, DeducedType);
2851 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2852 return QualType(AT, 0);
2853 }
2854
2855 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2856 Types.push_back(AT);
2857 if (InsertPos)
2858 AutoTypes.InsertNode(AT, InsertPos);
2859 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002860}
2861
Richard Smith02e85f32011-04-14 22:09:26 +00002862/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2863QualType ASTContext::getAutoDeductType() const {
2864 if (AutoDeductTy.isNull())
2865 AutoDeductTy = getAutoType(QualType());
2866 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2867 return AutoDeductTy;
2868}
2869
2870/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2871QualType ASTContext::getAutoRRefDeductType() const {
2872 if (AutoRRefDeductTy.isNull())
2873 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2874 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2875 return AutoRRefDeductTy;
2876}
2877
Chris Lattnerfb072462007-01-23 05:45:31 +00002878/// getTagDeclType - Return the unique reference to the type for the
2879/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002880QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002881 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002882 // FIXME: What is the design on getTagDeclType when it requires casting
2883 // away const? mutable?
2884 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002885}
2886
Mike Stump11289f42009-09-09 15:08:12 +00002887/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2888/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2889/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002890CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002891 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002892}
Chris Lattnerfb072462007-01-23 05:45:31 +00002893
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002894/// getSignedWCharType - Return the type of "signed wchar_t".
2895/// Used when in C++, as a GCC extension.
2896QualType ASTContext::getSignedWCharType() const {
2897 // FIXME: derive from "Target" ?
2898 return WCharTy;
2899}
2900
2901/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2902/// Used when in C++, as a GCC extension.
2903QualType ASTContext::getUnsignedWCharType() const {
2904 // FIXME: derive from "Target" ?
2905 return UnsignedIntTy;
2906}
2907
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002908/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2909/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2910QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002911 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002912}
2913
Chris Lattnera21ad802008-04-02 05:18:44 +00002914//===----------------------------------------------------------------------===//
2915// Type Operators
2916//===----------------------------------------------------------------------===//
2917
Jay Foad39c79802011-01-12 09:06:06 +00002918CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002919 // Push qualifiers into arrays, and then discard any remaining
2920 // qualifiers.
2921 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002922 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002923 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002924 QualType Result;
2925 if (isa<ArrayType>(Ty)) {
2926 Result = getArrayDecayedType(QualType(Ty,0));
2927 } else if (isa<FunctionType>(Ty)) {
2928 Result = getPointerType(QualType(Ty, 0));
2929 } else {
2930 Result = QualType(Ty, 0);
2931 }
2932
2933 return CanQualType::CreateUnsafe(Result);
2934}
2935
John McCall6c9dd522011-01-18 07:41:22 +00002936QualType ASTContext::getUnqualifiedArrayType(QualType type,
2937 Qualifiers &quals) {
2938 SplitQualType splitType = type.getSplitUnqualifiedType();
2939
2940 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2941 // the unqualified desugared type and then drops it on the floor.
2942 // We then have to strip that sugar back off with
2943 // getUnqualifiedDesugaredType(), which is silly.
2944 const ArrayType *AT =
2945 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2946
2947 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002948 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002949 quals = splitType.second;
2950 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002951 }
2952
John McCall6c9dd522011-01-18 07:41:22 +00002953 // Otherwise, recurse on the array's element type.
2954 QualType elementType = AT->getElementType();
2955 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2956
2957 // If that didn't change the element type, AT has no qualifiers, so we
2958 // can just use the results in splitType.
2959 if (elementType == unqualElementType) {
2960 assert(quals.empty()); // from the recursive call
2961 quals = splitType.second;
2962 return QualType(splitType.first, 0);
2963 }
2964
2965 // Otherwise, add in the qualifiers from the outermost type, then
2966 // build the type back up.
2967 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002968
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002969 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002970 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002971 CAT->getSizeModifier(), 0);
2972 }
2973
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002974 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002975 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002976 }
2977
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002978 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002979 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002980 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002981 VAT->getSizeModifier(),
2982 VAT->getIndexTypeCVRQualifiers(),
2983 VAT->getBracketsRange());
2984 }
2985
2986 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00002987 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002988 DSAT->getSizeModifier(), 0,
2989 SourceRange());
2990}
2991
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002992/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2993/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2994/// they point to and return true. If T1 and T2 aren't pointer types
2995/// or pointer-to-member types, or if they are not similar at this
2996/// level, returns false and leaves T1 and T2 unchanged. Top-level
2997/// qualifiers on T1 and T2 are ignored. This function will typically
2998/// be called in a loop that successively "unwraps" pointer and
2999/// pointer-to-member types to compare them at each level.
3000bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3001 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3002 *T2PtrType = T2->getAs<PointerType>();
3003 if (T1PtrType && T2PtrType) {
3004 T1 = T1PtrType->getPointeeType();
3005 T2 = T2PtrType->getPointeeType();
3006 return true;
3007 }
3008
3009 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3010 *T2MPType = T2->getAs<MemberPointerType>();
3011 if (T1MPType && T2MPType &&
3012 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3013 QualType(T2MPType->getClass(), 0))) {
3014 T1 = T1MPType->getPointeeType();
3015 T2 = T2MPType->getPointeeType();
3016 return true;
3017 }
3018
3019 if (getLangOptions().ObjC1) {
3020 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3021 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3022 if (T1OPType && T2OPType) {
3023 T1 = T1OPType->getPointeeType();
3024 T2 = T2OPType->getPointeeType();
3025 return true;
3026 }
3027 }
3028
3029 // FIXME: Block pointers, too?
3030
3031 return false;
3032}
3033
Jay Foad39c79802011-01-12 09:06:06 +00003034DeclarationNameInfo
3035ASTContext::getNameForTemplate(TemplateName Name,
3036 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003037 switch (Name.getKind()) {
3038 case TemplateName::QualifiedTemplate:
3039 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003040 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003041 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3042 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003043
John McCalld9dfe3a2011-06-30 08:33:18 +00003044 case TemplateName::OverloadedTemplate: {
3045 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3046 // DNInfo work in progress: CHECKME: what about DNLoc?
3047 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3048 }
3049
3050 case TemplateName::DependentTemplate: {
3051 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003052 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003053 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003054 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3055 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003056 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003057 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3058 // DNInfo work in progress: FIXME: source locations?
3059 DeclarationNameLoc DNLoc;
3060 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3061 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3062 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003063 }
3064 }
3065
John McCalld9dfe3a2011-06-30 08:33:18 +00003066 case TemplateName::SubstTemplateTemplateParm: {
3067 SubstTemplateTemplateParmStorage *subst
3068 = Name.getAsSubstTemplateTemplateParm();
3069 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3070 NameLoc);
3071 }
3072
3073 case TemplateName::SubstTemplateTemplateParmPack: {
3074 SubstTemplateTemplateParmPackStorage *subst
3075 = Name.getAsSubstTemplateTemplateParmPack();
3076 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3077 NameLoc);
3078 }
3079 }
3080
3081 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003082}
3083
Jay Foad39c79802011-01-12 09:06:06 +00003084TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003085 switch (Name.getKind()) {
3086 case TemplateName::QualifiedTemplate:
3087 case TemplateName::Template: {
3088 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003089 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003090 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003091 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3092
3093 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003094 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003095 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003096
John McCalld9dfe3a2011-06-30 08:33:18 +00003097 case TemplateName::OverloadedTemplate:
3098 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003099
John McCalld9dfe3a2011-06-30 08:33:18 +00003100 case TemplateName::DependentTemplate: {
3101 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3102 assert(DTN && "Non-dependent template names must refer to template decls.");
3103 return DTN->CanonicalTemplateName;
3104 }
3105
3106 case TemplateName::SubstTemplateTemplateParm: {
3107 SubstTemplateTemplateParmStorage *subst
3108 = Name.getAsSubstTemplateTemplateParm();
3109 return getCanonicalTemplateName(subst->getReplacement());
3110 }
3111
3112 case TemplateName::SubstTemplateTemplateParmPack: {
3113 SubstTemplateTemplateParmPackStorage *subst
3114 = Name.getAsSubstTemplateTemplateParmPack();
3115 TemplateTemplateParmDecl *canonParameter
3116 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3117 TemplateArgument canonArgPack
3118 = getCanonicalTemplateArgument(subst->getArgumentPack());
3119 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3120 }
3121 }
3122
3123 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003124}
3125
Douglas Gregoradee3e32009-11-11 23:06:43 +00003126bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3127 X = getCanonicalTemplateName(X);
3128 Y = getCanonicalTemplateName(Y);
3129 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3130}
3131
Mike Stump11289f42009-09-09 15:08:12 +00003132TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003133ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003134 switch (Arg.getKind()) {
3135 case TemplateArgument::Null:
3136 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003137
Douglas Gregora8e02e72009-07-28 23:00:59 +00003138 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003139 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003140
Douglas Gregora8e02e72009-07-28 23:00:59 +00003141 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003142 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003143
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003144 case TemplateArgument::Template:
3145 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003146
3147 case TemplateArgument::TemplateExpansion:
3148 return TemplateArgument(getCanonicalTemplateName(
3149 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003150 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003151
Douglas Gregora8e02e72009-07-28 23:00:59 +00003152 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003153 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003154 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003155
Douglas Gregora8e02e72009-07-28 23:00:59 +00003156 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003157 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003158
Douglas Gregora8e02e72009-07-28 23:00:59 +00003159 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003160 if (Arg.pack_size() == 0)
3161 return Arg;
3162
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003163 TemplateArgument *CanonArgs
3164 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003165 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003166 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003167 AEnd = Arg.pack_end();
3168 A != AEnd; (void)++A, ++Idx)
3169 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003170
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003171 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003172 }
3173 }
3174
3175 // Silence GCC warning
3176 assert(false && "Unhandled template argument kind");
3177 return TemplateArgument();
3178}
3179
Douglas Gregor333489b2009-03-27 23:10:48 +00003180NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003181ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003182 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003183 return 0;
3184
3185 switch (NNS->getKind()) {
3186 case NestedNameSpecifier::Identifier:
3187 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003188 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003189 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3190 NNS->getAsIdentifier());
3191
3192 case NestedNameSpecifier::Namespace:
3193 // A namespace is canonical; build a nested-name-specifier with
3194 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003195 return NestedNameSpecifier::Create(*this, 0,
3196 NNS->getAsNamespace()->getOriginalNamespace());
3197
3198 case NestedNameSpecifier::NamespaceAlias:
3199 // A namespace is canonical; build a nested-name-specifier with
3200 // this namespace and no prefix.
3201 return NestedNameSpecifier::Create(*this, 0,
3202 NNS->getAsNamespaceAlias()->getNamespace()
3203 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003204
3205 case NestedNameSpecifier::TypeSpec:
3206 case NestedNameSpecifier::TypeSpecWithTemplate: {
3207 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003208
3209 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3210 // break it apart into its prefix and identifier, then reconsititute those
3211 // as the canonical nested-name-specifier. This is required to canonicalize
3212 // a dependent nested-name-specifier involving typedefs of dependent-name
3213 // types, e.g.,
3214 // typedef typename T::type T1;
3215 // typedef typename T1::type T2;
3216 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3217 NestedNameSpecifier *Prefix
3218 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3219 return NestedNameSpecifier::Create(*this, Prefix,
3220 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3221 }
3222
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003223 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003224 if (const DependentTemplateSpecializationType *DTST
3225 = T->getAs<DependentTemplateSpecializationType>()) {
3226 NestedNameSpecifier *Prefix
3227 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003228
3229 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3230 Prefix, DTST->getIdentifier(),
3231 DTST->getNumArgs(),
3232 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003233 T = getCanonicalType(T);
3234 }
3235
John McCall33ddac02011-01-19 10:06:00 +00003236 return NestedNameSpecifier::Create(*this, 0, false,
3237 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003238 }
3239
3240 case NestedNameSpecifier::Global:
3241 // The global specifier is canonical and unique.
3242 return NNS;
3243 }
3244
3245 // Required to silence a GCC warning
3246 return 0;
3247}
3248
Chris Lattner7adf0762008-08-04 07:31:14 +00003249
Jay Foad39c79802011-01-12 09:06:06 +00003250const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003251 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003252 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003253 // Handle the common positive case fast.
3254 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3255 return AT;
3256 }
Mike Stump11289f42009-09-09 15:08:12 +00003257
John McCall8ccfcb52009-09-24 19:53:00 +00003258 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003259 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003260 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003261
John McCall8ccfcb52009-09-24 19:53:00 +00003262 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003263 // implements C99 6.7.3p8: "If the specification of an array type includes
3264 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003265
Chris Lattner7adf0762008-08-04 07:31:14 +00003266 // If we get here, we either have type qualifiers on the type, or we have
3267 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003268 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003269
John McCall33ddac02011-01-19 10:06:00 +00003270 SplitQualType split = T.getSplitDesugaredType();
3271 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003272
Chris Lattner7adf0762008-08-04 07:31:14 +00003273 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003274 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3275 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003276 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003277
Chris Lattner7adf0762008-08-04 07:31:14 +00003278 // Otherwise, we have an array and we have qualifiers on it. Push the
3279 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003280 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003281
Chris Lattner7adf0762008-08-04 07:31:14 +00003282 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3283 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3284 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003285 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003286 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3287 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3288 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003289 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003290
Mike Stump11289f42009-09-09 15:08:12 +00003291 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003292 = dyn_cast<DependentSizedArrayType>(ATy))
3293 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003294 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003295 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003296 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003297 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003298 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003299
Chris Lattner7adf0762008-08-04 07:31:14 +00003300 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003301 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003302 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003303 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003304 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003305 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003306}
3307
Douglas Gregor84280642011-07-12 04:42:08 +00003308QualType ASTContext::getAdjustedParameterType(QualType T) {
3309 // C99 6.7.5.3p7:
3310 // A declaration of a parameter as "array of type" shall be
3311 // adjusted to "qualified pointer to type", where the type
3312 // qualifiers (if any) are those specified within the [ and ] of
3313 // the array type derivation.
3314 if (T->isArrayType())
3315 return getArrayDecayedType(T);
3316
3317 // C99 6.7.5.3p8:
3318 // A declaration of a parameter as "function returning type"
3319 // shall be adjusted to "pointer to function returning type", as
3320 // in 6.3.2.1.
3321 if (T->isFunctionType())
3322 return getPointerType(T);
3323
3324 return T;
3325}
3326
3327QualType ASTContext::getSignatureParameterType(QualType T) {
3328 T = getVariableArrayDecayedType(T);
3329 T = getAdjustedParameterType(T);
3330 return T.getUnqualifiedType();
3331}
3332
Chris Lattnera21ad802008-04-02 05:18:44 +00003333/// getArrayDecayedType - Return the properly qualified result of decaying the
3334/// specified array type to a pointer. This operation is non-trivial when
3335/// handling typedefs etc. The canonical type of "T" must be an array type,
3336/// this returns a pointer to a properly qualified element of the array.
3337///
3338/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003339QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003340 // Get the element type with 'getAsArrayType' so that we don't lose any
3341 // typedefs in the element type of the array. This also handles propagation
3342 // of type qualifiers from the array type into the element type if present
3343 // (C99 6.7.3p8).
3344 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3345 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003346
Chris Lattner7adf0762008-08-04 07:31:14 +00003347 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003348
3349 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003350 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003351}
3352
John McCall33ddac02011-01-19 10:06:00 +00003353QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3354 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003355}
3356
John McCall33ddac02011-01-19 10:06:00 +00003357QualType ASTContext::getBaseElementType(QualType type) const {
3358 Qualifiers qs;
3359 while (true) {
3360 SplitQualType split = type.getSplitDesugaredType();
3361 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3362 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003363
John McCall33ddac02011-01-19 10:06:00 +00003364 type = array->getElementType();
3365 qs.addConsistentQualifiers(split.second);
3366 }
Mike Stump11289f42009-09-09 15:08:12 +00003367
John McCall33ddac02011-01-19 10:06:00 +00003368 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003369}
3370
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003371/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003372uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003373ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3374 uint64_t ElementCount = 1;
3375 do {
3376 ElementCount *= CA->getSize().getZExtValue();
3377 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3378 } while (CA);
3379 return ElementCount;
3380}
3381
Steve Naroff0af91202007-04-27 21:51:21 +00003382/// getFloatingRank - Return a relative rank for floating point types.
3383/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003384static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003385 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003386 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003387
John McCall9dd450b2009-09-21 23:43:11 +00003388 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3389 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003390 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003391 case BuiltinType::Float: return FloatRank;
3392 case BuiltinType::Double: return DoubleRank;
3393 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003394 }
3395}
3396
Mike Stump11289f42009-09-09 15:08:12 +00003397/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3398/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003399/// 'typeDomain' is a real floating point or complex type.
3400/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003401QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3402 QualType Domain) const {
3403 FloatingRank EltRank = getFloatingRank(Size);
3404 if (Domain->isComplexType()) {
3405 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003406 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003407 case FloatRank: return FloatComplexTy;
3408 case DoubleRank: return DoubleComplexTy;
3409 case LongDoubleRank: return LongDoubleComplexTy;
3410 }
Steve Naroff0af91202007-04-27 21:51:21 +00003411 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003412
3413 assert(Domain->isRealFloatingType() && "Unknown domain!");
3414 switch (EltRank) {
3415 default: assert(0 && "getFloatingRank(): illegal value for rank");
3416 case FloatRank: return FloatTy;
3417 case DoubleRank: return DoubleTy;
3418 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003419 }
Steve Naroffe4718892007-04-27 18:30:00 +00003420}
3421
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003422/// getFloatingTypeOrder - Compare the rank of the two specified floating
3423/// point types, ignoring the domain of the type (i.e. 'double' ==
3424/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003425/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003426int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003427 FloatingRank LHSR = getFloatingRank(LHS);
3428 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003429
Chris Lattnerb90739d2008-04-06 23:38:49 +00003430 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003431 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003432 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003433 return 1;
3434 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003435}
3436
Chris Lattner76a00cf2008-04-06 22:59:24 +00003437/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3438/// routine will assert if passed a built-in type that isn't an integer or enum,
3439/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003440unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003441 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003442 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003443 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003444
Chris Lattnerad3467e2010-12-25 23:25:43 +00003445 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3446 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003447 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3448
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003449 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3450 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3451
3452 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3453 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3454
Chris Lattner76a00cf2008-04-06 22:59:24 +00003455 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003456 default: assert(0 && "getIntegerRank(): not a built-in integer");
3457 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003458 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003459 case BuiltinType::Char_S:
3460 case BuiltinType::Char_U:
3461 case BuiltinType::SChar:
3462 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003463 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003464 case BuiltinType::Short:
3465 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003466 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003467 case BuiltinType::Int:
3468 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003469 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003470 case BuiltinType::Long:
3471 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003472 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003473 case BuiltinType::LongLong:
3474 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003475 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003476 case BuiltinType::Int128:
3477 case BuiltinType::UInt128:
3478 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003479 }
3480}
3481
Eli Friedman629ffb92009-08-20 04:21:42 +00003482/// \brief Whether this is a promotable bitfield reference according
3483/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3484///
3485/// \returns the type this bit-field will promote to, or NULL if no
3486/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003487QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003488 if (E->isTypeDependent() || E->isValueDependent())
3489 return QualType();
3490
Eli Friedman629ffb92009-08-20 04:21:42 +00003491 FieldDecl *Field = E->getBitField();
3492 if (!Field)
3493 return QualType();
3494
3495 QualType FT = Field->getType();
3496
3497 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3498 uint64_t BitWidth = BitWidthAP.getZExtValue();
3499 uint64_t IntSize = getTypeSize(IntTy);
3500 // GCC extension compatibility: if the bit-field size is less than or equal
3501 // to the size of int, it gets promoted no matter what its type is.
3502 // For instance, unsigned long bf : 4 gets promoted to signed int.
3503 if (BitWidth < IntSize)
3504 return IntTy;
3505
3506 if (BitWidth == IntSize)
3507 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3508
3509 // Types bigger than int are not subject to promotions, and therefore act
3510 // like the base type.
3511 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3512 // is ridiculous.
3513 return QualType();
3514}
3515
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003516/// getPromotedIntegerType - Returns the type that Promotable will
3517/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3518/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003519QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003520 assert(!Promotable.isNull());
3521 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003522 if (const EnumType *ET = Promotable->getAs<EnumType>())
3523 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003524 if (Promotable->isSignedIntegerType())
3525 return IntTy;
3526 uint64_t PromotableSize = getTypeSize(Promotable);
3527 uint64_t IntSize = getTypeSize(IntTy);
3528 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3529 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3530}
3531
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003532/// \brief Recurses in pointer/array types until it finds an objc retainable
3533/// type and returns its ownership.
3534Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3535 while (!T.isNull()) {
3536 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3537 return T.getObjCLifetime();
3538 if (T->isArrayType())
3539 T = getBaseElementType(T);
3540 else if (const PointerType *PT = T->getAs<PointerType>())
3541 T = PT->getPointeeType();
3542 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003543 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003544 else
3545 break;
3546 }
3547
3548 return Qualifiers::OCL_None;
3549}
3550
Mike Stump11289f42009-09-09 15:08:12 +00003551/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003552/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003553/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003554int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003555 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3556 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003557 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003558
Chris Lattner76a00cf2008-04-06 22:59:24 +00003559 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3560 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003561
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003562 unsigned LHSRank = getIntegerRank(LHSC);
3563 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003564
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003565 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3566 if (LHSRank == RHSRank) return 0;
3567 return LHSRank > RHSRank ? 1 : -1;
3568 }
Mike Stump11289f42009-09-09 15:08:12 +00003569
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003570 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3571 if (LHSUnsigned) {
3572 // If the unsigned [LHS] type is larger, return it.
3573 if (LHSRank >= RHSRank)
3574 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003575
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003576 // If the signed type can represent all values of the unsigned type, it
3577 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003578 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003579 return -1;
3580 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003581
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003582 // If the unsigned [RHS] type is larger, return it.
3583 if (RHSRank >= LHSRank)
3584 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003585
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003586 // If the signed type can represent all values of the unsigned type, it
3587 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003588 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003589 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003590}
Anders Carlsson98f07902007-08-17 05:31:46 +00003591
Anders Carlsson6d417272009-11-14 21:45:58 +00003592static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003593CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3594 DeclContext *DC, IdentifierInfo *Id) {
3595 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003596 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003597 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003598 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003599 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003600}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003601
Mike Stump11289f42009-09-09 15:08:12 +00003602// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003603QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003604 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003605 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003606 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003607 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003608 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003609
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003610 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003611
Anders Carlsson98f07902007-08-17 05:31:46 +00003612 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003613 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003614 // int flags;
3615 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003616 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003617 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003618 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003619 FieldTypes[3] = LongTy;
3620
Anders Carlsson98f07902007-08-17 05:31:46 +00003621 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003622 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003623 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003624 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003625 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003626 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003627 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003628 /*Mutable=*/false,
3629 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003630 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003631 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003632 }
3633
Douglas Gregord5058122010-02-11 01:19:42 +00003634 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003635 }
Mike Stump11289f42009-09-09 15:08:12 +00003636
Anders Carlsson98f07902007-08-17 05:31:46 +00003637 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003638}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003639
Douglas Gregor512b0772009-04-23 22:29:11 +00003640void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003641 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003642 assert(Rec && "Invalid CFConstantStringType");
3643 CFConstantStringTypeDecl = Rec->getDecl();
3644}
3645
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003646// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003647QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003648 if (!NSConstantStringTypeDecl) {
3649 NSConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003650 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003651 &Idents.get("__builtin_NSString"));
3652 NSConstantStringTypeDecl->startDefinition();
3653
3654 QualType FieldTypes[3];
3655
3656 // const int *isa;
3657 FieldTypes[0] = getPointerType(IntTy.withConst());
3658 // const char *str;
3659 FieldTypes[1] = getPointerType(CharTy.withConst());
3660 // unsigned int length;
3661 FieldTypes[2] = UnsignedIntTy;
3662
3663 // Create fields
3664 for (unsigned i = 0; i < 3; ++i) {
3665 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003666 SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003667 SourceLocation(), 0,
3668 FieldTypes[i], /*TInfo=*/0,
3669 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003670 /*Mutable=*/false,
3671 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003672 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003673 NSConstantStringTypeDecl->addDecl(Field);
3674 }
3675
3676 NSConstantStringTypeDecl->completeDefinition();
3677 }
3678
3679 return getTagDeclType(NSConstantStringTypeDecl);
3680}
3681
3682void ASTContext::setNSConstantStringType(QualType T) {
3683 const RecordType *Rec = T->getAs<RecordType>();
3684 assert(Rec && "Invalid NSConstantStringType");
3685 NSConstantStringTypeDecl = Rec->getDecl();
3686}
3687
Jay Foad39c79802011-01-12 09:06:06 +00003688QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003689 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003690 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003691 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003692 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003693 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003694
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003695 QualType FieldTypes[] = {
3696 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003697 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003698 getPointerType(UnsignedLongTy),
3699 getConstantArrayType(UnsignedLongTy,
3700 llvm::APInt(32, 5), ArrayType::Normal, 0)
3701 };
Mike Stump11289f42009-09-09 15:08:12 +00003702
Douglas Gregor91f84212008-12-11 16:49:14 +00003703 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003704 FieldDecl *Field = FieldDecl::Create(*this,
3705 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003706 SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003707 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003708 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003709 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003710 /*Mutable=*/false,
3711 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003712 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003713 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003714 }
Mike Stump11289f42009-09-09 15:08:12 +00003715
Douglas Gregord5058122010-02-11 01:19:42 +00003716 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003717 }
Mike Stump11289f42009-09-09 15:08:12 +00003718
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003719 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3720}
3721
Jay Foad39c79802011-01-12 09:06:06 +00003722QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003723 if (BlockDescriptorType)
3724 return getTagDeclType(BlockDescriptorType);
3725
3726 RecordDecl *T;
3727 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003728 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003729 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003730 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003731
3732 QualType FieldTypes[] = {
3733 UnsignedLongTy,
3734 UnsignedLongTy,
3735 };
3736
3737 const char *FieldNames[] = {
3738 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003739 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003740 };
3741
3742 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003743 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003744 SourceLocation(),
3745 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003746 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003747 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003748 /*Mutable=*/false,
3749 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003750 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003751 T->addDecl(Field);
3752 }
3753
Douglas Gregord5058122010-02-11 01:19:42 +00003754 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003755
3756 BlockDescriptorType = T;
3757
3758 return getTagDeclType(BlockDescriptorType);
3759}
3760
3761void ASTContext::setBlockDescriptorType(QualType T) {
3762 const RecordType *Rec = T->getAs<RecordType>();
3763 assert(Rec && "Invalid BlockDescriptorType");
3764 BlockDescriptorType = Rec->getDecl();
3765}
3766
Jay Foad39c79802011-01-12 09:06:06 +00003767QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003768 if (BlockDescriptorExtendedType)
3769 return getTagDeclType(BlockDescriptorExtendedType);
3770
3771 RecordDecl *T;
3772 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003773 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003774 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003775 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003776
3777 QualType FieldTypes[] = {
3778 UnsignedLongTy,
3779 UnsignedLongTy,
3780 getPointerType(VoidPtrTy),
3781 getPointerType(VoidPtrTy)
3782 };
3783
3784 const char *FieldNames[] = {
3785 "reserved",
3786 "Size",
3787 "CopyFuncPtr",
3788 "DestroyFuncPtr"
3789 };
3790
3791 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003792 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003793 SourceLocation(),
3794 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003795 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003796 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003797 /*Mutable=*/false,
3798 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003799 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003800 T->addDecl(Field);
3801 }
3802
Douglas Gregord5058122010-02-11 01:19:42 +00003803 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003804
3805 BlockDescriptorExtendedType = T;
3806
3807 return getTagDeclType(BlockDescriptorExtendedType);
3808}
3809
3810void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3811 const RecordType *Rec = T->getAs<RecordType>();
3812 assert(Rec && "Invalid BlockDescriptorType");
3813 BlockDescriptorExtendedType = Rec->getDecl();
3814}
3815
Jay Foad39c79802011-01-12 09:06:06 +00003816bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003817 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003818 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003819 if (getLangOptions().CPlusPlus) {
3820 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3821 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003822 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003823
3824 }
3825 }
Mike Stump94967902009-10-21 18:16:27 +00003826 return false;
3827}
3828
Jay Foad39c79802011-01-12 09:06:06 +00003829QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003830ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003831 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003832 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003833 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003834 // unsigned int __flags;
3835 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003836 // void *__copy_helper; // as needed
3837 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003838 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003839 // } *
3840
Mike Stump94967902009-10-21 18:16:27 +00003841 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3842
3843 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003844 llvm::SmallString<36> Name;
3845 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3846 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003847 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003848 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003849 T->startDefinition();
3850 QualType Int32Ty = IntTy;
3851 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3852 QualType FieldTypes[] = {
3853 getPointerType(VoidPtrTy),
3854 getPointerType(getTagDeclType(T)),
3855 Int32Ty,
3856 Int32Ty,
3857 getPointerType(VoidPtrTy),
3858 getPointerType(VoidPtrTy),
3859 Ty
3860 };
3861
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003862 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003863 "__isa",
3864 "__forwarding",
3865 "__flags",
3866 "__size",
3867 "__copy_helper",
3868 "__destroy_helper",
3869 DeclName,
3870 };
3871
3872 for (size_t i = 0; i < 7; ++i) {
3873 if (!HasCopyAndDispose && i >=4 && i <= 5)
3874 continue;
3875 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003876 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003877 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003878 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003879 /*BitWidth=*/0, /*Mutable=*/false,
3880 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003881 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003882 T->addDecl(Field);
3883 }
3884
Douglas Gregord5058122010-02-11 01:19:42 +00003885 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003886
3887 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003888}
3889
Douglas Gregor512b0772009-04-23 22:29:11 +00003890void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003891 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003892 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3893 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3894}
3895
Anders Carlsson18acd442007-10-29 06:33:42 +00003896// This returns true if a type has been typedefed to BOOL:
3897// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003898static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003899 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003900 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3901 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003902
Anders Carlssond8499822007-10-29 05:01:08 +00003903 return false;
3904}
3905
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003906/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003907/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003908CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00003909 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3910 return CharUnits::Zero();
3911
Ken Dyck40775002010-01-11 17:06:35 +00003912 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003913
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003914 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003915 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003916 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003917 // Treat arrays as pointers, since that's how they're passed in.
3918 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003919 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003920 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003921}
3922
3923static inline
3924std::string charUnitsToString(const CharUnits &CU) {
3925 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003926}
3927
John McCall351762c2011-02-07 10:33:21 +00003928/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003929/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003930std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3931 std::string S;
3932
David Chisnall950a9512009-11-17 19:33:30 +00003933 const BlockDecl *Decl = Expr->getBlockDecl();
3934 QualType BlockTy =
3935 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3936 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003937 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003938 // Compute size of all parameters.
3939 // Start with computing size of a pointer in number of bytes.
3940 // FIXME: There might(should) be a better way of doing this computation!
3941 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003942 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3943 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003944 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003945 E = Decl->param_end(); PI != E; ++PI) {
3946 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003947 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003948 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003949 ParmOffset += sz;
3950 }
3951 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003952 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003953 // Block pointer and offset.
3954 S += "@?0";
3955 ParmOffset = PtrSize;
3956
3957 // Argument types.
3958 ParmOffset = PtrSize;
3959 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3960 Decl->param_end(); PI != E; ++PI) {
3961 ParmVarDecl *PVDecl = *PI;
3962 QualType PType = PVDecl->getOriginalType();
3963 if (const ArrayType *AT =
3964 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3965 // Use array's original type only if it has known number of
3966 // elements.
3967 if (!isa<ConstantArrayType>(AT))
3968 PType = PVDecl->getType();
3969 } else if (PType->isFunctionType())
3970 PType = PVDecl->getType();
3971 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003972 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003973 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003974 }
John McCall351762c2011-02-07 10:33:21 +00003975
3976 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003977}
3978
Douglas Gregora9d84932011-05-27 01:19:52 +00003979bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00003980 std::string& S) {
3981 // Encode result type.
3982 getObjCEncodingForType(Decl->getResultType(), S);
3983 CharUnits ParmOffset;
3984 // Compute size of all parameters.
3985 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3986 E = Decl->param_end(); PI != E; ++PI) {
3987 QualType PType = (*PI)->getType();
3988 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00003989 if (sz.isZero())
3990 return true;
3991
David Chisnall50e4eba2010-12-30 14:05:53 +00003992 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00003993 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00003994 ParmOffset += sz;
3995 }
3996 S += charUnitsToString(ParmOffset);
3997 ParmOffset = CharUnits::Zero();
3998
3999 // Argument types.
4000 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4001 E = Decl->param_end(); PI != E; ++PI) {
4002 ParmVarDecl *PVDecl = *PI;
4003 QualType PType = PVDecl->getOriginalType();
4004 if (const ArrayType *AT =
4005 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4006 // Use array's original type only if it has known number of
4007 // elements.
4008 if (!isa<ConstantArrayType>(AT))
4009 PType = PVDecl->getType();
4010 } else if (PType->isFunctionType())
4011 PType = PVDecl->getType();
4012 getObjCEncodingForType(PType, S);
4013 S += charUnitsToString(ParmOffset);
4014 ParmOffset += getObjCEncodingTypeSize(PType);
4015 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004016
4017 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004018}
4019
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004020/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004021/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004022bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00004023 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004024 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004025 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004026 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004027 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004028 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004029 // Compute size of all parameters.
4030 // Start with computing size of a pointer in number of bytes.
4031 // FIXME: There might(should) be a better way of doing this computation!
4032 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004033 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004034 // The first two arguments (self and _cmd) are pointers; account for
4035 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004036 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00004037 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004038 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004039 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004040 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004041 if (sz.isZero())
4042 return true;
4043
Ken Dyck40775002010-01-11 17:06:35 +00004044 assert (sz.isPositive() &&
4045 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004046 ParmOffset += sz;
4047 }
Ken Dyck40775002010-01-11 17:06:35 +00004048 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004049 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004050 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004051
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004052 // Argument types.
4053 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00004054 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004055 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004056 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004057 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004058 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004059 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4060 // Use array's original type only if it has known number of
4061 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004062 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004063 PType = PVDecl->getType();
4064 } else if (PType->isFunctionType())
4065 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004066 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004067 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004068 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004069 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004070 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004071 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004072 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004073
4074 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004075}
4076
Daniel Dunbar4932b362008-08-28 04:38:10 +00004077/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004078/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004079/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4080/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004081/// Property attributes are stored as a comma-delimited C string. The simple
4082/// attributes readonly and bycopy are encoded as single characters. The
4083/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4084/// encoded as single characters, followed by an identifier. Property types
4085/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004086/// these attributes are defined by the following enumeration:
4087/// @code
4088/// enum PropertyAttributes {
4089/// kPropertyReadOnly = 'R', // property is read-only.
4090/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4091/// kPropertyByref = '&', // property is a reference to the value last assigned
4092/// kPropertyDynamic = 'D', // property is dynamic
4093/// kPropertyGetter = 'G', // followed by getter selector name
4094/// kPropertySetter = 'S', // followed by setter selector name
4095/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4096/// kPropertyType = 't' // followed by old-style type encoding.
4097/// kPropertyWeak = 'W' // 'weak' property
4098/// kPropertyStrong = 'P' // property GC'able
4099/// kPropertyNonAtomic = 'N' // property non-atomic
4100/// };
4101/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004102void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004103 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004104 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004105 // Collect information from the property implementation decl(s).
4106 bool Dynamic = false;
4107 ObjCPropertyImplDecl *SynthesizePID = 0;
4108
4109 // FIXME: Duplicated code due to poor abstraction.
4110 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004111 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004112 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4113 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004114 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004115 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004116 ObjCPropertyImplDecl *PID = *i;
4117 if (PID->getPropertyDecl() == PD) {
4118 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4119 Dynamic = true;
4120 } else {
4121 SynthesizePID = PID;
4122 }
4123 }
4124 }
4125 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004126 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004127 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004128 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004129 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004130 ObjCPropertyImplDecl *PID = *i;
4131 if (PID->getPropertyDecl() == PD) {
4132 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4133 Dynamic = true;
4134 } else {
4135 SynthesizePID = PID;
4136 }
4137 }
Mike Stump11289f42009-09-09 15:08:12 +00004138 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004139 }
4140 }
4141
4142 // FIXME: This is not very efficient.
4143 S = "T";
4144
4145 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004146 // GCC has some special rules regarding encoding of properties which
4147 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004148 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004149 true /* outermost type */,
4150 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004151
4152 if (PD->isReadOnly()) {
4153 S += ",R";
4154 } else {
4155 switch (PD->getSetterKind()) {
4156 case ObjCPropertyDecl::Assign: break;
4157 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004158 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004159 }
4160 }
4161
4162 // It really isn't clear at all what this means, since properties
4163 // are "dynamic by default".
4164 if (Dynamic)
4165 S += ",D";
4166
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004167 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4168 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004169
Daniel Dunbar4932b362008-08-28 04:38:10 +00004170 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4171 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004172 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004173 }
4174
4175 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4176 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004177 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004178 }
4179
4180 if (SynthesizePID) {
4181 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4182 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004183 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004184 }
4185
4186 // FIXME: OBJCGC: weak & strong
4187}
4188
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004189/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004190/// Another legacy compatibility encoding: 32-bit longs are encoded as
4191/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004192/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4193///
4194void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004195 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004196 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004197 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004198 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004199 else
Jay Foad39c79802011-01-12 09:06:06 +00004200 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004201 PointeeTy = IntTy;
4202 }
4203 }
4204}
4205
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004206void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004207 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004208 // We follow the behavior of gcc, expanding structures which are
4209 // directly pointed to, and expanding embedded structures. Note that
4210 // these rules are sufficient to prevent recursive encoding of the
4211 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004212 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004213 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004214}
4215
David Chisnallb190a2c2010-06-04 01:10:52 +00004216static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4217 switch (T->getAs<BuiltinType>()->getKind()) {
4218 default: assert(0 && "Unhandled builtin type kind");
4219 case BuiltinType::Void: return 'v';
4220 case BuiltinType::Bool: return 'B';
4221 case BuiltinType::Char_U:
4222 case BuiltinType::UChar: return 'C';
4223 case BuiltinType::UShort: return 'S';
4224 case BuiltinType::UInt: return 'I';
4225 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004226 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004227 case BuiltinType::UInt128: return 'T';
4228 case BuiltinType::ULongLong: return 'Q';
4229 case BuiltinType::Char_S:
4230 case BuiltinType::SChar: return 'c';
4231 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004232 case BuiltinType::WChar_S:
4233 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004234 case BuiltinType::Int: return 'i';
4235 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004236 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004237 case BuiltinType::LongLong: return 'q';
4238 case BuiltinType::Int128: return 't';
4239 case BuiltinType::Float: return 'f';
4240 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004241 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004242 }
4243}
4244
Jay Foad39c79802011-01-12 09:06:06 +00004245static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004246 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004247 const Expr *E = FD->getBitWidth();
4248 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004249 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004250 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4251 // The GNU runtime requires more information; bitfields are encoded as b,
4252 // then the offset (in bits) of the first element, then the type of the
4253 // bitfield, then the size in bits. For example, in this structure:
4254 //
4255 // struct
4256 // {
4257 // int integer;
4258 // int flags:2;
4259 // };
4260 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4261 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4262 // information is not especially sensible, but we're stuck with it for
4263 // compatibility with GCC, although providing it breaks anything that
4264 // actually uses runtime introspection and wants to work on both runtimes...
4265 if (!Ctx->getLangOptions().NeXTRuntime) {
4266 const RecordDecl *RD = FD->getParent();
4267 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004268 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004269 if (T->isEnumeralType())
4270 S += 'i';
4271 else
Jay Foad39c79802011-01-12 09:06:06 +00004272 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004273 }
4274 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004275 S += llvm::utostr(N);
4276}
4277
Daniel Dunbar07d07852009-10-18 21:17:35 +00004278// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004279void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4280 bool ExpandPointedToStructures,
4281 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004282 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004283 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004284 bool EncodingProperty,
4285 bool StructField) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004286 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004287 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004288 return EncodeBitField(this, S, T, FD);
4289 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004290 return;
4291 }
Mike Stump11289f42009-09-09 15:08:12 +00004292
John McCall9dd450b2009-09-21 23:43:11 +00004293 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004294 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004295 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004296 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004297 return;
4298 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004299
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004300 // encoding for pointer or r3eference types.
4301 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004302 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004303 if (PT->isObjCSelType()) {
4304 S += ':';
4305 return;
4306 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004307 PointeeTy = PT->getPointeeType();
4308 }
4309 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4310 PointeeTy = RT->getPointeeType();
4311 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004312 bool isReadOnly = false;
4313 // For historical/compatibility reasons, the read-only qualifier of the
4314 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4315 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004316 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004317 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004318 if (OutermostType && T.isConstQualified()) {
4319 isReadOnly = true;
4320 S += 'r';
4321 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004322 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004323 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004324 while (P->getAs<PointerType>())
4325 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004326 if (P.isConstQualified()) {
4327 isReadOnly = true;
4328 S += 'r';
4329 }
4330 }
4331 if (isReadOnly) {
4332 // Another legacy compatibility encoding. Some ObjC qualifier and type
4333 // combinations need to be rearranged.
4334 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004335 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004336 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004337 }
Mike Stump11289f42009-09-09 15:08:12 +00004338
Anders Carlssond8499822007-10-29 05:01:08 +00004339 if (PointeeTy->isCharType()) {
4340 // char pointer types should be encoded as '*' unless it is a
4341 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004342 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004343 S += '*';
4344 return;
4345 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004346 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004347 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4348 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4349 S += '#';
4350 return;
4351 }
4352 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4353 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4354 S += '@';
4355 return;
4356 }
4357 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004358 }
Anders Carlssond8499822007-10-29 05:01:08 +00004359 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004360 getLegacyIntegralTypeEncoding(PointeeTy);
4361
Mike Stump11289f42009-09-09 15:08:12 +00004362 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004363 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004364 return;
4365 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004366
Chris Lattnere7cabb92009-07-13 00:10:46 +00004367 if (const ArrayType *AT =
4368 // Ignore type qualifiers etc.
4369 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004370 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004371 // Incomplete arrays are encoded as a pointer to the array element.
4372 S += '^';
4373
Mike Stump11289f42009-09-09 15:08:12 +00004374 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004375 false, ExpandStructures, FD);
4376 } else {
4377 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004378
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004379 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4380 if (getTypeSize(CAT->getElementType()) == 0)
4381 S += '0';
4382 else
4383 S += llvm::utostr(CAT->getSize().getZExtValue());
4384 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004385 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004386 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4387 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004388 S += '0';
4389 }
Mike Stump11289f42009-09-09 15:08:12 +00004390
4391 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004392 false, ExpandStructures, FD);
4393 S += ']';
4394 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004395 return;
4396 }
Mike Stump11289f42009-09-09 15:08:12 +00004397
John McCall9dd450b2009-09-21 23:43:11 +00004398 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004399 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004400 return;
4401 }
Mike Stump11289f42009-09-09 15:08:12 +00004402
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004403 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004404 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004405 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004406 // Anonymous structures print as '?'
4407 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4408 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004409 if (ClassTemplateSpecializationDecl *Spec
4410 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4411 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4412 std::string TemplateArgsStr
4413 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004414 TemplateArgs.data(),
4415 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004416 (*this).PrintingPolicy);
4417
4418 S += TemplateArgsStr;
4419 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004420 } else {
4421 S += '?';
4422 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004423 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004424 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004425 if (!RDecl->isUnion()) {
4426 getObjCEncodingForStructureImpl(RDecl, S, FD);
4427 } else {
4428 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4429 FieldEnd = RDecl->field_end();
4430 Field != FieldEnd; ++Field) {
4431 if (FD) {
4432 S += '"';
4433 S += Field->getNameAsString();
4434 S += '"';
4435 }
Mike Stump11289f42009-09-09 15:08:12 +00004436
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004437 // Special case bit-fields.
4438 if (Field->isBitField()) {
4439 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4440 (*Field));
4441 } else {
4442 QualType qt = Field->getType();
4443 getLegacyIntegralTypeEncoding(qt);
4444 getObjCEncodingForTypeImpl(qt, S, false, true,
4445 FD, /*OutermostType*/false,
4446 /*EncodingProperty*/false,
4447 /*StructField*/true);
4448 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004449 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004450 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004451 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004452 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004453 return;
4454 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004455
Chris Lattnere7cabb92009-07-13 00:10:46 +00004456 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004457 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004458 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004459 else
4460 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004461 return;
4462 }
Mike Stump11289f42009-09-09 15:08:12 +00004463
Chris Lattnere7cabb92009-07-13 00:10:46 +00004464 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004465 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004466 return;
4467 }
Mike Stump11289f42009-09-09 15:08:12 +00004468
John McCall8b07ec22010-05-15 11:32:37 +00004469 // Ignore protocol qualifiers when mangling at this level.
4470 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4471 T = OT->getBaseType();
4472
John McCall8ccfcb52009-09-24 19:53:00 +00004473 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004474 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004475 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004476 S += '{';
4477 const IdentifierInfo *II = OI->getIdentifier();
4478 S += II->getName();
4479 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004480 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004481 DeepCollectObjCIvars(OI, true, Ivars);
4482 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004483 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004484 if (Field->isBitField())
4485 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004486 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004487 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004488 }
4489 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004490 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004491 }
Mike Stump11289f42009-09-09 15:08:12 +00004492
John McCall9dd450b2009-09-21 23:43:11 +00004493 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004494 if (OPT->isObjCIdType()) {
4495 S += '@';
4496 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004497 }
Mike Stump11289f42009-09-09 15:08:12 +00004498
Steve Narofff0c86112009-10-28 22:03:49 +00004499 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4500 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4501 // Since this is a binary compatibility issue, need to consult with runtime
4502 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004503 S += '#';
4504 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004505 }
Mike Stump11289f42009-09-09 15:08:12 +00004506
Chris Lattnere7cabb92009-07-13 00:10:46 +00004507 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004508 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004509 ExpandPointedToStructures,
4510 ExpandStructures, FD);
4511 if (FD || EncodingProperty) {
4512 // Note that we do extended encoding of protocol qualifer list
4513 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004514 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004515 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4516 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004517 S += '<';
4518 S += (*I)->getNameAsString();
4519 S += '>';
4520 }
4521 S += '"';
4522 }
4523 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004524 }
Mike Stump11289f42009-09-09 15:08:12 +00004525
Chris Lattnere7cabb92009-07-13 00:10:46 +00004526 QualType PointeeTy = OPT->getPointeeType();
4527 if (!EncodingProperty &&
4528 isa<TypedefType>(PointeeTy.getTypePtr())) {
4529 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004530 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004531 // {...};
4532 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004533 getObjCEncodingForTypeImpl(PointeeTy, S,
4534 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004535 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004536 return;
4537 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004538
4539 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004540 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004541 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004542 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004543 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4544 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004545 S += '<';
4546 S += (*I)->getNameAsString();
4547 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004548 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004549 S += '"';
4550 }
4551 return;
4552 }
Mike Stump11289f42009-09-09 15:08:12 +00004553
John McCalla9e6e8d2010-05-17 23:56:34 +00004554 // gcc just blithely ignores member pointers.
4555 // TODO: maybe there should be a mangling for these
4556 if (T->getAs<MemberPointerType>())
4557 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004558
4559 if (T->isVectorType()) {
4560 // This matches gcc's encoding, even though technically it is
4561 // insufficient.
4562 // FIXME. We should do a better job than gcc.
4563 return;
4564 }
4565
Chris Lattnere7cabb92009-07-13 00:10:46 +00004566 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004567}
4568
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004569void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4570 std::string &S,
4571 const FieldDecl *FD,
4572 bool includeVBases) const {
4573 assert(RDecl && "Expected non-null RecordDecl");
4574 assert(!RDecl->isUnion() && "Should not be called for unions");
4575 if (!RDecl->getDefinition())
4576 return;
4577
4578 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4579 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4580 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4581
4582 if (CXXRec) {
4583 for (CXXRecordDecl::base_class_iterator
4584 BI = CXXRec->bases_begin(),
4585 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4586 if (!BI->isVirtual()) {
4587 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004588 if (base->isEmpty())
4589 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004590 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4591 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4592 std::make_pair(offs, base));
4593 }
4594 }
4595 }
4596
4597 unsigned i = 0;
4598 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4599 FieldEnd = RDecl->field_end();
4600 Field != FieldEnd; ++Field, ++i) {
4601 uint64_t offs = layout.getFieldOffset(i);
4602 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4603 std::make_pair(offs, *Field));
4604 }
4605
4606 if (CXXRec && includeVBases) {
4607 for (CXXRecordDecl::base_class_iterator
4608 BI = CXXRec->vbases_begin(),
4609 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4610 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004611 if (base->isEmpty())
4612 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004613 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4614 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4615 std::make_pair(offs, base));
4616 }
4617 }
4618
4619 CharUnits size;
4620 if (CXXRec) {
4621 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4622 } else {
4623 size = layout.getSize();
4624 }
4625
4626 uint64_t CurOffs = 0;
4627 std::multimap<uint64_t, NamedDecl *>::iterator
4628 CurLayObj = FieldOrBaseOffsets.begin();
4629
4630 if (CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) {
4631 assert(CXXRec && CXXRec->isDynamicClass() &&
4632 "Offset 0 was empty but no VTable ?");
4633 if (FD) {
4634 S += "\"_vptr$";
4635 std::string recname = CXXRec->getNameAsString();
4636 if (recname.empty()) recname = "?";
4637 S += recname;
4638 S += '"';
4639 }
4640 S += "^^?";
4641 CurOffs += getTypeSize(VoidPtrTy);
4642 }
4643
4644 if (!RDecl->hasFlexibleArrayMember()) {
4645 // Mark the end of the structure.
4646 uint64_t offs = toBits(size);
4647 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4648 std::make_pair(offs, (NamedDecl*)0));
4649 }
4650
4651 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4652 assert(CurOffs <= CurLayObj->first);
4653
4654 if (CurOffs < CurLayObj->first) {
4655 uint64_t padding = CurLayObj->first - CurOffs;
4656 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4657 // packing/alignment of members is different that normal, in which case
4658 // the encoding will be out-of-sync with the real layout.
4659 // If the runtime switches to just consider the size of types without
4660 // taking into account alignment, we could make padding explicit in the
4661 // encoding (e.g. using arrays of chars). The encoding strings would be
4662 // longer then though.
4663 CurOffs += padding;
4664 }
4665
4666 NamedDecl *dcl = CurLayObj->second;
4667 if (dcl == 0)
4668 break; // reached end of structure.
4669
4670 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4671 // We expand the bases without their virtual bases since those are going
4672 // in the initial structure. Note that this differs from gcc which
4673 // expands virtual bases each time one is encountered in the hierarchy,
4674 // making the encoding type bigger than it really is.
4675 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004676 assert(!base->isEmpty());
4677 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004678 } else {
4679 FieldDecl *field = cast<FieldDecl>(dcl);
4680 if (FD) {
4681 S += '"';
4682 S += field->getNameAsString();
4683 S += '"';
4684 }
4685
4686 if (field->isBitField()) {
4687 EncodeBitField(this, S, field->getType(), field);
4688 CurOffs += field->getBitWidth()->EvaluateAsInt(*this).getZExtValue();
4689 } else {
4690 QualType qt = field->getType();
4691 getLegacyIntegralTypeEncoding(qt);
4692 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4693 /*OutermostType*/false,
4694 /*EncodingProperty*/false,
4695 /*StructField*/true);
4696 CurOffs += getTypeSize(field->getType());
4697 }
4698 }
4699 }
4700}
4701
Mike Stump11289f42009-09-09 15:08:12 +00004702void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004703 std::string& S) const {
4704 if (QT & Decl::OBJC_TQ_In)
4705 S += 'n';
4706 if (QT & Decl::OBJC_TQ_Inout)
4707 S += 'N';
4708 if (QT & Decl::OBJC_TQ_Out)
4709 S += 'o';
4710 if (QT & Decl::OBJC_TQ_Bycopy)
4711 S += 'O';
4712 if (QT & Decl::OBJC_TQ_Byref)
4713 S += 'R';
4714 if (QT & Decl::OBJC_TQ_Oneway)
4715 S += 'V';
4716}
4717
Chris Lattnere7cabb92009-07-13 00:10:46 +00004718void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004719 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004720
Anders Carlsson87c149b2007-10-11 01:00:40 +00004721 BuiltinVaListType = T;
4722}
4723
Chris Lattnere7cabb92009-07-13 00:10:46 +00004724void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004725 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004726}
4727
Chris Lattnere7cabb92009-07-13 00:10:46 +00004728void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004729 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004730}
4731
Chris Lattnere7cabb92009-07-13 00:10:46 +00004732void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004733 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004734}
4735
Chris Lattnere7cabb92009-07-13 00:10:46 +00004736void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004737 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004738}
4739
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004740void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004741 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004742 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004743
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004744 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004745}
4746
John McCalld28ae272009-12-02 08:04:21 +00004747/// \brief Retrieve the template name that corresponds to a non-empty
4748/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004749TemplateName
4750ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4751 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004752 unsigned size = End - Begin;
4753 assert(size > 1 && "set is not overloaded!");
4754
4755 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4756 size * sizeof(FunctionTemplateDecl*));
4757 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4758
4759 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004760 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004761 NamedDecl *D = *I;
4762 assert(isa<FunctionTemplateDecl>(D) ||
4763 (isa<UsingShadowDecl>(D) &&
4764 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4765 *Storage++ = D;
4766 }
4767
4768 return TemplateName(OT);
4769}
4770
Douglas Gregordc572a32009-03-30 22:58:21 +00004771/// \brief Retrieve the template name that represents a qualified
4772/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004773TemplateName
4774ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4775 bool TemplateKeyword,
4776 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004777 assert(NNS && "Missing nested-name-specifier in qualified template name");
4778
Douglas Gregorc42075a2010-02-04 18:10:26 +00004779 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004780 llvm::FoldingSetNodeID ID;
4781 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4782
4783 void *InsertPos = 0;
4784 QualifiedTemplateName *QTN =
4785 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4786 if (!QTN) {
4787 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4788 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4789 }
4790
4791 return TemplateName(QTN);
4792}
4793
4794/// \brief Retrieve the template name that represents a dependent
4795/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004796TemplateName
4797ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4798 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004799 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004800 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004801
4802 llvm::FoldingSetNodeID ID;
4803 DependentTemplateName::Profile(ID, NNS, Name);
4804
4805 void *InsertPos = 0;
4806 DependentTemplateName *QTN =
4807 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4808
4809 if (QTN)
4810 return TemplateName(QTN);
4811
4812 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4813 if (CanonNNS == NNS) {
4814 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4815 } else {
4816 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4817 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004818 DependentTemplateName *CheckQTN =
4819 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4820 assert(!CheckQTN && "Dependent type name canonicalization broken");
4821 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004822 }
4823
4824 DependentTemplateNames.InsertNode(QTN, InsertPos);
4825 return TemplateName(QTN);
4826}
4827
Douglas Gregor71395fa2009-11-04 00:56:37 +00004828/// \brief Retrieve the template name that represents a dependent
4829/// template name such as \c MetaFun::template operator+.
4830TemplateName
4831ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004832 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004833 assert((!NNS || NNS->isDependent()) &&
4834 "Nested name specifier must be dependent");
4835
4836 llvm::FoldingSetNodeID ID;
4837 DependentTemplateName::Profile(ID, NNS, Operator);
4838
4839 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004840 DependentTemplateName *QTN
4841 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004842
4843 if (QTN)
4844 return TemplateName(QTN);
4845
4846 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4847 if (CanonNNS == NNS) {
4848 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4849 } else {
4850 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4851 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004852
4853 DependentTemplateName *CheckQTN
4854 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4855 assert(!CheckQTN && "Dependent template name canonicalization broken");
4856 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004857 }
4858
4859 DependentTemplateNames.InsertNode(QTN, InsertPos);
4860 return TemplateName(QTN);
4861}
4862
Douglas Gregor5590be02011-01-15 06:45:20 +00004863TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00004864ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4865 TemplateName replacement) const {
4866 llvm::FoldingSetNodeID ID;
4867 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4868
4869 void *insertPos = 0;
4870 SubstTemplateTemplateParmStorage *subst
4871 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4872
4873 if (!subst) {
4874 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4875 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4876 }
4877
4878 return TemplateName(subst);
4879}
4880
4881TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00004882ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4883 const TemplateArgument &ArgPack) const {
4884 ASTContext &Self = const_cast<ASTContext &>(*this);
4885 llvm::FoldingSetNodeID ID;
4886 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4887
4888 void *InsertPos = 0;
4889 SubstTemplateTemplateParmPackStorage *Subst
4890 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4891
4892 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00004893 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00004894 ArgPack.pack_size(),
4895 ArgPack.pack_begin());
4896 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4897 }
4898
4899 return TemplateName(Subst);
4900}
4901
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004902/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004903/// TargetInfo, produce the corresponding type. The unsigned @p Type
4904/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004905CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004906 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004907 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004908 case TargetInfo::SignedShort: return ShortTy;
4909 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4910 case TargetInfo::SignedInt: return IntTy;
4911 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4912 case TargetInfo::SignedLong: return LongTy;
4913 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4914 case TargetInfo::SignedLongLong: return LongLongTy;
4915 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4916 }
4917
4918 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004919 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004920}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004921
4922//===----------------------------------------------------------------------===//
4923// Type Predicates.
4924//===----------------------------------------------------------------------===//
4925
Fariborz Jahanian96207692009-02-18 21:49:28 +00004926/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4927/// garbage collection attribute.
4928///
John McCall553d45a2011-01-12 00:34:59 +00004929Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4930 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4931 return Qualifiers::GCNone;
4932
4933 assert(getLangOptions().ObjC1);
4934 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4935
4936 // Default behaviour under objective-C's gc is for ObjC pointers
4937 // (or pointers to them) be treated as though they were declared
4938 // as __strong.
4939 if (GCAttrs == Qualifiers::GCNone) {
4940 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4941 return Qualifiers::Strong;
4942 else if (Ty->isPointerType())
4943 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4944 } else {
4945 // It's not valid to set GC attributes on anything that isn't a
4946 // pointer.
4947#ifndef NDEBUG
4948 QualType CT = Ty->getCanonicalTypeInternal();
4949 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4950 CT = AT->getElementType();
4951 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4952#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004953 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004954 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004955}
4956
Chris Lattner49af6a42008-04-07 06:51:04 +00004957//===----------------------------------------------------------------------===//
4958// Type Compatibility Testing
4959//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004960
Mike Stump11289f42009-09-09 15:08:12 +00004961/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004962/// compatible.
4963static bool areCompatVectorTypes(const VectorType *LHS,
4964 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004965 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004966 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004967 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004968}
4969
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004970bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4971 QualType SecondVec) {
4972 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4973 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4974
4975 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4976 return true;
4977
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004978 // Treat Neon vector types and most AltiVec vector types as if they are the
4979 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004980 const VectorType *First = FirstVec->getAs<VectorType>();
4981 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004982 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004983 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004984 First->getVectorKind() != VectorType::AltiVecPixel &&
4985 First->getVectorKind() != VectorType::AltiVecBool &&
4986 Second->getVectorKind() != VectorType::AltiVecPixel &&
4987 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004988 return true;
4989
4990 return false;
4991}
4992
Steve Naroff8e6aee52009-07-23 01:01:38 +00004993//===----------------------------------------------------------------------===//
4994// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4995//===----------------------------------------------------------------------===//
4996
4997/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4998/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004999bool
5000ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5001 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005002 if (lProto == rProto)
5003 return true;
5004 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5005 E = rProto->protocol_end(); PI != E; ++PI)
5006 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5007 return true;
5008 return false;
5009}
5010
Steve Naroff8e6aee52009-07-23 01:01:38 +00005011/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5012/// return true if lhs's protocols conform to rhs's protocol; false
5013/// otherwise.
5014bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5015 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5016 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5017 return false;
5018}
5019
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005020/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5021/// Class<p1, ...>.
5022bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5023 QualType rhs) {
5024 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5025 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5026 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5027
5028 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5029 E = lhsQID->qual_end(); I != E; ++I) {
5030 bool match = false;
5031 ObjCProtocolDecl *lhsProto = *I;
5032 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5033 E = rhsOPT->qual_end(); J != E; ++J) {
5034 ObjCProtocolDecl *rhsProto = *J;
5035 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5036 match = true;
5037 break;
5038 }
5039 }
5040 if (!match)
5041 return false;
5042 }
5043 return true;
5044}
5045
Steve Naroff8e6aee52009-07-23 01:01:38 +00005046/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5047/// ObjCQualifiedIDType.
5048bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5049 bool compare) {
5050 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005051 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005052 lhs->isObjCIdType() || lhs->isObjCClassType())
5053 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005054 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005055 rhs->isObjCIdType() || rhs->isObjCClassType())
5056 return true;
5057
5058 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005059 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005060
Steve Naroff8e6aee52009-07-23 01:01:38 +00005061 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005062
Steve Naroff8e6aee52009-07-23 01:01:38 +00005063 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005064 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005065 // make sure we check the class hierarchy.
5066 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5067 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5068 E = lhsQID->qual_end(); I != E; ++I) {
5069 // when comparing an id<P> on lhs with a static type on rhs,
5070 // see if static class implements all of id's protocols, directly or
5071 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005072 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005073 return false;
5074 }
5075 }
5076 // If there are no qualifiers and no interface, we have an 'id'.
5077 return true;
5078 }
Mike Stump11289f42009-09-09 15:08:12 +00005079 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005080 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5081 E = lhsQID->qual_end(); I != E; ++I) {
5082 ObjCProtocolDecl *lhsProto = *I;
5083 bool match = false;
5084
5085 // when comparing an id<P> on lhs with a static type on rhs,
5086 // see if static class implements all of id's protocols, directly or
5087 // through its super class and categories.
5088 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5089 E = rhsOPT->qual_end(); J != E; ++J) {
5090 ObjCProtocolDecl *rhsProto = *J;
5091 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5092 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5093 match = true;
5094 break;
5095 }
5096 }
Mike Stump11289f42009-09-09 15:08:12 +00005097 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005098 // make sure we check the class hierarchy.
5099 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5100 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5101 E = lhsQID->qual_end(); I != E; ++I) {
5102 // when comparing an id<P> on lhs with a static type on rhs,
5103 // see if static class implements all of id's protocols, directly or
5104 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005105 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005106 match = true;
5107 break;
5108 }
5109 }
5110 }
5111 if (!match)
5112 return false;
5113 }
Mike Stump11289f42009-09-09 15:08:12 +00005114
Steve Naroff8e6aee52009-07-23 01:01:38 +00005115 return true;
5116 }
Mike Stump11289f42009-09-09 15:08:12 +00005117
Steve Naroff8e6aee52009-07-23 01:01:38 +00005118 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5119 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5120
Mike Stump11289f42009-09-09 15:08:12 +00005121 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005122 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005123 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005124 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5125 E = lhsOPT->qual_end(); I != E; ++I) {
5126 ObjCProtocolDecl *lhsProto = *I;
5127 bool match = false;
5128
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005129 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005130 // see if static class implements all of id's protocols, directly or
5131 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005132 // First, lhs protocols in the qualifier list must be found, direct
5133 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005134 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5135 E = rhsQID->qual_end(); J != E; ++J) {
5136 ObjCProtocolDecl *rhsProto = *J;
5137 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5138 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5139 match = true;
5140 break;
5141 }
5142 }
5143 if (!match)
5144 return false;
5145 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005146
5147 // Static class's protocols, or its super class or category protocols
5148 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5149 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5150 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5151 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5152 // This is rather dubious but matches gcc's behavior. If lhs has
5153 // no type qualifier and its class has no static protocol(s)
5154 // assume that it is mismatch.
5155 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5156 return false;
5157 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5158 LHSInheritedProtocols.begin(),
5159 E = LHSInheritedProtocols.end(); I != E; ++I) {
5160 bool match = false;
5161 ObjCProtocolDecl *lhsProto = (*I);
5162 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5163 E = rhsQID->qual_end(); J != E; ++J) {
5164 ObjCProtocolDecl *rhsProto = *J;
5165 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5166 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5167 match = true;
5168 break;
5169 }
5170 }
5171 if (!match)
5172 return false;
5173 }
5174 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005175 return true;
5176 }
5177 return false;
5178}
5179
Eli Friedman47f77112008-08-22 00:56:42 +00005180/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005181/// compatible for assignment from RHS to LHS. This handles validation of any
5182/// protocol qualifiers on the LHS or RHS.
5183///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005184bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5185 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005186 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5187 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5188
Steve Naroff1329fa02009-07-15 18:40:39 +00005189 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005190 if (LHS->isObjCUnqualifiedIdOrClass() ||
5191 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005192 return true;
5193
John McCall8b07ec22010-05-15 11:32:37 +00005194 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005195 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5196 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005197 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005198
5199 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5200 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5201 QualType(RHSOPT,0));
5202
John McCall8b07ec22010-05-15 11:32:37 +00005203 // If we have 2 user-defined types, fall into that path.
5204 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005205 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005206
Steve Naroff8e6aee52009-07-23 01:01:38 +00005207 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005208}
5209
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005210/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005211/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005212/// arguments in block literals. When passed as arguments, passing 'A*' where
5213/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5214/// not OK. For the return type, the opposite is not OK.
5215bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5216 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005217 const ObjCObjectPointerType *RHSOPT,
5218 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005219 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005220 return true;
5221
5222 if (LHSOPT->isObjCBuiltinType()) {
5223 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5224 }
5225
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005226 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005227 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5228 QualType(RHSOPT,0),
5229 false);
5230
5231 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5232 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5233 if (LHS && RHS) { // We have 2 user-defined types.
5234 if (LHS != RHS) {
5235 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005236 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005237 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005238 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005239 }
5240 else
5241 return true;
5242 }
5243 return false;
5244}
5245
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005246/// getIntersectionOfProtocols - This routine finds the intersection of set
5247/// of protocols inherited from two distinct objective-c pointer objects.
5248/// It is used to build composite qualifier list of the composite type of
5249/// the conditional expression involving two objective-c pointer objects.
5250static
5251void getIntersectionOfProtocols(ASTContext &Context,
5252 const ObjCObjectPointerType *LHSOPT,
5253 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005254 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005255
John McCall8b07ec22010-05-15 11:32:37 +00005256 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5257 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5258 assert(LHS->getInterface() && "LHS must have an interface base");
5259 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005260
5261 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5262 unsigned LHSNumProtocols = LHS->getNumProtocols();
5263 if (LHSNumProtocols > 0)
5264 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5265 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005266 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005267 Context.CollectInheritedProtocols(LHS->getInterface(),
5268 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005269 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5270 LHSInheritedProtocols.end());
5271 }
5272
5273 unsigned RHSNumProtocols = RHS->getNumProtocols();
5274 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005275 ObjCProtocolDecl **RHSProtocols =
5276 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005277 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5278 if (InheritedProtocolSet.count(RHSProtocols[i]))
5279 IntersectionOfProtocols.push_back(RHSProtocols[i]);
5280 }
5281 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005282 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005283 Context.CollectInheritedProtocols(RHS->getInterface(),
5284 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005285 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5286 RHSInheritedProtocols.begin(),
5287 E = RHSInheritedProtocols.end(); I != E; ++I)
5288 if (InheritedProtocolSet.count((*I)))
5289 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005290 }
5291}
5292
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005293/// areCommonBaseCompatible - Returns common base class of the two classes if
5294/// one found. Note that this is O'2 algorithm. But it will be called as the
5295/// last type comparison in a ?-exp of ObjC pointer types before a
5296/// warning is issued. So, its invokation is extremely rare.
5297QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005298 const ObjCObjectPointerType *Lptr,
5299 const ObjCObjectPointerType *Rptr) {
5300 const ObjCObjectType *LHS = Lptr->getObjectType();
5301 const ObjCObjectType *RHS = Rptr->getObjectType();
5302 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5303 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005304 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005305 return QualType();
5306
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005307 do {
John McCall8b07ec22010-05-15 11:32:37 +00005308 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005309 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005310 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005311 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5312
5313 QualType Result = QualType(LHS, 0);
5314 if (!Protocols.empty())
5315 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5316 Result = getObjCObjectPointerType(Result);
5317 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005318 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005319 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005320
5321 return QualType();
5322}
5323
John McCall8b07ec22010-05-15 11:32:37 +00005324bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5325 const ObjCObjectType *RHS) {
5326 assert(LHS->getInterface() && "LHS is not an interface type");
5327 assert(RHS->getInterface() && "RHS is not an interface type");
5328
Chris Lattner49af6a42008-04-07 06:51:04 +00005329 // Verify that the base decls are compatible: the RHS must be a subclass of
5330 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005331 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005332 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005333
Chris Lattner49af6a42008-04-07 06:51:04 +00005334 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5335 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005336 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005337 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005338
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005339 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5340 // more detailed analysis is required.
5341 if (RHS->getNumProtocols() == 0) {
5342 // OK, if LHS is a superclass of RHS *and*
5343 // this superclass is assignment compatible with LHS.
5344 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005345 bool IsSuperClass =
5346 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5347 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005348 // OK if conversion of LHS to SuperClass results in narrowing of types
5349 // ; i.e., SuperClass may implement at least one of the protocols
5350 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5351 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5352 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005353 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005354 // If super class has no protocols, it is not a match.
5355 if (SuperClassInheritedProtocols.empty())
5356 return false;
5357
5358 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5359 LHSPE = LHS->qual_end();
5360 LHSPI != LHSPE; LHSPI++) {
5361 bool SuperImplementsProtocol = false;
5362 ObjCProtocolDecl *LHSProto = (*LHSPI);
5363
5364 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5365 SuperClassInheritedProtocols.begin(),
5366 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5367 ObjCProtocolDecl *SuperClassProto = (*I);
5368 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5369 SuperImplementsProtocol = true;
5370 break;
5371 }
5372 }
5373 if (!SuperImplementsProtocol)
5374 return false;
5375 }
5376 return true;
5377 }
5378 return false;
5379 }
Mike Stump11289f42009-09-09 15:08:12 +00005380
John McCall8b07ec22010-05-15 11:32:37 +00005381 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5382 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005383 LHSPI != LHSPE; LHSPI++) {
5384 bool RHSImplementsProtocol = false;
5385
5386 // If the RHS doesn't implement the protocol on the left, the types
5387 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005388 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5389 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005390 RHSPI != RHSPE; RHSPI++) {
5391 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005392 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005393 break;
5394 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005395 }
5396 // FIXME: For better diagnostics, consider passing back the protocol name.
5397 if (!RHSImplementsProtocol)
5398 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005399 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005400 // The RHS implements all protocols listed on the LHS.
5401 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005402}
5403
Steve Naroffb7605152009-02-12 17:52:19 +00005404bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5405 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005406 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5407 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005408
Steve Naroff7cae42b2009-07-10 23:34:53 +00005409 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005410 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005411
5412 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5413 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005414}
5415
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005416bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5417 return canAssignObjCInterfaces(
5418 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5419 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5420}
5421
Mike Stump11289f42009-09-09 15:08:12 +00005422/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005423/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005424/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005425/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005426bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5427 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005428 if (getLangOptions().CPlusPlus)
5429 return hasSameType(LHS, RHS);
5430
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005431 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005432}
5433
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005434bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005435 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005436}
5437
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005438bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5439 return !mergeTypes(LHS, RHS, true).isNull();
5440}
5441
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005442/// mergeTransparentUnionType - if T is a transparent union type and a member
5443/// of T is compatible with SubType, return the merged type, else return
5444/// QualType()
5445QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5446 bool OfBlockPointer,
5447 bool Unqualified) {
5448 if (const RecordType *UT = T->getAsUnionType()) {
5449 RecordDecl *UD = UT->getDecl();
5450 if (UD->hasAttr<TransparentUnionAttr>()) {
5451 for (RecordDecl::field_iterator it = UD->field_begin(),
5452 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005453 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005454 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5455 if (!MT.isNull())
5456 return MT;
5457 }
5458 }
5459 }
5460
5461 return QualType();
5462}
5463
5464/// mergeFunctionArgumentTypes - merge two types which appear as function
5465/// argument types
5466QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5467 bool OfBlockPointer,
5468 bool Unqualified) {
5469 // GNU extension: two types are compatible if they appear as a function
5470 // argument, one of the types is a transparent union type and the other
5471 // type is compatible with a union member
5472 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5473 Unqualified);
5474 if (!lmerge.isNull())
5475 return lmerge;
5476
5477 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5478 Unqualified);
5479 if (!rmerge.isNull())
5480 return rmerge;
5481
5482 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5483}
5484
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005485QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005486 bool OfBlockPointer,
5487 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005488 const FunctionType *lbase = lhs->getAs<FunctionType>();
5489 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005490 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5491 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005492 bool allLTypes = true;
5493 bool allRTypes = true;
5494
5495 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005496 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005497 if (OfBlockPointer) {
5498 QualType RHS = rbase->getResultType();
5499 QualType LHS = lbase->getResultType();
5500 bool UnqualifiedResult = Unqualified;
5501 if (!UnqualifiedResult)
5502 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005503 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005504 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005505 else
John McCall8c6b56f2010-12-15 01:06:38 +00005506 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5507 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005508 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005509
5510 if (Unqualified)
5511 retType = retType.getUnqualifiedType();
5512
5513 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5514 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5515 if (Unqualified) {
5516 LRetType = LRetType.getUnqualifiedType();
5517 RRetType = RRetType.getUnqualifiedType();
5518 }
5519
5520 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005521 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005522 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005523 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005524
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005525 // FIXME: double check this
5526 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5527 // rbase->getRegParmAttr() != 0 &&
5528 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005529 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5530 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005531
Douglas Gregor8c940862010-01-18 17:14:39 +00005532 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005533 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005534 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005535
John McCall8c6b56f2010-12-15 01:06:38 +00005536 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005537 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5538 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005539 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5540 return QualType();
5541
John McCall31168b02011-06-15 23:02:42 +00005542 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5543 return QualType();
5544
John McCall8c6b56f2010-12-15 01:06:38 +00005545 // It's noreturn if either type is.
5546 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5547 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5548 if (NoReturn != lbaseInfo.getNoReturn())
5549 allLTypes = false;
5550 if (NoReturn != rbaseInfo.getNoReturn())
5551 allRTypes = false;
5552
John McCall31168b02011-06-15 23:02:42 +00005553 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005554
Eli Friedman47f77112008-08-22 00:56:42 +00005555 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005556 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5557 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005558 unsigned lproto_nargs = lproto->getNumArgs();
5559 unsigned rproto_nargs = rproto->getNumArgs();
5560
5561 // Compatible functions must have the same number of arguments
5562 if (lproto_nargs != rproto_nargs)
5563 return QualType();
5564
5565 // Variadic and non-variadic functions aren't compatible
5566 if (lproto->isVariadic() != rproto->isVariadic())
5567 return QualType();
5568
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005569 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5570 return QualType();
5571
Eli Friedman47f77112008-08-22 00:56:42 +00005572 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005573 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00005574 for (unsigned i = 0; i < lproto_nargs; i++) {
5575 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5576 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005577 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5578 OfBlockPointer,
5579 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005580 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005581
5582 if (Unqualified)
5583 argtype = argtype.getUnqualifiedType();
5584
Eli Friedman47f77112008-08-22 00:56:42 +00005585 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005586 if (Unqualified) {
5587 largtype = largtype.getUnqualifiedType();
5588 rargtype = rargtype.getUnqualifiedType();
5589 }
5590
Chris Lattner465fa322008-10-05 17:34:18 +00005591 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5592 allLTypes = false;
5593 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5594 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005595 }
5596 if (allLTypes) return lhs;
5597 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005598
5599 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5600 EPI.ExtInfo = einfo;
5601 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005602 }
5603
5604 if (lproto) allRTypes = false;
5605 if (rproto) allLTypes = false;
5606
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005607 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005608 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005609 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005610 if (proto->isVariadic()) return QualType();
5611 // Check that the types are compatible with the types that
5612 // would result from default argument promotions (C99 6.7.5.3p15).
5613 // The only types actually affected are promotable integer
5614 // types and floats, which would be passed as a different
5615 // type depending on whether the prototype is visible.
5616 unsigned proto_nargs = proto->getNumArgs();
5617 for (unsigned i = 0; i < proto_nargs; ++i) {
5618 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005619
5620 // Look at the promotion type of enum types, since that is the type used
5621 // to pass enum values.
5622 if (const EnumType *Enum = argTy->getAs<EnumType>())
5623 argTy = Enum->getDecl()->getPromotionType();
5624
Eli Friedman47f77112008-08-22 00:56:42 +00005625 if (argTy->isPromotableIntegerType() ||
5626 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5627 return QualType();
5628 }
5629
5630 if (allLTypes) return lhs;
5631 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005632
5633 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5634 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005635 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005636 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005637 }
5638
5639 if (allLTypes) return lhs;
5640 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005641 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005642}
5643
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005644QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005645 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005646 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005647 // C++ [expr]: If an expression initially has the type "reference to T", the
5648 // type is adjusted to "T" prior to any further analysis, the expression
5649 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005650 // expression is an lvalue unless the reference is an rvalue reference and
5651 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005652 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5653 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005654
5655 if (Unqualified) {
5656 LHS = LHS.getUnqualifiedType();
5657 RHS = RHS.getUnqualifiedType();
5658 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005659
Eli Friedman47f77112008-08-22 00:56:42 +00005660 QualType LHSCan = getCanonicalType(LHS),
5661 RHSCan = getCanonicalType(RHS);
5662
5663 // If two types are identical, they are compatible.
5664 if (LHSCan == RHSCan)
5665 return LHS;
5666
John McCall8ccfcb52009-09-24 19:53:00 +00005667 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005668 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5669 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005670 if (LQuals != RQuals) {
5671 // If any of these qualifiers are different, we have a type
5672 // mismatch.
5673 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005674 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5675 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005676 return QualType();
5677
5678 // Exactly one GC qualifier difference is allowed: __strong is
5679 // okay if the other type has no GC qualifier but is an Objective
5680 // C object pointer (i.e. implicitly strong by default). We fix
5681 // this by pretending that the unqualified type was actually
5682 // qualified __strong.
5683 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5684 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5685 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5686
5687 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5688 return QualType();
5689
5690 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5691 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5692 }
5693 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5694 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5695 }
Eli Friedman47f77112008-08-22 00:56:42 +00005696 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005697 }
5698
5699 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005700
Eli Friedmandcca6332009-06-01 01:22:52 +00005701 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5702 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005703
Chris Lattnerfd652912008-01-14 05:45:46 +00005704 // We want to consider the two function types to be the same for these
5705 // comparisons, just force one to the other.
5706 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5707 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005708
5709 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005710 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5711 LHSClass = Type::ConstantArray;
5712 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5713 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005714
John McCall8b07ec22010-05-15 11:32:37 +00005715 // ObjCInterfaces are just specialized ObjCObjects.
5716 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5717 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5718
Nate Begemance4d7fc2008-04-18 23:10:10 +00005719 // Canonicalize ExtVector -> Vector.
5720 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5721 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005722
Chris Lattner95554662008-04-07 05:43:21 +00005723 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005724 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005725 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005726 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005727 // Compatibility is based on the underlying type, not the promotion
5728 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005729 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005730 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5731 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005732 }
John McCall9dd450b2009-09-21 23:43:11 +00005733 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005734 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5735 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005736 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005737
Eli Friedman47f77112008-08-22 00:56:42 +00005738 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005739 }
Eli Friedman47f77112008-08-22 00:56:42 +00005740
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005741 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005742 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005743#define TYPE(Class, Base)
5744#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005745#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005746#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5747#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5748#include "clang/AST/TypeNodes.def"
5749 assert(false && "Non-canonical and dependent types shouldn't get here");
5750 return QualType();
5751
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005752 case Type::LValueReference:
5753 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005754 case Type::MemberPointer:
5755 assert(false && "C++ should never be in mergeTypes");
5756 return QualType();
5757
John McCall8b07ec22010-05-15 11:32:37 +00005758 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005759 case Type::IncompleteArray:
5760 case Type::VariableArray:
5761 case Type::FunctionProto:
5762 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005763 assert(false && "Types are eliminated above");
5764 return QualType();
5765
Chris Lattnerfd652912008-01-14 05:45:46 +00005766 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005767 {
5768 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005769 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5770 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005771 if (Unqualified) {
5772 LHSPointee = LHSPointee.getUnqualifiedType();
5773 RHSPointee = RHSPointee.getUnqualifiedType();
5774 }
5775 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5776 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005777 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005778 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005779 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005780 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005781 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005782 return getPointerType(ResultType);
5783 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005784 case Type::BlockPointer:
5785 {
5786 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005787 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5788 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005789 if (Unqualified) {
5790 LHSPointee = LHSPointee.getUnqualifiedType();
5791 RHSPointee = RHSPointee.getUnqualifiedType();
5792 }
5793 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5794 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005795 if (ResultType.isNull()) return QualType();
5796 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5797 return LHS;
5798 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5799 return RHS;
5800 return getBlockPointerType(ResultType);
5801 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005802 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005803 {
5804 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5805 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5806 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5807 return QualType();
5808
5809 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5810 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005811 if (Unqualified) {
5812 LHSElem = LHSElem.getUnqualifiedType();
5813 RHSElem = RHSElem.getUnqualifiedType();
5814 }
5815
5816 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005817 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005818 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5819 return LHS;
5820 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5821 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005822 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5823 ArrayType::ArraySizeModifier(), 0);
5824 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5825 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005826 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5827 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005828 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5829 return LHS;
5830 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5831 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005832 if (LVAT) {
5833 // FIXME: This isn't correct! But tricky to implement because
5834 // the array's size has to be the size of LHS, but the type
5835 // has to be different.
5836 return LHS;
5837 }
5838 if (RVAT) {
5839 // FIXME: This isn't correct! But tricky to implement because
5840 // the array's size has to be the size of RHS, but the type
5841 // has to be different.
5842 return RHS;
5843 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005844 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5845 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005846 return getIncompleteArrayType(ResultType,
5847 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005848 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005849 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005850 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005851 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005852 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005853 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005854 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005855 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005856 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005857 case Type::Complex:
5858 // Distinct complex types are incompatible.
5859 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005860 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005861 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005862 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5863 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005864 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005865 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005866 case Type::ObjCObject: {
5867 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005868 // FIXME: This should be type compatibility, e.g. whether
5869 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005870 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5871 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5872 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005873 return LHS;
5874
Eli Friedman47f77112008-08-22 00:56:42 +00005875 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005876 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005877 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005878 if (OfBlockPointer) {
5879 if (canAssignObjCInterfacesInBlockPointer(
5880 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005881 RHS->getAs<ObjCObjectPointerType>(),
5882 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005883 return LHS;
5884 return QualType();
5885 }
John McCall9dd450b2009-09-21 23:43:11 +00005886 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5887 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005888 return LHS;
5889
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005890 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005891 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005892 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005893
5894 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005895}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005896
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005897/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5898/// 'RHS' attributes and returns the merged version; including for function
5899/// return types.
5900QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5901 QualType LHSCan = getCanonicalType(LHS),
5902 RHSCan = getCanonicalType(RHS);
5903 // If two types are identical, they are compatible.
5904 if (LHSCan == RHSCan)
5905 return LHS;
5906 if (RHSCan->isFunctionType()) {
5907 if (!LHSCan->isFunctionType())
5908 return QualType();
5909 QualType OldReturnType =
5910 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5911 QualType NewReturnType =
5912 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5913 QualType ResReturnType =
5914 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5915 if (ResReturnType.isNull())
5916 return QualType();
5917 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5918 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5919 // In either case, use OldReturnType to build the new function type.
5920 const FunctionType *F = LHS->getAs<FunctionType>();
5921 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005922 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5923 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005924 QualType ResultType
5925 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005926 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005927 return ResultType;
5928 }
5929 }
5930 return QualType();
5931 }
5932
5933 // If the qualifiers are different, the types can still be merged.
5934 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5935 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5936 if (LQuals != RQuals) {
5937 // If any of these qualifiers are different, we have a type mismatch.
5938 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5939 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5940 return QualType();
5941
5942 // Exactly one GC qualifier difference is allowed: __strong is
5943 // okay if the other type has no GC qualifier but is an Objective
5944 // C object pointer (i.e. implicitly strong by default). We fix
5945 // this by pretending that the unqualified type was actually
5946 // qualified __strong.
5947 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5948 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5949 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5950
5951 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5952 return QualType();
5953
5954 if (GC_L == Qualifiers::Strong)
5955 return LHS;
5956 if (GC_R == Qualifiers::Strong)
5957 return RHS;
5958 return QualType();
5959 }
5960
5961 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5962 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5963 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5964 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5965 if (ResQT == LHSBaseQT)
5966 return LHS;
5967 if (ResQT == RHSBaseQT)
5968 return RHS;
5969 }
5970 return QualType();
5971}
5972
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005973//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005974// Integer Predicates
5975//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005976
Jay Foad39c79802011-01-12 09:06:06 +00005977unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005978 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005979 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005980 if (T->isBooleanType())
5981 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005982 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005983 return (unsigned)getTypeSize(T);
5984}
5985
5986QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005987 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005988
5989 // Turn <4 x signed int> -> <4 x unsigned int>
5990 if (const VectorType *VTy = T->getAs<VectorType>())
5991 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005992 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005993
5994 // For enums, we return the unsigned version of the base type.
5995 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005996 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005997
5998 const BuiltinType *BTy = T->getAs<BuiltinType>();
5999 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006000 switch (BTy->getKind()) {
6001 case BuiltinType::Char_S:
6002 case BuiltinType::SChar:
6003 return UnsignedCharTy;
6004 case BuiltinType::Short:
6005 return UnsignedShortTy;
6006 case BuiltinType::Int:
6007 return UnsignedIntTy;
6008 case BuiltinType::Long:
6009 return UnsignedLongTy;
6010 case BuiltinType::LongLong:
6011 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006012 case BuiltinType::Int128:
6013 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006014 default:
6015 assert(0 && "Unexpected signed integer type");
6016 return QualType();
6017 }
6018}
6019
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006020ASTMutationListener::~ASTMutationListener() { }
6021
Chris Lattnerecd79c62009-06-14 00:45:47 +00006022
6023//===----------------------------------------------------------------------===//
6024// Builtin Type Computation
6025//===----------------------------------------------------------------------===//
6026
6027/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006028/// pointer over the consumed characters. This returns the resultant type. If
6029/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6030/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6031/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006032///
6033/// RequiresICE is filled in on return to indicate whether the value is required
6034/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006035static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006036 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006037 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006038 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006039 // Modifiers.
6040 int HowLong = 0;
6041 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006042 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006043
Chris Lattnerdc226c22010-10-01 22:42:38 +00006044 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006045 bool Done = false;
6046 while (!Done) {
6047 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006048 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006049 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006050 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006051 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006052 case 'S':
6053 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6054 assert(!Signed && "Can't use 'S' modifier multiple times!");
6055 Signed = true;
6056 break;
6057 case 'U':
6058 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6059 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6060 Unsigned = true;
6061 break;
6062 case 'L':
6063 assert(HowLong <= 2 && "Can't have LLLL modifier");
6064 ++HowLong;
6065 break;
6066 }
6067 }
6068
6069 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006070
Chris Lattnerecd79c62009-06-14 00:45:47 +00006071 // Read the base type.
6072 switch (*Str++) {
6073 default: assert(0 && "Unknown builtin type letter!");
6074 case 'v':
6075 assert(HowLong == 0 && !Signed && !Unsigned &&
6076 "Bad modifiers used with 'v'!");
6077 Type = Context.VoidTy;
6078 break;
6079 case 'f':
6080 assert(HowLong == 0 && !Signed && !Unsigned &&
6081 "Bad modifiers used with 'f'!");
6082 Type = Context.FloatTy;
6083 break;
6084 case 'd':
6085 assert(HowLong < 2 && !Signed && !Unsigned &&
6086 "Bad modifiers used with 'd'!");
6087 if (HowLong)
6088 Type = Context.LongDoubleTy;
6089 else
6090 Type = Context.DoubleTy;
6091 break;
6092 case 's':
6093 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6094 if (Unsigned)
6095 Type = Context.UnsignedShortTy;
6096 else
6097 Type = Context.ShortTy;
6098 break;
6099 case 'i':
6100 if (HowLong == 3)
6101 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6102 else if (HowLong == 2)
6103 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6104 else if (HowLong == 1)
6105 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6106 else
6107 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6108 break;
6109 case 'c':
6110 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6111 if (Signed)
6112 Type = Context.SignedCharTy;
6113 else if (Unsigned)
6114 Type = Context.UnsignedCharTy;
6115 else
6116 Type = Context.CharTy;
6117 break;
6118 case 'b': // boolean
6119 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6120 Type = Context.BoolTy;
6121 break;
6122 case 'z': // size_t.
6123 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6124 Type = Context.getSizeType();
6125 break;
6126 case 'F':
6127 Type = Context.getCFConstantStringType();
6128 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006129 case 'G':
6130 Type = Context.getObjCIdType();
6131 break;
6132 case 'H':
6133 Type = Context.getObjCSelType();
6134 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006135 case 'a':
6136 Type = Context.getBuiltinVaListType();
6137 assert(!Type.isNull() && "builtin va list type not initialized!");
6138 break;
6139 case 'A':
6140 // This is a "reference" to a va_list; however, what exactly
6141 // this means depends on how va_list is defined. There are two
6142 // different kinds of va_list: ones passed by value, and ones
6143 // passed by reference. An example of a by-value va_list is
6144 // x86, where va_list is a char*. An example of by-ref va_list
6145 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6146 // we want this argument to be a char*&; for x86-64, we want
6147 // it to be a __va_list_tag*.
6148 Type = Context.getBuiltinVaListType();
6149 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006150 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006151 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006152 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006153 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006154 break;
6155 case 'V': {
6156 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006157 unsigned NumElements = strtoul(Str, &End, 10);
6158 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006159 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006160
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006161 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6162 RequiresICE, false);
6163 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006164
6165 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006166 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006167 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006168 break;
6169 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006170 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006171 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6172 false);
6173 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006174 Type = Context.getComplexType(ElementType);
6175 break;
6176 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006177 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006178 Type = Context.getFILEType();
6179 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006180 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006181 return QualType();
6182 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006183 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006184 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006185 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006186 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006187 else
6188 Type = Context.getjmp_bufType();
6189
Mike Stump2adb4da2009-07-28 23:47:15 +00006190 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006191 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006192 return QualType();
6193 }
6194 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006195 }
Mike Stump11289f42009-09-09 15:08:12 +00006196
Chris Lattnerdc226c22010-10-01 22:42:38 +00006197 // If there are modifiers and if we're allowed to parse them, go for it.
6198 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006199 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006200 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006201 default: Done = true; --Str; break;
6202 case '*':
6203 case '&': {
6204 // Both pointers and references can have their pointee types
6205 // qualified with an address space.
6206 char *End;
6207 unsigned AddrSpace = strtoul(Str, &End, 10);
6208 if (End != Str && AddrSpace != 0) {
6209 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6210 Str = End;
6211 }
6212 if (c == '*')
6213 Type = Context.getPointerType(Type);
6214 else
6215 Type = Context.getLValueReferenceType(Type);
6216 break;
6217 }
6218 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6219 case 'C':
6220 Type = Type.withConst();
6221 break;
6222 case 'D':
6223 Type = Context.getVolatileType(Type);
6224 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006225 }
6226 }
Chris Lattner84733392010-10-01 07:13:18 +00006227
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006228 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006229 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006230
Chris Lattnerecd79c62009-06-14 00:45:47 +00006231 return Type;
6232}
6233
6234/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006235QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006236 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006237 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006238 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006239
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006240 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006241
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006242 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006243 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006244 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6245 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006246 if (Error != GE_None)
6247 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006248
6249 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6250
Chris Lattnerecd79c62009-06-14 00:45:47 +00006251 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006252 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006253 if (Error != GE_None)
6254 return QualType();
6255
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006256 // If this argument is required to be an IntegerConstantExpression and the
6257 // caller cares, fill in the bitmask we return.
6258 if (RequiresICE && IntegerConstantArgs)
6259 *IntegerConstantArgs |= 1 << ArgTypes.size();
6260
Chris Lattnerecd79c62009-06-14 00:45:47 +00006261 // Do array -> pointer decay. The builtin should use the decayed type.
6262 if (Ty->isArrayType())
6263 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006264
Chris Lattnerecd79c62009-06-14 00:45:47 +00006265 ArgTypes.push_back(Ty);
6266 }
6267
6268 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6269 "'.' should only occur at end of builtin type list!");
6270
John McCall991eb4b2010-12-21 00:44:39 +00006271 FunctionType::ExtInfo EI;
6272 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6273
6274 bool Variadic = (TypeStr[0] == '.');
6275
6276 // We really shouldn't be making a no-proto type here, especially in C++.
6277 if (ArgTypes.empty() && Variadic)
6278 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006279
John McCalldb40c7f2010-12-14 08:05:40 +00006280 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006281 EPI.ExtInfo = EI;
6282 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006283
6284 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006285}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006286
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006287GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6288 GVALinkage External = GVA_StrongExternal;
6289
6290 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006291 switch (L) {
6292 case NoLinkage:
6293 case InternalLinkage:
6294 case UniqueExternalLinkage:
6295 return GVA_Internal;
6296
6297 case ExternalLinkage:
6298 switch (FD->getTemplateSpecializationKind()) {
6299 case TSK_Undeclared:
6300 case TSK_ExplicitSpecialization:
6301 External = GVA_StrongExternal;
6302 break;
6303
6304 case TSK_ExplicitInstantiationDefinition:
6305 return GVA_ExplicitTemplateInstantiation;
6306
6307 case TSK_ExplicitInstantiationDeclaration:
6308 case TSK_ImplicitInstantiation:
6309 External = GVA_TemplateInstantiation;
6310 break;
6311 }
6312 }
6313
6314 if (!FD->isInlined())
6315 return External;
6316
6317 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6318 // GNU or C99 inline semantics. Determine whether this symbol should be
6319 // externally visible.
6320 if (FD->isInlineDefinitionExternallyVisible())
6321 return External;
6322
6323 // C99 inline semantics, where the symbol is not externally visible.
6324 return GVA_C99Inline;
6325 }
6326
6327 // C++0x [temp.explicit]p9:
6328 // [ Note: The intent is that an inline function that is the subject of
6329 // an explicit instantiation declaration will still be implicitly
6330 // instantiated when used so that the body can be considered for
6331 // inlining, but that no out-of-line copy of the inline function would be
6332 // generated in the translation unit. -- end note ]
6333 if (FD->getTemplateSpecializationKind()
6334 == TSK_ExplicitInstantiationDeclaration)
6335 return GVA_C99Inline;
6336
6337 return GVA_CXXInline;
6338}
6339
6340GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6341 // If this is a static data member, compute the kind of template
6342 // specialization. Otherwise, this variable is not part of a
6343 // template.
6344 TemplateSpecializationKind TSK = TSK_Undeclared;
6345 if (VD->isStaticDataMember())
6346 TSK = VD->getTemplateSpecializationKind();
6347
6348 Linkage L = VD->getLinkage();
6349 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6350 VD->getType()->getLinkage() == UniqueExternalLinkage)
6351 L = UniqueExternalLinkage;
6352
6353 switch (L) {
6354 case NoLinkage:
6355 case InternalLinkage:
6356 case UniqueExternalLinkage:
6357 return GVA_Internal;
6358
6359 case ExternalLinkage:
6360 switch (TSK) {
6361 case TSK_Undeclared:
6362 case TSK_ExplicitSpecialization:
6363 return GVA_StrongExternal;
6364
6365 case TSK_ExplicitInstantiationDeclaration:
6366 llvm_unreachable("Variable should not be instantiated");
6367 // Fall through to treat this like any other instantiation.
6368
6369 case TSK_ExplicitInstantiationDefinition:
6370 return GVA_ExplicitTemplateInstantiation;
6371
6372 case TSK_ImplicitInstantiation:
6373 return GVA_TemplateInstantiation;
6374 }
6375 }
6376
6377 return GVA_StrongExternal;
6378}
6379
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006380bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006381 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6382 if (!VD->isFileVarDecl())
6383 return false;
6384 } else if (!isa<FunctionDecl>(D))
6385 return false;
6386
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006387 // Weak references don't produce any output by themselves.
6388 if (D->hasAttr<WeakRefAttr>())
6389 return false;
6390
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006391 // Aliases and used decls are required.
6392 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6393 return true;
6394
6395 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6396 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006397 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006398 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006399
6400 // Constructors and destructors are required.
6401 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6402 return true;
6403
6404 // The key function for a class is required.
6405 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6406 const CXXRecordDecl *RD = MD->getParent();
6407 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6408 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6409 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6410 return true;
6411 }
6412 }
6413
6414 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6415
6416 // static, static inline, always_inline, and extern inline functions can
6417 // always be deferred. Normal inline functions can be deferred in C99/C++.
6418 // Implicit template instantiations can also be deferred in C++.
6419 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6420 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6421 return false;
6422 return true;
6423 }
6424
6425 const VarDecl *VD = cast<VarDecl>(D);
6426 assert(VD->isFileVarDecl() && "Expected file scoped var");
6427
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006428 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6429 return false;
6430
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006431 // Structs that have non-trivial constructors or destructors are required.
6432
6433 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006434 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006435 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6436 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006437 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6438 RD->hasTrivialCopyConstructor() &&
6439 RD->hasTrivialMoveConstructor() &&
6440 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006441 return true;
6442 }
6443 }
6444
6445 GVALinkage L = GetGVALinkageForVariable(VD);
6446 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6447 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6448 return false;
6449 }
6450
6451 return true;
6452}
Charles Davis53c59df2010-08-16 03:33:14 +00006453
Charles Davis99202b32010-11-09 18:04:24 +00006454CallingConv ASTContext::getDefaultMethodCallConv() {
6455 // Pass through to the C++ ABI object
6456 return ABI->getDefaultMethodCallConv();
6457}
6458
Jay Foad39c79802011-01-12 09:06:06 +00006459bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006460 // Pass through to the C++ ABI object
6461 return ABI->isNearlyEmpty(RD);
6462}
6463
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006464MangleContext *ASTContext::createMangleContext() {
6465 switch (Target.getCXXABI()) {
6466 case CXXABI_ARM:
6467 case CXXABI_Itanium:
6468 return createItaniumMangleContext(*this, getDiagnostics());
6469 case CXXABI_Microsoft:
6470 return createMicrosoftMangleContext(*this, getDiagnostics());
6471 }
6472 assert(0 && "Unsupported ABI");
6473 return 0;
6474}
6475
Charles Davis53c59df2010-08-16 03:33:14 +00006476CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006477
6478size_t ASTContext::getSideTableAllocatedMemory() const {
6479 size_t bytes = 0;
6480 bytes += ASTRecordLayouts.getMemorySize();
6481 bytes += ObjCLayouts.getMemorySize();
6482 bytes += KeyFunctions.getMemorySize();
6483 bytes += ObjCImpls.getMemorySize();
6484 bytes += BlockVarCopyInits.getMemorySize();
6485 bytes += DeclAttrs.getMemorySize();
6486 bytes += InstantiatedFromStaticDataMember.getMemorySize();
6487 bytes += InstantiatedFromUsingDecl.getMemorySize();
6488 bytes += InstantiatedFromUsingShadowDecl.getMemorySize();
6489 bytes += InstantiatedFromUnnamedFieldDecl.getMemorySize();
6490 return bytes;
6491}