blob: a653e60efec0ec9560f0248c3432234206031ae1 [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();
107 llvm::SmallVector<NamedDecl *, 4> CanonParams;
108 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()) {
126 llvm::SmallVector<QualType, 2> ExpandedTypes;
127 llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
128 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_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000222 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
223 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
John McCall31168b02011-06-15 23:02:42 +0000224 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0),
225 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
226 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000227 NullTypeSourceInfo(QualType()),
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000228 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
229 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000230 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000231 BuiltinInfo(builtins),
232 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000233 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000234 LastSDM(0, 0),
John McCall147d0212011-02-22 22:38:33 +0000235 UniqueBlockByRefTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000236 ObjCIdRedefinitionType = QualType();
237 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000238 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000239 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000240 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000241 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000242}
243
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000244ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000245 // Release the DenseMaps associated with DeclContext objects.
246 // FIXME: Is this the ideal solution?
247 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000248
Douglas Gregor5b11d492010-07-25 17:53:33 +0000249 // Call all of the deallocation functions.
250 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
251 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000252
Douglas Gregor832940b2010-03-02 23:58:15 +0000253 // Release all of the memory associated with overridden C++ methods.
254 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
255 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
256 OM != OMEnd; ++OM)
257 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000258
Ted Kremenek076baeb2010-06-08 23:00:58 +0000259 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000260 // because they can contain DenseMaps.
261 for (llvm::DenseMap<const ObjCContainerDecl*,
262 const ASTRecordLayout*>::iterator
263 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
264 // Increment in loop to prevent using deallocated memory.
265 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
266 R->Destroy(*this);
267
Ted Kremenek076baeb2010-06-08 23:00:58 +0000268 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
269 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
270 // Increment in loop to prevent using deallocated memory.
271 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
272 R->Destroy(*this);
273 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000274
275 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
276 AEnd = DeclAttrs.end();
277 A != AEnd; ++A)
278 A->second->~AttrVec();
279}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000280
Douglas Gregor1a809332010-05-23 18:26:36 +0000281void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
282 Deallocations.push_back(std::make_pair(Callback, Data));
283}
284
Mike Stump11289f42009-09-09 15:08:12 +0000285void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000286ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
287 ExternalSource.reset(Source.take());
288}
289
Chris Lattner4eb445d2007-01-26 01:27:23 +0000290void ASTContext::PrintStats() const {
291 fprintf(stderr, "*** AST Context Stats:\n");
292 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000293
Douglas Gregora30d0462009-05-26 14:40:08 +0000294 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000295#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000296#define ABSTRACT_TYPE(Name, Parent)
297#include "clang/AST/TypeNodes.def"
298 0 // Extra
299 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000300
Chris Lattner4eb445d2007-01-26 01:27:23 +0000301 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
302 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000303 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000304 }
305
Douglas Gregora30d0462009-05-26 14:40:08 +0000306 unsigned Idx = 0;
307 unsigned TotalBytes = 0;
308#define TYPE(Name, Parent) \
309 if (counts[Idx]) \
310 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
311 TotalBytes += counts[Idx] * sizeof(Name##Type); \
312 ++Idx;
313#define ABSTRACT_TYPE(Name, Parent)
314#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000315
Douglas Gregora30d0462009-05-26 14:40:08 +0000316 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregor747eb782010-07-08 06:14:04 +0000317
Douglas Gregor7454c562010-07-02 20:37:36 +0000318 // Implicit special member functions.
Douglas Gregor9672f922010-07-03 00:47:00 +0000319 fprintf(stderr, " %u/%u implicit default constructors created\n",
320 NumImplicitDefaultConstructorsDeclared,
321 NumImplicitDefaultConstructors);
Douglas Gregora6d69502010-07-02 23:41:54 +0000322 fprintf(stderr, " %u/%u implicit copy constructors created\n",
323 NumImplicitCopyConstructorsDeclared,
324 NumImplicitCopyConstructors);
Alexis Huntfcaeae42011-05-25 20:50:04 +0000325 if (getLangOptions().CPlusPlus)
326 fprintf(stderr, " %u/%u implicit move constructors created\n",
327 NumImplicitMoveConstructorsDeclared,
328 NumImplicitMoveConstructors);
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000329 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
330 NumImplicitCopyAssignmentOperatorsDeclared,
331 NumImplicitCopyAssignmentOperators);
Alexis Huntfcaeae42011-05-25 20:50:04 +0000332 if (getLangOptions().CPlusPlus)
333 fprintf(stderr, " %u/%u implicit move assignment operators created\n",
334 NumImplicitMoveAssignmentOperatorsDeclared,
335 NumImplicitMoveAssignmentOperators);
Douglas Gregor7454c562010-07-02 20:37:36 +0000336 fprintf(stderr, " %u/%u implicit destructors created\n",
337 NumImplicitDestructorsDeclared, NumImplicitDestructors);
338
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000339 if (ExternalSource.get()) {
340 fprintf(stderr, "\n");
341 ExternalSource->PrintStats();
342 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000343
Douglas Gregor5b11d492010-07-25 17:53:33 +0000344 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000345}
346
347
John McCall48f2d582009-10-23 23:03:21 +0000348void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000349 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000350 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000351 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000352}
353
Chris Lattner970e54e2006-11-12 00:37:36 +0000354void ASTContext::InitBuiltinTypes() {
355 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000356
Chris Lattner970e54e2006-11-12 00:37:36 +0000357 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000358 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000359
Chris Lattner970e54e2006-11-12 00:37:36 +0000360 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000361 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000362 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000363 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000364 InitBuiltinType(CharTy, BuiltinType::Char_S);
365 else
366 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000367 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000368 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
369 InitBuiltinType(ShortTy, BuiltinType::Short);
370 InitBuiltinType(IntTy, BuiltinType::Int);
371 InitBuiltinType(LongTy, BuiltinType::Long);
372 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000373
Chris Lattner970e54e2006-11-12 00:37:36 +0000374 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000375 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
376 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
377 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
378 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
379 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000380
Chris Lattner970e54e2006-11-12 00:37:36 +0000381 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000382 InitBuiltinType(FloatTy, BuiltinType::Float);
383 InitBuiltinType(DoubleTy, BuiltinType::Double);
384 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000385
Chris Lattnerf122cef2009-04-30 02:43:43 +0000386 // GNU extension, 128-bit integers.
387 InitBuiltinType(Int128Ty, BuiltinType::Int128);
388 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
389
Chris Lattnerad3467e2010-12-25 23:25:43 +0000390 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000391 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000392 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
393 else // -fshort-wchar makes wchar_t be unsigned.
394 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
395 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000396 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000397
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000398 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
399 InitBuiltinType(Char16Ty, BuiltinType::Char16);
400 else // C99
401 Char16Ty = getFromTargetType(Target.getChar16Type());
402
403 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
404 InitBuiltinType(Char32Ty, BuiltinType::Char32);
405 else // C99
406 Char32Ty = getFromTargetType(Target.getChar32Type());
407
Douglas Gregor4619e432008-12-05 23:32:09 +0000408 // Placeholder type for type-dependent expressions whose type is
409 // completely unknown. No code should ever check a type against
410 // DependentTy and users should never see it; however, it is here to
411 // help diagnose failures to properly check for type-dependent
412 // expressions.
413 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000414
John McCall36e7fe32010-10-12 00:20:44 +0000415 // Placeholder type for functions.
416 InitBuiltinType(OverloadTy, BuiltinType::Overload);
417
John McCall0009fcc2011-04-26 20:42:42 +0000418 // Placeholder type for bound members.
419 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
420
John McCall31996342011-04-07 08:22:57 +0000421 // "any" type; useful for debugger-like clients.
422 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
423
Chris Lattner970e54e2006-11-12 00:37:36 +0000424 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000425 FloatComplexTy = getComplexType(FloatTy);
426 DoubleComplexTy = getComplexType(DoubleTy);
427 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000428
Steve Naroff66e9f332007-10-15 14:41:52 +0000429 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000430
Steve Naroff1329fa02009-07-15 18:40:39 +0000431 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
432 ObjCIdTypedefType = QualType();
433 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000434 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000435
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000436 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000437 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
438 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000439 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000440
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000441 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000442
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000443 // void * type
444 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000445
446 // nullptr type (C++0x 2.14.7)
447 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000448}
449
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000450Diagnostic &ASTContext::getDiagnostics() const {
451 return SourceMgr.getDiagnostics();
452}
453
Douglas Gregor561eceb2010-08-30 16:49:28 +0000454AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
455 AttrVec *&Result = DeclAttrs[D];
456 if (!Result) {
457 void *Mem = Allocate(sizeof(AttrVec));
458 Result = new (Mem) AttrVec;
459 }
460
461 return *Result;
462}
463
464/// \brief Erase the attributes corresponding to the given declaration.
465void ASTContext::eraseDeclAttrs(const Decl *D) {
466 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
467 if (Pos != DeclAttrs.end()) {
468 Pos->second->~AttrVec();
469 DeclAttrs.erase(Pos);
470 }
471}
472
Douglas Gregor86d142a2009-10-08 07:24:58 +0000473MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000474ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000475 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000476 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000477 = InstantiatedFromStaticDataMember.find(Var);
478 if (Pos == InstantiatedFromStaticDataMember.end())
479 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000480
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000481 return Pos->second;
482}
483
Mike Stump11289f42009-09-09 15:08:12 +0000484void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000485ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000486 TemplateSpecializationKind TSK,
487 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000488 assert(Inst->isStaticDataMember() && "Not a static data member");
489 assert(Tmpl->isStaticDataMember() && "Not a static data member");
490 assert(!InstantiatedFromStaticDataMember[Inst] &&
491 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000492 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000493 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000494}
495
John McCalle61f2ba2009-11-18 02:36:19 +0000496NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000497ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000498 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000499 = InstantiatedFromUsingDecl.find(UUD);
500 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000501 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000502
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000503 return Pos->second;
504}
505
506void
John McCallb96ec562009-12-04 22:46:56 +0000507ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
508 assert((isa<UsingDecl>(Pattern) ||
509 isa<UnresolvedUsingValueDecl>(Pattern) ||
510 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
511 "pattern decl is not a using decl");
512 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
513 InstantiatedFromUsingDecl[Inst] = Pattern;
514}
515
516UsingShadowDecl *
517ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
518 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
519 = InstantiatedFromUsingShadowDecl.find(Inst);
520 if (Pos == InstantiatedFromUsingShadowDecl.end())
521 return 0;
522
523 return Pos->second;
524}
525
526void
527ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
528 UsingShadowDecl *Pattern) {
529 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
530 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000531}
532
Anders Carlsson5da84842009-09-01 04:26:58 +0000533FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
534 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
535 = InstantiatedFromUnnamedFieldDecl.find(Field);
536 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
537 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000538
Anders Carlsson5da84842009-09-01 04:26:58 +0000539 return Pos->second;
540}
541
542void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
543 FieldDecl *Tmpl) {
544 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
545 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
546 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
547 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000548
Anders Carlsson5da84842009-09-01 04:26:58 +0000549 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
550}
551
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000552bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
553 const FieldDecl *LastFD) const {
554 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
555 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0);
556
557}
558
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000559bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
560 const FieldDecl *LastFD) const {
561 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Fariborz Jahanian759e4a12011-05-03 22:07:14 +0000562 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0 &&
563 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000564
565}
566
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000567bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
568 const FieldDecl *LastFD) const {
569 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
570 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() &&
571 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
572}
573
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000574bool ASTContext::NoneBitfieldFollowsBitfield(const FieldDecl *FD,
575 const FieldDecl *LastFD) const {
576 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
577 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
578}
579
580bool ASTContext::BitfieldFollowsNoneBitfield(const FieldDecl *FD,
581 const FieldDecl *LastFD) const {
582 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
583 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
584}
585
Douglas Gregor832940b2010-03-02 23:58:15 +0000586ASTContext::overridden_cxx_method_iterator
587ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
588 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
589 = OverriddenMethods.find(Method);
590 if (Pos == OverriddenMethods.end())
591 return 0;
592
593 return Pos->second.begin();
594}
595
596ASTContext::overridden_cxx_method_iterator
597ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
598 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
599 = OverriddenMethods.find(Method);
600 if (Pos == OverriddenMethods.end())
601 return 0;
602
603 return Pos->second.end();
604}
605
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000606unsigned
607ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
608 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
609 = OverriddenMethods.find(Method);
610 if (Pos == OverriddenMethods.end())
611 return 0;
612
613 return Pos->second.size();
614}
615
Douglas Gregor832940b2010-03-02 23:58:15 +0000616void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
617 const CXXMethodDecl *Overridden) {
618 OverriddenMethods[Method].push_back(Overridden);
619}
620
Chris Lattner53cfe802007-07-18 17:52:12 +0000621//===----------------------------------------------------------------------===//
622// Type Sizing and Analysis
623//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000624
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000625/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
626/// scalar floating point type.
627const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000628 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000629 assert(BT && "Not a floating point type!");
630 switch (BT->getKind()) {
631 default: assert(0 && "Not a floating point type!");
632 case BuiltinType::Float: return Target.getFloatFormat();
633 case BuiltinType::Double: return Target.getDoubleFormat();
634 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
635 }
636}
637
Ken Dyck160146e2010-01-27 17:10:57 +0000638/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000639/// specified decl. Note that bitfields do not have a valid alignment, so
640/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000641/// If @p RefAsPointee, references are treated like their underlying type
642/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000643CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000644 unsigned Align = Target.getCharWidth();
645
John McCall94268702010-10-08 18:24:19 +0000646 bool UseAlignAttrOnly = false;
647 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
648 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000649
John McCall94268702010-10-08 18:24:19 +0000650 // __attribute__((aligned)) can increase or decrease alignment
651 // *except* on a struct or struct member, where it only increases
652 // alignment unless 'packed' is also specified.
653 //
654 // It is an error for [[align]] to decrease alignment, so we can
655 // ignore that possibility; Sema should diagnose it.
656 if (isa<FieldDecl>(D)) {
657 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
658 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
659 } else {
660 UseAlignAttrOnly = true;
661 }
662 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000663 else if (isa<FieldDecl>(D))
664 UseAlignAttrOnly =
665 D->hasAttr<PackedAttr>() ||
666 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000667
John McCall4e819612011-01-20 07:57:12 +0000668 // If we're using the align attribute only, just ignore everything
669 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000670 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000671 // do nothing
672
John McCall94268702010-10-08 18:24:19 +0000673 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000674 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000675 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000676 if (RefAsPointee)
677 T = RT->getPointeeType();
678 else
679 T = getPointerType(RT->getPointeeType());
680 }
681 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000682 // Adjust alignments of declarations with array type by the
683 // large-array alignment on the target.
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000684 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000685 const ArrayType *arrayType;
686 if (MinWidth && (arrayType = getAsArrayType(T))) {
687 if (isa<VariableArrayType>(arrayType))
688 Align = std::max(Align, Target.getLargeArrayAlign());
689 else if (isa<ConstantArrayType>(arrayType) &&
690 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
691 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000692
John McCall33ddac02011-01-19 10:06:00 +0000693 // Walk through any array types while we're at it.
694 T = getBaseElementType(arrayType);
695 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000696 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
697 }
John McCall4e819612011-01-20 07:57:12 +0000698
699 // Fields can be subject to extra alignment constraints, like if
700 // the field is packed, the struct is packed, or the struct has a
701 // a max-field-alignment constraint (#pragma pack). So calculate
702 // the actual alignment of the field within the struct, and then
703 // (as we're expected to) constrain that by the alignment of the type.
704 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
705 // So calculate the alignment of the field.
706 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
707
708 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000709 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000710
711 // Use the GCD of that and the offset within the record.
712 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
713 if (offset > 0) {
714 // Alignment is always a power of 2, so the GCD will be a power of 2,
715 // which means we get to do this crazy thing instead of Euclid's.
716 uint64_t lowBitOfOffset = offset & (~offset + 1);
717 if (lowBitOfOffset < fieldAlign)
718 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
719 }
720
721 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000722 }
Chris Lattner68061312009-01-24 21:53:27 +0000723 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000724
Ken Dyckcc56c542011-01-15 18:38:59 +0000725 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000726}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000727
John McCall87fe5d52010-05-20 01:18:31 +0000728std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000729ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000730 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000731 return std::make_pair(toCharUnitsFromBits(Info.first),
732 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000733}
734
735std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000736ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000737 return getTypeInfoInChars(T.getTypePtr());
738}
739
Chris Lattner983a8bb2007-07-13 22:13:22 +0000740/// getTypeSize - Return the size of the specified type, in bits. This method
741/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000742///
743/// FIXME: Pointers into different addr spaces could have different sizes and
744/// alignment requirements: getPointerInfo should take an AddrSpace, this
745/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000746std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000747ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000748 uint64_t Width=0;
749 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000750 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000751#define TYPE(Class, Base)
752#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000753#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000754#define DEPENDENT_TYPE(Class, Base) case Type::Class:
755#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000756 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000757 break;
758
Chris Lattner355332d2007-07-13 22:27:08 +0000759 case Type::FunctionNoProto:
760 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000761 // GCC extension: alignof(function) = 32 bits
762 Width = 0;
763 Align = 32;
764 break;
765
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000766 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000767 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000768 Width = 0;
769 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
770 break;
771
Steve Naroff5c131802007-08-30 01:06:46 +0000772 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000773 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000774
Chris Lattner37e05872008-03-05 18:54:05 +0000775 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000776 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000777 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000778 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000779 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000780 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000781 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000782 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000783 const VectorType *VT = cast<VectorType>(T);
784 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
785 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000786 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000787 // If the alignment is not a power of 2, round up to the next power of 2.
788 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000789 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000790 Align = llvm::NextPowerOf2(Align);
791 Width = llvm::RoundUpToAlignment(Width, Align);
792 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000793 break;
794 }
Chris Lattner647fb222007-07-18 18:26:58 +0000795
Chris Lattner7570e9c2008-03-08 08:52:55 +0000796 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000797 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000798 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000799 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000800 // GCC extension: alignof(void) = 8 bits.
801 Width = 0;
802 Align = 8;
803 break;
804
Chris Lattner6a4f7452007-12-19 19:23:28 +0000805 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000806 Width = Target.getBoolWidth();
807 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000808 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000809 case BuiltinType::Char_S:
810 case BuiltinType::Char_U:
811 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000812 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000813 Width = Target.getCharWidth();
814 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000815 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000816 case BuiltinType::WChar_S:
817 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000818 Width = Target.getWCharWidth();
819 Align = Target.getWCharAlign();
820 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000821 case BuiltinType::Char16:
822 Width = Target.getChar16Width();
823 Align = Target.getChar16Align();
824 break;
825 case BuiltinType::Char32:
826 Width = Target.getChar32Width();
827 Align = Target.getChar32Align();
828 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000829 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000830 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000831 Width = Target.getShortWidth();
832 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000833 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000834 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000835 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000836 Width = Target.getIntWidth();
837 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000838 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000839 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000840 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000841 Width = Target.getLongWidth();
842 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000843 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000844 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000845 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000846 Width = Target.getLongLongWidth();
847 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000848 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000849 case BuiltinType::Int128:
850 case BuiltinType::UInt128:
851 Width = 128;
852 Align = 128; // int128_t is 128-bit aligned on all targets.
853 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000854 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000855 Width = Target.getFloatWidth();
856 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000857 break;
858 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000859 Width = Target.getDoubleWidth();
860 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000861 break;
862 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000863 Width = Target.getLongDoubleWidth();
864 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000865 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000866 case BuiltinType::NullPtr:
867 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
868 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000869 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000870 case BuiltinType::ObjCId:
871 case BuiltinType::ObjCClass:
872 case BuiltinType::ObjCSel:
873 Width = Target.getPointerWidth(0);
874 Align = Target.getPointerAlign(0);
875 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000876 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000877 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000878 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000879 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000880 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000881 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000882 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000883 unsigned AS = getTargetAddressSpace(
884 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff921a45c2008-09-24 15:05:44 +0000885 Width = Target.getPointerWidth(AS);
886 Align = Target.getPointerAlign(AS);
887 break;
888 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000889 case Type::LValueReference:
890 case Type::RValueReference: {
891 // alignof and sizeof should never enter this code path here, so we go
892 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000893 unsigned AS = getTargetAddressSpace(
894 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000895 Width = Target.getPointerWidth(AS);
896 Align = Target.getPointerAlign(AS);
897 break;
898 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000899 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000900 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000901 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000902 Align = Target.getPointerAlign(AS);
903 break;
904 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000905 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000906 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000907 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000908 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000909 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000910 Align = PtrDiffInfo.second;
911 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000912 }
Chris Lattner647fb222007-07-18 18:26:58 +0000913 case Type::Complex: {
914 // Complex types have the same alignment as their elements, but twice the
915 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000916 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000917 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000918 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000919 Align = EltInfo.second;
920 break;
921 }
John McCall8b07ec22010-05-15 11:32:37 +0000922 case Type::ObjCObject:
923 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000924 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000925 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000926 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000927 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000928 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000929 break;
930 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000931 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000932 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000933 const TagType *TT = cast<TagType>(T);
934
935 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +0000936 Width = 8;
937 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +0000938 break;
939 }
Mike Stump11289f42009-09-09 15:08:12 +0000940
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000941 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000942 return getTypeInfo(ET->getDecl()->getIntegerType());
943
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000944 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000945 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000946 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000947 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +0000948 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000949 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000950
Chris Lattner63d2b362009-10-22 05:17:15 +0000951 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000952 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
953 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000954
Richard Smith30482bc2011-02-20 03:19:35 +0000955 case Type::Auto: {
956 const AutoType *A = cast<AutoType>(T);
957 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +0000958 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +0000959 }
960
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000961 case Type::Paren:
962 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
963
Douglas Gregoref462e62009-04-30 17:32:17 +0000964 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +0000965 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000966 std::pair<uint64_t, unsigned> Info
967 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +0000968 // If the typedef has an aligned attribute on it, it overrides any computed
969 // alignment we have. This violates the GCC documentation (which says that
970 // attribute(aligned) can only round up) but matches its implementation.
971 if (unsigned AttrAlign = Typedef->getMaxAlignment())
972 Align = AttrAlign;
973 else
974 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +0000975 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000976 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000977 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000978
979 case Type::TypeOfExpr:
980 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
981 .getTypePtr());
982
983 case Type::TypeOf:
984 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
985
Anders Carlsson81df7b82009-06-24 19:06:50 +0000986 case Type::Decltype:
987 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
988 .getTypePtr());
989
Alexis Hunte852b102011-05-24 22:41:36 +0000990 case Type::UnaryTransform:
991 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
992
Abramo Bagnara6150c882010-05-11 21:36:43 +0000993 case Type::Elaborated:
994 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000995
John McCall81904512011-01-06 01:58:22 +0000996 case Type::Attributed:
997 return getTypeInfo(
998 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
999
Richard Smith3f1b5d02011-05-05 21:57:07 +00001000 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001001 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001002 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001003 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1004 // A type alias template specialization may refer to a typedef with the
1005 // aligned attribute on it.
1006 if (TST->isTypeAlias())
1007 return getTypeInfo(TST->getAliasedType().getTypePtr());
1008 else
1009 return getTypeInfo(getCanonicalType(T));
1010 }
1011
Douglas Gregoref462e62009-04-30 17:32:17 +00001012 }
Mike Stump11289f42009-09-09 15:08:12 +00001013
Chris Lattner53cfe802007-07-18 17:52:12 +00001014 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001015 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001016}
1017
Ken Dyckcc56c542011-01-15 18:38:59 +00001018/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1019CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1020 return CharUnits::fromQuantity(BitSize / getCharWidth());
1021}
1022
Ken Dyckb0fcc592011-02-11 01:54:29 +00001023/// toBits - Convert a size in characters to a size in characters.
1024int64_t ASTContext::toBits(CharUnits CharSize) const {
1025 return CharSize.getQuantity() * getCharWidth();
1026}
1027
Ken Dyck8c89d592009-12-22 14:23:30 +00001028/// getTypeSizeInChars - Return the size of the specified type, in characters.
1029/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001030CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001031 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001032}
Jay Foad39c79802011-01-12 09:06:06 +00001033CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001034 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001035}
1036
Ken Dycka6046ab2010-01-26 17:25:18 +00001037/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001038/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001039CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001040 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001041}
Jay Foad39c79802011-01-12 09:06:06 +00001042CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001043 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001044}
1045
Chris Lattnera3402cd2009-01-27 18:08:34 +00001046/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1047/// type for the current target in bits. This can be different than the ABI
1048/// alignment in cases where it is beneficial for performance to overalign
1049/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001050unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001051 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001052
1053 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001054 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001055 T = CT->getElementType().getTypePtr();
1056 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1057 T->isSpecificBuiltinType(BuiltinType::LongLong))
1058 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1059
Chris Lattnera3402cd2009-01-27 18:08:34 +00001060 return ABIAlign;
1061}
1062
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001063/// ShallowCollectObjCIvars -
1064/// Collect all ivars, including those synthesized, in the current class.
1065///
1066void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +00001067 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001068 // FIXME. This need be removed but there are two many places which
1069 // assume const-ness of ObjCInterfaceDecl
1070 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1071 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1072 Iv= Iv->getNextIvar())
1073 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001074}
1075
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001076/// DeepCollectObjCIvars -
1077/// This routine first collects all declared, but not synthesized, ivars in
1078/// super class and then collects all ivars, including those synthesized for
1079/// current class. This routine is used for implementation of current class
1080/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001081///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001082void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1083 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +00001084 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001085 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1086 DeepCollectObjCIvars(SuperClass, false, Ivars);
1087 if (!leafClass) {
1088 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1089 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001090 Ivars.push_back(*I);
1091 }
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001092 else
1093 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001094}
1095
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001096/// CollectInheritedProtocols - Collect all protocols in current class and
1097/// those inherited by it.
1098void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001099 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001100 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001101 // We can use protocol_iterator here instead of
1102 // all_referenced_protocol_iterator since we are walking all categories.
1103 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1104 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001105 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001106 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001107 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001108 PE = Proto->protocol_end(); P != PE; ++P) {
1109 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001110 CollectInheritedProtocols(*P, Protocols);
1111 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001112 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001113
1114 // Categories of this Interface.
1115 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1116 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1117 CollectInheritedProtocols(CDeclChain, Protocols);
1118 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1119 while (SD) {
1120 CollectInheritedProtocols(SD, Protocols);
1121 SD = SD->getSuperClass();
1122 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001123 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001124 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001125 PE = OC->protocol_end(); P != PE; ++P) {
1126 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001127 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001128 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1129 PE = Proto->protocol_end(); P != PE; ++P)
1130 CollectInheritedProtocols(*P, Protocols);
1131 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001132 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001133 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1134 PE = OP->protocol_end(); P != PE; ++P) {
1135 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001136 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001137 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1138 PE = Proto->protocol_end(); P != PE; ++P)
1139 CollectInheritedProtocols(*P, Protocols);
1140 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001141 }
1142}
1143
Jay Foad39c79802011-01-12 09:06:06 +00001144unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001145 unsigned count = 0;
1146 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001147 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1148 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001149 count += CDecl->ivar_size();
1150
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001151 // Count ivar defined in this class's implementation. This
1152 // includes synthesized ivars.
1153 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001154 count += ImplDecl->ivar_size();
1155
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001156 return count;
1157}
1158
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001159/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1160ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1161 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1162 I = ObjCImpls.find(D);
1163 if (I != ObjCImpls.end())
1164 return cast<ObjCImplementationDecl>(I->second);
1165 return 0;
1166}
1167/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1168ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1169 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1170 I = ObjCImpls.find(D);
1171 if (I != ObjCImpls.end())
1172 return cast<ObjCCategoryImplDecl>(I->second);
1173 return 0;
1174}
1175
1176/// \brief Set the implementation of ObjCInterfaceDecl.
1177void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1178 ObjCImplementationDecl *ImplD) {
1179 assert(IFaceD && ImplD && "Passed null params");
1180 ObjCImpls[IFaceD] = ImplD;
1181}
1182/// \brief Set the implementation of ObjCCategoryDecl.
1183void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1184 ObjCCategoryImplDecl *ImplD) {
1185 assert(CatD && ImplD && "Passed null params");
1186 ObjCImpls[CatD] = ImplD;
1187}
1188
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001189/// \brief Get the copy initialization expression of VarDecl,or NULL if
1190/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001191Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001192 assert(VD && "Passed null params");
1193 assert(VD->hasAttr<BlocksAttr>() &&
1194 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001195 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001196 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001197 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1198}
1199
1200/// \brief Set the copy inialization expression of a block var decl.
1201void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1202 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001203 assert(VD->hasAttr<BlocksAttr>() &&
1204 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001205 BlockVarCopyInits[VD] = Init;
1206}
1207
John McCallbcd03502009-12-07 02:54:59 +00001208/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001209///
John McCallbcd03502009-12-07 02:54:59 +00001210/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001211/// the TypeLoc wrappers.
1212///
1213/// \param T the type that will be the basis for type source info. This type
1214/// should refer to how the declarator was written in source code, not to
1215/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001216TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001217 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001218 if (!DataSize)
1219 DataSize = TypeLoc::getFullDataSizeForType(T);
1220 else
1221 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001222 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001223
John McCallbcd03502009-12-07 02:54:59 +00001224 TypeSourceInfo *TInfo =
1225 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1226 new (TInfo) TypeSourceInfo(T);
1227 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001228}
1229
John McCallbcd03502009-12-07 02:54:59 +00001230TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001231 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001232 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001233 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001234 return DI;
1235}
1236
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001237const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001238ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001239 return getObjCLayout(D, 0);
1240}
1241
1242const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001243ASTContext::getASTObjCImplementationLayout(
1244 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001245 return getObjCLayout(D->getClassInterface(), D);
1246}
1247
Chris Lattner983a8bb2007-07-13 22:13:22 +00001248//===----------------------------------------------------------------------===//
1249// Type creation/memoization methods
1250//===----------------------------------------------------------------------===//
1251
Jay Foad39c79802011-01-12 09:06:06 +00001252QualType
John McCall33ddac02011-01-19 10:06:00 +00001253ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1254 unsigned fastQuals = quals.getFastQualifiers();
1255 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001256
1257 // Check if we've already instantiated this type.
1258 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001259 ExtQuals::Profile(ID, baseType, quals);
1260 void *insertPos = 0;
1261 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1262 assert(eq->getQualifiers() == quals);
1263 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001264 }
1265
John McCall33ddac02011-01-19 10:06:00 +00001266 // If the base type is not canonical, make the appropriate canonical type.
1267 QualType canon;
1268 if (!baseType->isCanonicalUnqualified()) {
1269 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1270 canonSplit.second.addConsistentQualifiers(quals);
1271 canon = getExtQualType(canonSplit.first, canonSplit.second);
1272
1273 // Re-find the insert position.
1274 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1275 }
1276
1277 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1278 ExtQualNodes.InsertNode(eq, insertPos);
1279 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001280}
1281
Jay Foad39c79802011-01-12 09:06:06 +00001282QualType
1283ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001284 QualType CanT = getCanonicalType(T);
1285 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001286 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001287
John McCall8ccfcb52009-09-24 19:53:00 +00001288 // If we are composing extended qualifiers together, merge together
1289 // into one ExtQuals node.
1290 QualifierCollector Quals;
1291 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001292
John McCall8ccfcb52009-09-24 19:53:00 +00001293 // If this type already has an address space specified, it cannot get
1294 // another one.
1295 assert(!Quals.hasAddressSpace() &&
1296 "Type cannot be in multiple addr spaces!");
1297 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001298
John McCall8ccfcb52009-09-24 19:53:00 +00001299 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001300}
1301
Chris Lattnerd60183d2009-02-18 22:53:11 +00001302QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001303 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001304 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001305 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001306 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001307
John McCall53fa7142010-12-24 02:08:15 +00001308 if (const PointerType *ptr = T->getAs<PointerType>()) {
1309 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001310 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001311 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1312 return getPointerType(ResultType);
1313 }
1314 }
Mike Stump11289f42009-09-09 15:08:12 +00001315
John McCall8ccfcb52009-09-24 19:53:00 +00001316 // If we are composing extended qualifiers together, merge together
1317 // into one ExtQuals node.
1318 QualifierCollector Quals;
1319 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001320
John McCall8ccfcb52009-09-24 19:53:00 +00001321 // If this type already has an ObjCGC specified, it cannot get
1322 // another one.
1323 assert(!Quals.hasObjCGCAttr() &&
1324 "Type cannot have multiple ObjCGCs!");
1325 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001326
John McCall8ccfcb52009-09-24 19:53:00 +00001327 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001328}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001329
John McCall4f5019e2010-12-19 02:44:49 +00001330const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1331 FunctionType::ExtInfo Info) {
1332 if (T->getExtInfo() == Info)
1333 return T;
1334
1335 QualType Result;
1336 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1337 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1338 } else {
1339 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1340 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1341 EPI.ExtInfo = Info;
1342 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1343 FPT->getNumArgs(), EPI);
1344 }
1345
1346 return cast<FunctionType>(Result.getTypePtr());
1347}
1348
Chris Lattnerc6395932007-06-22 20:56:16 +00001349/// getComplexType - Return the uniqued reference to the type for a complex
1350/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001351QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001352 // Unique pointers, to guarantee there is only one pointer of a particular
1353 // structure.
1354 llvm::FoldingSetNodeID ID;
1355 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001356
Chris Lattnerc6395932007-06-22 20:56:16 +00001357 void *InsertPos = 0;
1358 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1359 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001360
Chris Lattnerc6395932007-06-22 20:56:16 +00001361 // If the pointee type isn't canonical, this won't be a canonical type either,
1362 // so fill in the canonical type field.
1363 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001364 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001365 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001366
Chris Lattnerc6395932007-06-22 20:56:16 +00001367 // Get the new insert position for the node we care about.
1368 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001369 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001370 }
John McCall90d1c2d2009-09-24 23:30:46 +00001371 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001372 Types.push_back(New);
1373 ComplexTypes.InsertNode(New, InsertPos);
1374 return QualType(New, 0);
1375}
1376
Chris Lattner970e54e2006-11-12 00:37:36 +00001377/// getPointerType - Return the uniqued reference to the type for a pointer to
1378/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001379QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001380 // Unique pointers, to guarantee there is only one pointer of a particular
1381 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001382 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001383 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001384
Chris Lattner67521df2007-01-27 01:29:36 +00001385 void *InsertPos = 0;
1386 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001387 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001388
Chris Lattner7ccecb92006-11-12 08:50:50 +00001389 // If the pointee type isn't canonical, this won't be a canonical type either,
1390 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001391 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001392 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001393 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001394
Chris Lattner67521df2007-01-27 01:29:36 +00001395 // Get the new insert position for the node we care about.
1396 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001397 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001398 }
John McCall90d1c2d2009-09-24 23:30:46 +00001399 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001400 Types.push_back(New);
1401 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001402 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001403}
1404
Mike Stump11289f42009-09-09 15:08:12 +00001405/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001406/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001407QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001408 assert(T->isFunctionType() && "block of function types only");
1409 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001410 // structure.
1411 llvm::FoldingSetNodeID ID;
1412 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001413
Steve Naroffec33ed92008-08-27 16:04:49 +00001414 void *InsertPos = 0;
1415 if (BlockPointerType *PT =
1416 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1417 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001418
1419 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001420 // type either so fill in the canonical type field.
1421 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001422 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001423 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001424
Steve Naroffec33ed92008-08-27 16:04:49 +00001425 // Get the new insert position for the node we care about.
1426 BlockPointerType *NewIP =
1427 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001428 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001429 }
John McCall90d1c2d2009-09-24 23:30:46 +00001430 BlockPointerType *New
1431 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001432 Types.push_back(New);
1433 BlockPointerTypes.InsertNode(New, InsertPos);
1434 return QualType(New, 0);
1435}
1436
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001437/// getLValueReferenceType - Return the uniqued reference to the type for an
1438/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001439QualType
1440ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001441 assert(getCanonicalType(T) != OverloadTy &&
1442 "Unresolved overloaded function type");
1443
Bill Wendling3708c182007-05-27 10:15:43 +00001444 // Unique pointers, to guarantee there is only one pointer of a particular
1445 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001446 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001447 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001448
1449 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001450 if (LValueReferenceType *RT =
1451 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001452 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001453
John McCallfc93cf92009-10-22 22:37:11 +00001454 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1455
Bill Wendling3708c182007-05-27 10:15:43 +00001456 // If the referencee type isn't canonical, this won't be a canonical type
1457 // either, so fill in the canonical type field.
1458 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001459 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1460 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1461 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001462
Bill Wendling3708c182007-05-27 10:15:43 +00001463 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001464 LValueReferenceType *NewIP =
1465 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001466 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001467 }
1468
John McCall90d1c2d2009-09-24 23:30:46 +00001469 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001470 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1471 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001472 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001473 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001474
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001475 return QualType(New, 0);
1476}
1477
1478/// getRValueReferenceType - Return the uniqued reference to the type for an
1479/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001480QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001481 // Unique pointers, to guarantee there is only one pointer of a particular
1482 // structure.
1483 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001484 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001485
1486 void *InsertPos = 0;
1487 if (RValueReferenceType *RT =
1488 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1489 return QualType(RT, 0);
1490
John McCallfc93cf92009-10-22 22:37:11 +00001491 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1492
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001493 // If the referencee type isn't canonical, this won't be a canonical type
1494 // either, so fill in the canonical type field.
1495 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001496 if (InnerRef || !T.isCanonical()) {
1497 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1498 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001499
1500 // Get the new insert position for the node we care about.
1501 RValueReferenceType *NewIP =
1502 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001503 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001504 }
1505
John McCall90d1c2d2009-09-24 23:30:46 +00001506 RValueReferenceType *New
1507 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001508 Types.push_back(New);
1509 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001510 return QualType(New, 0);
1511}
1512
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001513/// getMemberPointerType - Return the uniqued reference to the type for a
1514/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001515QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001516 // Unique pointers, to guarantee there is only one pointer of a particular
1517 // structure.
1518 llvm::FoldingSetNodeID ID;
1519 MemberPointerType::Profile(ID, T, Cls);
1520
1521 void *InsertPos = 0;
1522 if (MemberPointerType *PT =
1523 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1524 return QualType(PT, 0);
1525
1526 // If the pointee or class type isn't canonical, this won't be a canonical
1527 // type either, so fill in the canonical type field.
1528 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001529 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001530 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1531
1532 // Get the new insert position for the node we care about.
1533 MemberPointerType *NewIP =
1534 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001535 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001536 }
John McCall90d1c2d2009-09-24 23:30:46 +00001537 MemberPointerType *New
1538 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001539 Types.push_back(New);
1540 MemberPointerTypes.InsertNode(New, InsertPos);
1541 return QualType(New, 0);
1542}
1543
Mike Stump11289f42009-09-09 15:08:12 +00001544/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001545/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001546QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001547 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001548 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001549 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001550 assert((EltTy->isDependentType() ||
1551 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001552 "Constant array of VLAs is illegal!");
1553
Chris Lattnere2df3f92009-05-13 04:12:56 +00001554 // Convert the array size into a canonical width matching the pointer size for
1555 // the target.
1556 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001557 ArySize =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001558 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001559
Chris Lattner23b7eb62007-06-15 23:05:46 +00001560 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001561 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001562
Chris Lattner36f8e652007-01-27 08:31:04 +00001563 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001564 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001565 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001566 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001567
John McCall33ddac02011-01-19 10:06:00 +00001568 // If the element type isn't canonical or has qualifiers, this won't
1569 // be a canonical type either, so fill in the canonical type field.
1570 QualType Canon;
1571 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1572 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1573 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001574 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001575 Canon = getQualifiedType(Canon, canonSplit.second);
1576
Chris Lattner36f8e652007-01-27 08:31:04 +00001577 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001578 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001579 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001580 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001581 }
Mike Stump11289f42009-09-09 15:08:12 +00001582
John McCall90d1c2d2009-09-24 23:30:46 +00001583 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001584 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001585 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001586 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001587 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001588}
1589
John McCall06549462011-01-18 08:40:38 +00001590/// getVariableArrayDecayedType - Turns the given type, which may be
1591/// variably-modified, into the corresponding type with all the known
1592/// sizes replaced with [*].
1593QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1594 // Vastly most common case.
1595 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001596
John McCall06549462011-01-18 08:40:38 +00001597 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001598
John McCall06549462011-01-18 08:40:38 +00001599 SplitQualType split = type.getSplitDesugaredType();
1600 const Type *ty = split.first;
1601 switch (ty->getTypeClass()) {
1602#define TYPE(Class, Base)
1603#define ABSTRACT_TYPE(Class, Base)
1604#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1605#include "clang/AST/TypeNodes.def"
1606 llvm_unreachable("didn't desugar past all non-canonical types?");
1607
1608 // These types should never be variably-modified.
1609 case Type::Builtin:
1610 case Type::Complex:
1611 case Type::Vector:
1612 case Type::ExtVector:
1613 case Type::DependentSizedExtVector:
1614 case Type::ObjCObject:
1615 case Type::ObjCInterface:
1616 case Type::ObjCObjectPointer:
1617 case Type::Record:
1618 case Type::Enum:
1619 case Type::UnresolvedUsing:
1620 case Type::TypeOfExpr:
1621 case Type::TypeOf:
1622 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001623 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001624 case Type::DependentName:
1625 case Type::InjectedClassName:
1626 case Type::TemplateSpecialization:
1627 case Type::DependentTemplateSpecialization:
1628 case Type::TemplateTypeParm:
1629 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001630 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001631 case Type::PackExpansion:
1632 llvm_unreachable("type should never be variably-modified");
1633
1634 // These types can be variably-modified but should never need to
1635 // further decay.
1636 case Type::FunctionNoProto:
1637 case Type::FunctionProto:
1638 case Type::BlockPointer:
1639 case Type::MemberPointer:
1640 return type;
1641
1642 // These types can be variably-modified. All these modifications
1643 // preserve structure except as noted by comments.
1644 // TODO: if we ever care about optimizing VLAs, there are no-op
1645 // optimizations available here.
1646 case Type::Pointer:
1647 result = getPointerType(getVariableArrayDecayedType(
1648 cast<PointerType>(ty)->getPointeeType()));
1649 break;
1650
1651 case Type::LValueReference: {
1652 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1653 result = getLValueReferenceType(
1654 getVariableArrayDecayedType(lv->getPointeeType()),
1655 lv->isSpelledAsLValue());
1656 break;
1657 }
1658
1659 case Type::RValueReference: {
1660 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1661 result = getRValueReferenceType(
1662 getVariableArrayDecayedType(lv->getPointeeType()));
1663 break;
1664 }
1665
1666 case Type::ConstantArray: {
1667 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1668 result = getConstantArrayType(
1669 getVariableArrayDecayedType(cat->getElementType()),
1670 cat->getSize(),
1671 cat->getSizeModifier(),
1672 cat->getIndexTypeCVRQualifiers());
1673 break;
1674 }
1675
1676 case Type::DependentSizedArray: {
1677 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1678 result = getDependentSizedArrayType(
1679 getVariableArrayDecayedType(dat->getElementType()),
1680 dat->getSizeExpr(),
1681 dat->getSizeModifier(),
1682 dat->getIndexTypeCVRQualifiers(),
1683 dat->getBracketsRange());
1684 break;
1685 }
1686
1687 // Turn incomplete types into [*] types.
1688 case Type::IncompleteArray: {
1689 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1690 result = getVariableArrayType(
1691 getVariableArrayDecayedType(iat->getElementType()),
1692 /*size*/ 0,
1693 ArrayType::Normal,
1694 iat->getIndexTypeCVRQualifiers(),
1695 SourceRange());
1696 break;
1697 }
1698
1699 // Turn VLA types into [*] types.
1700 case Type::VariableArray: {
1701 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1702 result = getVariableArrayType(
1703 getVariableArrayDecayedType(vat->getElementType()),
1704 /*size*/ 0,
1705 ArrayType::Star,
1706 vat->getIndexTypeCVRQualifiers(),
1707 vat->getBracketsRange());
1708 break;
1709 }
1710 }
1711
1712 // Apply the top-level qualifiers from the original.
1713 return getQualifiedType(result, split.second);
1714}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001715
Steve Naroffcadebd02007-08-30 18:14:25 +00001716/// getVariableArrayType - Returns a non-unique reference to the type for a
1717/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001718QualType ASTContext::getVariableArrayType(QualType EltTy,
1719 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001720 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001721 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001722 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001723 // Since we don't unique expressions, it isn't possible to unique VLA's
1724 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001725 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001726
John McCall33ddac02011-01-19 10:06:00 +00001727 // Be sure to pull qualifiers off the element type.
1728 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1729 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1730 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001731 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001732 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001733 }
1734
John McCall90d1c2d2009-09-24 23:30:46 +00001735 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001736 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001737
1738 VariableArrayTypes.push_back(New);
1739 Types.push_back(New);
1740 return QualType(New, 0);
1741}
1742
Douglas Gregor4619e432008-12-05 23:32:09 +00001743/// getDependentSizedArrayType - Returns a non-unique reference to
1744/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001745/// type.
John McCall33ddac02011-01-19 10:06:00 +00001746QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1747 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001748 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001749 unsigned elementTypeQuals,
1750 SourceRange brackets) const {
1751 assert((!numElements || numElements->isTypeDependent() ||
1752 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001753 "Size must be type- or value-dependent!");
1754
John McCall33ddac02011-01-19 10:06:00 +00001755 // Dependently-sized array types that do not have a specified number
1756 // of elements will have their sizes deduced from a dependent
1757 // initializer. We do no canonicalization here at all, which is okay
1758 // because they can't be used in most locations.
1759 if (!numElements) {
1760 DependentSizedArrayType *newType
1761 = new (*this, TypeAlignment)
1762 DependentSizedArrayType(*this, elementType, QualType(),
1763 numElements, ASM, elementTypeQuals,
1764 brackets);
1765 Types.push_back(newType);
1766 return QualType(newType, 0);
1767 }
1768
1769 // Otherwise, we actually build a new type every time, but we
1770 // also build a canonical type.
1771
1772 SplitQualType canonElementType = getCanonicalType(elementType).split();
1773
1774 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001775 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001776 DependentSizedArrayType::Profile(ID, *this,
1777 QualType(canonElementType.first, 0),
1778 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001779
John McCall33ddac02011-01-19 10:06:00 +00001780 // Look for an existing type with these properties.
1781 DependentSizedArrayType *canonTy =
1782 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001783
John McCall33ddac02011-01-19 10:06:00 +00001784 // If we don't have one, build one.
1785 if (!canonTy) {
1786 canonTy = new (*this, TypeAlignment)
1787 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1788 QualType(), numElements, ASM, elementTypeQuals,
1789 brackets);
1790 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1791 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001792 }
1793
John McCall33ddac02011-01-19 10:06:00 +00001794 // Apply qualifiers from the element type to the array.
1795 QualType canon = getQualifiedType(QualType(canonTy,0),
1796 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001797
John McCall33ddac02011-01-19 10:06:00 +00001798 // If we didn't need extra canonicalization for the element type,
1799 // then just use that as our result.
1800 if (QualType(canonElementType.first, 0) == elementType)
1801 return canon;
1802
1803 // Otherwise, we need to build a type which follows the spelling
1804 // of the element type.
1805 DependentSizedArrayType *sugaredType
1806 = new (*this, TypeAlignment)
1807 DependentSizedArrayType(*this, elementType, canon, numElements,
1808 ASM, elementTypeQuals, brackets);
1809 Types.push_back(sugaredType);
1810 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001811}
1812
John McCall33ddac02011-01-19 10:06:00 +00001813QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001814 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001815 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001816 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001817 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001818
John McCall33ddac02011-01-19 10:06:00 +00001819 void *insertPos = 0;
1820 if (IncompleteArrayType *iat =
1821 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1822 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001823
1824 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001825 // either, so fill in the canonical type field. We also have to pull
1826 // qualifiers off the element type.
1827 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001828
John McCall33ddac02011-01-19 10:06:00 +00001829 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1830 SplitQualType canonSplit = getCanonicalType(elementType).split();
1831 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1832 ASM, elementTypeQuals);
1833 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001834
1835 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001836 IncompleteArrayType *existing =
1837 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1838 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001839 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001840
John McCall33ddac02011-01-19 10:06:00 +00001841 IncompleteArrayType *newType = new (*this, TypeAlignment)
1842 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001843
John McCall33ddac02011-01-19 10:06:00 +00001844 IncompleteArrayTypes.InsertNode(newType, insertPos);
1845 Types.push_back(newType);
1846 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001847}
1848
Steve Naroff91fcddb2007-07-18 18:00:27 +00001849/// getVectorType - Return the unique reference to a vector type of
1850/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001851QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001852 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001853 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001854
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001855 // Check if we've already instantiated a vector of this type.
1856 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001857 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001858
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001859 void *InsertPos = 0;
1860 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1861 return QualType(VTP, 0);
1862
1863 // If the element type isn't canonical, this won't be a canonical type either,
1864 // so fill in the canonical type field.
1865 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001866 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001867 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001868
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001869 // Get the new insert position for the node we care about.
1870 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001871 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001872 }
John McCall90d1c2d2009-09-24 23:30:46 +00001873 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001874 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001875 VectorTypes.InsertNode(New, InsertPos);
1876 Types.push_back(New);
1877 return QualType(New, 0);
1878}
1879
Nate Begemance4d7fc2008-04-18 23:10:10 +00001880/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001881/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001882QualType
1883ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00001884 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00001885
Steve Naroff91fcddb2007-07-18 18:00:27 +00001886 // Check if we've already instantiated a vector of this type.
1887 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001888 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001889 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001890 void *InsertPos = 0;
1891 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1892 return QualType(VTP, 0);
1893
1894 // If the element type isn't canonical, this won't be a canonical type either,
1895 // so fill in the canonical type field.
1896 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001897 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001898 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001899
Steve Naroff91fcddb2007-07-18 18:00:27 +00001900 // Get the new insert position for the node we care about.
1901 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001902 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001903 }
John McCall90d1c2d2009-09-24 23:30:46 +00001904 ExtVectorType *New = new (*this, TypeAlignment)
1905 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001906 VectorTypes.InsertNode(New, InsertPos);
1907 Types.push_back(New);
1908 return QualType(New, 0);
1909}
1910
Jay Foad39c79802011-01-12 09:06:06 +00001911QualType
1912ASTContext::getDependentSizedExtVectorType(QualType vecType,
1913 Expr *SizeExpr,
1914 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001915 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001916 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001917 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001918
Douglas Gregor352169a2009-07-31 03:54:25 +00001919 void *InsertPos = 0;
1920 DependentSizedExtVectorType *Canon
1921 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1922 DependentSizedExtVectorType *New;
1923 if (Canon) {
1924 // We already have a canonical version of this array type; use it as
1925 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001926 New = new (*this, TypeAlignment)
1927 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1928 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001929 } else {
1930 QualType CanonVecTy = getCanonicalType(vecType);
1931 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001932 New = new (*this, TypeAlignment)
1933 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1934 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001935
1936 DependentSizedExtVectorType *CanonCheck
1937 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1938 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1939 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001940 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1941 } else {
1942 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1943 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001944 New = new (*this, TypeAlignment)
1945 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001946 }
1947 }
Mike Stump11289f42009-09-09 15:08:12 +00001948
Douglas Gregor758a8692009-06-17 21:51:59 +00001949 Types.push_back(New);
1950 return QualType(New, 0);
1951}
1952
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001953/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001954///
Jay Foad39c79802011-01-12 09:06:06 +00001955QualType
1956ASTContext::getFunctionNoProtoType(QualType ResultTy,
1957 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00001958 const CallingConv DefaultCC = Info.getCC();
1959 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1960 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001961 // Unique functions, to guarantee there is only one function of a particular
1962 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001963 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001964 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001965
Chris Lattner47955de2007-01-27 08:37:20 +00001966 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001967 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001968 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001969 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001970
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001971 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001972 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001973 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001974 Canonical =
1975 getFunctionNoProtoType(getCanonicalType(ResultTy),
1976 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001977
Chris Lattner47955de2007-01-27 08:37:20 +00001978 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001979 FunctionNoProtoType *NewIP =
1980 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001981 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001982 }
Mike Stump11289f42009-09-09 15:08:12 +00001983
Roman Divacky65b88cd2011-03-01 17:40:53 +00001984 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00001985 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00001986 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00001987 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001988 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001989 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001990}
1991
1992/// getFunctionType - Return a normal function type with a typed argument
1993/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001994QualType
1995ASTContext::getFunctionType(QualType ResultTy,
1996 const QualType *ArgArray, unsigned NumArgs,
1997 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001998 // Unique functions, to guarantee there is only one function of a particular
1999 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002000 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002001 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002002
2003 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002004 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002005 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002006 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002007
2008 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002009 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002010 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002011 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002012 isCanonical = false;
2013
Roman Divacky65b88cd2011-03-01 17:40:53 +00002014 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2015 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2016 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002017
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002018 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002019 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002020 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002021 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002022 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002023 CanonicalArgs.reserve(NumArgs);
2024 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002025 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002026
John McCalldb40c7f2010-12-14 08:05:40 +00002027 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002028 CanonicalEPI.ExceptionSpecType = EST_None;
2029 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002030 CanonicalEPI.ExtInfo
2031 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2032
Chris Lattner76a00cf2008-04-06 22:59:24 +00002033 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002034 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002035 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002036
Chris Lattnerfd4de792007-01-27 01:15:32 +00002037 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002038 FunctionProtoType *NewIP =
2039 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002040 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002041 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002042
John McCall31168b02011-06-15 23:02:42 +00002043 // FunctionProtoType objects are allocated with extra bytes after
2044 // them for three variable size arrays at the end:
2045 // - parameter types
2046 // - exception types
2047 // - consumed-arguments flags
2048 // Instead of the exception types, there could be a noexcept
2049 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002050 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002051 NumArgs * sizeof(QualType);
2052 if (EPI.ExceptionSpecType == EST_Dynamic)
2053 Size += EPI.NumExceptions * sizeof(QualType);
2054 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002055 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002056 }
John McCall31168b02011-06-15 23:02:42 +00002057 if (EPI.ConsumedArguments)
2058 Size += NumArgs * sizeof(bool);
2059
John McCalldb40c7f2010-12-14 08:05:40 +00002060 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002061 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2062 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002063 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002064 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002065 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002066 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002067}
Chris Lattneref51c202006-11-10 07:17:23 +00002068
John McCalle78aac42010-03-10 03:28:59 +00002069#ifndef NDEBUG
2070static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2071 if (!isa<CXXRecordDecl>(D)) return false;
2072 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2073 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2074 return true;
2075 if (RD->getDescribedClassTemplate() &&
2076 !isa<ClassTemplateSpecializationDecl>(RD))
2077 return true;
2078 return false;
2079}
2080#endif
2081
2082/// getInjectedClassNameType - Return the unique reference to the
2083/// injected class name type for the specified templated declaration.
2084QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002085 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002086 assert(NeedsInjectedClassNameType(Decl));
2087 if (Decl->TypeForDecl) {
2088 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00002089 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00002090 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2091 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2092 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2093 } else {
John McCall424cec92011-01-19 06:33:43 +00002094 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002095 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002096 Decl->TypeForDecl = newType;
2097 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002098 }
2099 return QualType(Decl->TypeForDecl, 0);
2100}
2101
Douglas Gregor83a586e2008-04-13 21:07:44 +00002102/// getTypeDeclType - Return the unique reference to the type for the
2103/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002104QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002105 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002106 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002107
Richard Smithdda56e42011-04-15 14:24:37 +00002108 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002109 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002110
John McCall96f0b5f2010-03-10 06:48:02 +00002111 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2112 "Template type parameter types are always available.");
2113
John McCall81e38502010-02-16 03:57:14 +00002114 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002115 assert(!Record->getPreviousDeclaration() &&
2116 "struct/union has previous declaration");
2117 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002118 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002119 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002120 assert(!Enum->getPreviousDeclaration() &&
2121 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002122 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002123 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002124 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002125 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2126 Decl->TypeForDecl = newType;
2127 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002128 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002129 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002130
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002131 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002132}
2133
Chris Lattner32d920b2007-01-26 02:01:53 +00002134/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002135/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002136QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002137ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2138 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002139 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002140
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002141 if (Canonical.isNull())
2142 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002143 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002144 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002145 Decl->TypeForDecl = newType;
2146 Types.push_back(newType);
2147 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002148}
2149
Jay Foad39c79802011-01-12 09:06:06 +00002150QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002151 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2152
2153 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2154 if (PrevDecl->TypeForDecl)
2155 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2156
John McCall424cec92011-01-19 06:33:43 +00002157 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2158 Decl->TypeForDecl = newType;
2159 Types.push_back(newType);
2160 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002161}
2162
Jay Foad39c79802011-01-12 09:06:06 +00002163QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002164 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2165
2166 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2167 if (PrevDecl->TypeForDecl)
2168 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2169
John McCall424cec92011-01-19 06:33:43 +00002170 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2171 Decl->TypeForDecl = newType;
2172 Types.push_back(newType);
2173 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002174}
2175
John McCall81904512011-01-06 01:58:22 +00002176QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2177 QualType modifiedType,
2178 QualType equivalentType) {
2179 llvm::FoldingSetNodeID id;
2180 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2181
2182 void *insertPos = 0;
2183 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2184 if (type) return QualType(type, 0);
2185
2186 QualType canon = getCanonicalType(equivalentType);
2187 type = new (*this, TypeAlignment)
2188 AttributedType(canon, attrKind, modifiedType, equivalentType);
2189
2190 Types.push_back(type);
2191 AttributedTypes.InsertNode(type, insertPos);
2192
2193 return QualType(type, 0);
2194}
2195
2196
John McCallcebee162009-10-18 09:09:24 +00002197/// \brief Retrieve a substitution-result type.
2198QualType
2199ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002200 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002201 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002202 && "replacement types must always be canonical");
2203
2204 llvm::FoldingSetNodeID ID;
2205 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2206 void *InsertPos = 0;
2207 SubstTemplateTypeParmType *SubstParm
2208 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2209
2210 if (!SubstParm) {
2211 SubstParm = new (*this, TypeAlignment)
2212 SubstTemplateTypeParmType(Parm, Replacement);
2213 Types.push_back(SubstParm);
2214 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2215 }
2216
2217 return QualType(SubstParm, 0);
2218}
2219
Douglas Gregorada4b792011-01-14 02:55:32 +00002220/// \brief Retrieve a
2221QualType ASTContext::getSubstTemplateTypeParmPackType(
2222 const TemplateTypeParmType *Parm,
2223 const TemplateArgument &ArgPack) {
2224#ifndef NDEBUG
2225 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2226 PEnd = ArgPack.pack_end();
2227 P != PEnd; ++P) {
2228 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2229 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2230 }
2231#endif
2232
2233 llvm::FoldingSetNodeID ID;
2234 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2235 void *InsertPos = 0;
2236 if (SubstTemplateTypeParmPackType *SubstParm
2237 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2238 return QualType(SubstParm, 0);
2239
2240 QualType Canon;
2241 if (!Parm->isCanonicalUnqualified()) {
2242 Canon = getCanonicalType(QualType(Parm, 0));
2243 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2244 ArgPack);
2245 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2246 }
2247
2248 SubstTemplateTypeParmPackType *SubstParm
2249 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2250 ArgPack);
2251 Types.push_back(SubstParm);
2252 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2253 return QualType(SubstParm, 0);
2254}
2255
Douglas Gregoreff93e02009-02-05 23:33:38 +00002256/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002257/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002258/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002259QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002260 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002261 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002262 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002263 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002264 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002265 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002266 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2267
2268 if (TypeParm)
2269 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002270
Chandler Carruth08836322011-05-01 00:51:33 +00002271 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002272 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002273 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002274
2275 TemplateTypeParmType *TypeCheck
2276 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2277 assert(!TypeCheck && "Template type parameter canonical type broken");
2278 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002279 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002280 TypeParm = new (*this, TypeAlignment)
2281 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002282
2283 Types.push_back(TypeParm);
2284 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2285
2286 return QualType(TypeParm, 0);
2287}
2288
John McCalle78aac42010-03-10 03:28:59 +00002289TypeSourceInfo *
2290ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2291 SourceLocation NameLoc,
2292 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002293 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002294 assert(!Name.getAsDependentTemplateName() &&
2295 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002296 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002297
2298 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2299 TemplateSpecializationTypeLoc TL
2300 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2301 TL.setTemplateNameLoc(NameLoc);
2302 TL.setLAngleLoc(Args.getLAngleLoc());
2303 TL.setRAngleLoc(Args.getRAngleLoc());
2304 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2305 TL.setArgLocInfo(i, Args[i].getLocInfo());
2306 return DI;
2307}
2308
Mike Stump11289f42009-09-09 15:08:12 +00002309QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002310ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002311 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002312 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002313 assert(!Template.getAsDependentTemplateName() &&
2314 "No dependent template names here!");
2315
John McCall6b51f282009-11-23 01:53:49 +00002316 unsigned NumArgs = Args.size();
2317
John McCall0ad16662009-10-29 08:12:44 +00002318 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2319 ArgVec.reserve(NumArgs);
2320 for (unsigned i = 0; i != NumArgs; ++i)
2321 ArgVec.push_back(Args[i].getArgument());
2322
John McCall2408e322010-04-27 00:57:59 +00002323 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002324 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002325}
2326
2327QualType
2328ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002329 const TemplateArgument *Args,
2330 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002331 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002332 assert(!Template.getAsDependentTemplateName() &&
2333 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002334 // Look through qualified template names.
2335 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2336 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002337
Richard Smith3f1b5d02011-05-05 21:57:07 +00002338 bool isTypeAlias =
2339 Template.getAsTemplateDecl() &&
2340 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2341
2342 QualType CanonType;
2343 if (!Underlying.isNull())
2344 CanonType = getCanonicalType(Underlying);
2345 else {
2346 assert(!isTypeAlias &&
2347 "Underlying type for template alias must be computed by caller");
2348 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2349 NumArgs);
2350 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002351
Douglas Gregora8e02e72009-07-28 23:00:59 +00002352 // Allocate the (non-canonical) template specialization type, but don't
2353 // try to unique it: these types typically have location information that
2354 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002355 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2356 sizeof(TemplateArgument) * NumArgs +
2357 (isTypeAlias ? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002358 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002359 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002360 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002361 Args, NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002362 CanonType,
2363 isTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002364
Douglas Gregor8bf42052009-02-09 18:46:07 +00002365 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002366 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002367}
2368
Mike Stump11289f42009-09-09 15:08:12 +00002369QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002370ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2371 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002372 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002373 assert(!Template.getAsDependentTemplateName() &&
2374 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002375 assert((!Template.getAsTemplateDecl() ||
2376 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2377 "Underlying type for template alias must be computed by caller");
2378
Douglas Gregore29139c2011-03-03 17:04:51 +00002379 // Look through qualified template names.
2380 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2381 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002382
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002383 // Build the canonical template specialization type.
2384 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2385 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2386 CanonArgs.reserve(NumArgs);
2387 for (unsigned I = 0; I != NumArgs; ++I)
2388 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2389
2390 // Determine whether this canonical template specialization type already
2391 // exists.
2392 llvm::FoldingSetNodeID ID;
2393 TemplateSpecializationType::Profile(ID, CanonTemplate,
2394 CanonArgs.data(), NumArgs, *this);
2395
2396 void *InsertPos = 0;
2397 TemplateSpecializationType *Spec
2398 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2399
2400 if (!Spec) {
2401 // Allocate a new canonical template specialization type.
2402 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2403 sizeof(TemplateArgument) * NumArgs),
2404 TypeAlignment);
2405 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2406 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002407 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002408 Types.push_back(Spec);
2409 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2410 }
2411
2412 assert(Spec->isDependentType() &&
2413 "Non-dependent template-id type must have a canonical type");
2414 return QualType(Spec, 0);
2415}
2416
2417QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002418ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2419 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002420 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002421 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002422 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002423
2424 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002425 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002426 if (T)
2427 return QualType(T, 0);
2428
Douglas Gregorc42075a2010-02-04 18:10:26 +00002429 QualType Canon = NamedType;
2430 if (!Canon.isCanonical()) {
2431 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002432 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2433 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002434 (void)CheckT;
2435 }
2436
Abramo Bagnara6150c882010-05-11 21:36:43 +00002437 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002438 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002439 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002440 return QualType(T, 0);
2441}
2442
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002443QualType
Jay Foad39c79802011-01-12 09:06:06 +00002444ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002445 llvm::FoldingSetNodeID ID;
2446 ParenType::Profile(ID, InnerType);
2447
2448 void *InsertPos = 0;
2449 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2450 if (T)
2451 return QualType(T, 0);
2452
2453 QualType Canon = InnerType;
2454 if (!Canon.isCanonical()) {
2455 Canon = getCanonicalType(InnerType);
2456 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2457 assert(!CheckT && "Paren canonical type broken");
2458 (void)CheckT;
2459 }
2460
2461 T = new (*this) ParenType(InnerType, Canon);
2462 Types.push_back(T);
2463 ParenTypes.InsertNode(T, InsertPos);
2464 return QualType(T, 0);
2465}
2466
Douglas Gregor02085352010-03-31 20:19:30 +00002467QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2468 NestedNameSpecifier *NNS,
2469 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002470 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002471 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2472
2473 if (Canon.isNull()) {
2474 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002475 ElaboratedTypeKeyword CanonKeyword = Keyword;
2476 if (Keyword == ETK_None)
2477 CanonKeyword = ETK_Typename;
2478
2479 if (CanonNNS != NNS || CanonKeyword != Keyword)
2480 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002481 }
2482
2483 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002484 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002485
2486 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002487 DependentNameType *T
2488 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002489 if (T)
2490 return QualType(T, 0);
2491
Douglas Gregor02085352010-03-31 20:19:30 +00002492 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002493 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002494 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002495 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002496}
2497
Mike Stump11289f42009-09-09 15:08:12 +00002498QualType
John McCallc392f372010-06-11 00:33:02 +00002499ASTContext::getDependentTemplateSpecializationType(
2500 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002501 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002502 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002503 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002504 // TODO: avoid this copy
2505 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2506 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2507 ArgCopy.push_back(Args[I].getArgument());
2508 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2509 ArgCopy.size(),
2510 ArgCopy.data());
2511}
2512
2513QualType
2514ASTContext::getDependentTemplateSpecializationType(
2515 ElaboratedTypeKeyword Keyword,
2516 NestedNameSpecifier *NNS,
2517 const IdentifierInfo *Name,
2518 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002519 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002520 assert((!NNS || NNS->isDependent()) &&
2521 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002522
Douglas Gregorc42075a2010-02-04 18:10:26 +00002523 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002524 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2525 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002526
2527 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002528 DependentTemplateSpecializationType *T
2529 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002530 if (T)
2531 return QualType(T, 0);
2532
John McCallc392f372010-06-11 00:33:02 +00002533 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002534
John McCallc392f372010-06-11 00:33:02 +00002535 ElaboratedTypeKeyword CanonKeyword = Keyword;
2536 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2537
2538 bool AnyNonCanonArgs = false;
2539 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2540 for (unsigned I = 0; I != NumArgs; ++I) {
2541 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2542 if (!CanonArgs[I].structurallyEquals(Args[I]))
2543 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002544 }
2545
John McCallc392f372010-06-11 00:33:02 +00002546 QualType Canon;
2547 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2548 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2549 Name, NumArgs,
2550 CanonArgs.data());
2551
2552 // Find the insert position again.
2553 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2554 }
2555
2556 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2557 sizeof(TemplateArgument) * NumArgs),
2558 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002559 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002560 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002561 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002562 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002563 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002564}
2565
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002566QualType ASTContext::getPackExpansionType(QualType Pattern,
2567 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002568 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002569 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002570
2571 assert(Pattern->containsUnexpandedParameterPack() &&
2572 "Pack expansions must expand one or more parameter packs");
2573 void *InsertPos = 0;
2574 PackExpansionType *T
2575 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2576 if (T)
2577 return QualType(T, 0);
2578
2579 QualType Canon;
2580 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002581 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002582
2583 // Find the insert position again.
2584 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2585 }
2586
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002587 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002588 Types.push_back(T);
2589 PackExpansionTypes.InsertNode(T, InsertPos);
2590 return QualType(T, 0);
2591}
2592
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002593/// CmpProtocolNames - Comparison predicate for sorting protocols
2594/// alphabetically.
2595static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2596 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002597 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002598}
2599
John McCall8b07ec22010-05-15 11:32:37 +00002600static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002601 unsigned NumProtocols) {
2602 if (NumProtocols == 0) return true;
2603
2604 for (unsigned i = 1; i != NumProtocols; ++i)
2605 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2606 return false;
2607 return true;
2608}
2609
2610static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002611 unsigned &NumProtocols) {
2612 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002613
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002614 // Sort protocols, keyed by name.
2615 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2616
2617 // Remove duplicates.
2618 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2619 NumProtocols = ProtocolsEnd-Protocols;
2620}
2621
John McCall8b07ec22010-05-15 11:32:37 +00002622QualType ASTContext::getObjCObjectType(QualType BaseType,
2623 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002624 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002625 // If the base type is an interface and there aren't any protocols
2626 // to add, then the interface type will do just fine.
2627 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2628 return BaseType;
2629
2630 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002631 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002632 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002633 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002634 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2635 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002636
John McCall8b07ec22010-05-15 11:32:37 +00002637 // Build the canonical type, which has the canonical base type and
2638 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002639 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002640 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2641 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2642 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002643 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2644 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002645 unsigned UniqueCount = NumProtocols;
2646
John McCallfc93cf92009-10-22 22:37:11 +00002647 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002648 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2649 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002650 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002651 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2652 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002653 }
2654
2655 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002656 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2657 }
2658
2659 unsigned Size = sizeof(ObjCObjectTypeImpl);
2660 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2661 void *Mem = Allocate(Size, TypeAlignment);
2662 ObjCObjectTypeImpl *T =
2663 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2664
2665 Types.push_back(T);
2666 ObjCObjectTypes.InsertNode(T, InsertPos);
2667 return QualType(T, 0);
2668}
2669
2670/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2671/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002672QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002673 llvm::FoldingSetNodeID ID;
2674 ObjCObjectPointerType::Profile(ID, ObjectT);
2675
2676 void *InsertPos = 0;
2677 if (ObjCObjectPointerType *QT =
2678 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2679 return QualType(QT, 0);
2680
2681 // Find the canonical object type.
2682 QualType Canonical;
2683 if (!ObjectT.isCanonical()) {
2684 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2685
2686 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002687 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2688 }
2689
Douglas Gregorf85bee62010-02-08 22:59:26 +00002690 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002691 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2692 ObjCObjectPointerType *QType =
2693 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002694
Steve Narofffb4330f2009-06-17 22:40:22 +00002695 Types.push_back(QType);
2696 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002697 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002698}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002699
Douglas Gregor1c283312010-08-11 12:19:30 +00002700/// getObjCInterfaceType - Return the unique reference to the type for the
2701/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002702QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002703 if (Decl->TypeForDecl)
2704 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002705
Douglas Gregor1c283312010-08-11 12:19:30 +00002706 // FIXME: redeclarations?
2707 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2708 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2709 Decl->TypeForDecl = T;
2710 Types.push_back(T);
2711 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002712}
2713
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002714/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2715/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002716/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002717/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002718/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002719QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002720 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002721 if (tofExpr->isTypeDependent()) {
2722 llvm::FoldingSetNodeID ID;
2723 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002724
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002725 void *InsertPos = 0;
2726 DependentTypeOfExprType *Canon
2727 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2728 if (Canon) {
2729 // We already have a "canonical" version of an identical, dependent
2730 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002731 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002732 QualType((TypeOfExprType*)Canon, 0));
2733 }
2734 else {
2735 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002736 Canon
2737 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002738 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2739 toe = Canon;
2740 }
2741 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002742 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002743 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002744 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002745 Types.push_back(toe);
2746 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002747}
2748
Steve Naroffa773cd52007-08-01 18:02:17 +00002749/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2750/// TypeOfType AST's. The only motivation to unique these nodes would be
2751/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002752/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002753/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002754QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002755 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002756 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002757 Types.push_back(tot);
2758 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002759}
2760
Anders Carlssonad6bd352009-06-24 21:24:56 +00002761/// getDecltypeForExpr - Given an expr, will return the decltype for that
2762/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002763static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002764 if (e->isTypeDependent())
2765 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002766
Anders Carlssonad6bd352009-06-24 21:24:56 +00002767 // If e is an id expression or a class member access, decltype(e) is defined
2768 // as the type of the entity named by e.
2769 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2770 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2771 return VD->getType();
2772 }
2773 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2774 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2775 return FD->getType();
2776 }
2777 // If e is a function call or an invocation of an overloaded operator,
2778 // (parentheses around e are ignored), decltype(e) is defined as the
2779 // return type of that function.
2780 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2781 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002782
Anders Carlssonad6bd352009-06-24 21:24:56 +00002783 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002784
2785 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002786 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002787 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002788 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002789
Anders Carlssonad6bd352009-06-24 21:24:56 +00002790 return T;
2791}
2792
Anders Carlsson81df7b82009-06-24 19:06:50 +00002793/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2794/// DecltypeType AST's. The only motivation to unique these nodes would be
2795/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002796/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002797/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002798QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002799 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002800 if (e->isTypeDependent()) {
2801 llvm::FoldingSetNodeID ID;
2802 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002803
Douglas Gregora21f6c32009-07-30 23:36:40 +00002804 void *InsertPos = 0;
2805 DependentDecltypeType *Canon
2806 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2807 if (Canon) {
2808 // We already have a "canonical" version of an equivalent, dependent
2809 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002810 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002811 QualType((DecltypeType*)Canon, 0));
2812 }
2813 else {
2814 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002815 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002816 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2817 dt = Canon;
2818 }
2819 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002820 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002821 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002822 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002823 Types.push_back(dt);
2824 return QualType(dt, 0);
2825}
2826
Alexis Hunte852b102011-05-24 22:41:36 +00002827/// getUnaryTransformationType - We don't unique these, since the memory
2828/// savings are minimal and these are rare.
2829QualType ASTContext::getUnaryTransformType(QualType BaseType,
2830 QualType UnderlyingType,
2831 UnaryTransformType::UTTKind Kind)
2832 const {
2833 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002834 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2835 Kind,
2836 UnderlyingType->isDependentType() ?
2837 QualType() : UnderlyingType);
Alexis Hunte852b102011-05-24 22:41:36 +00002838 Types.push_back(Ty);
2839 return QualType(Ty, 0);
2840}
2841
Richard Smithb2bc2e62011-02-21 20:05:19 +00002842/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002843QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002844 void *InsertPos = 0;
2845 if (!DeducedType.isNull()) {
2846 // Look in the folding set for an existing type.
2847 llvm::FoldingSetNodeID ID;
2848 AutoType::Profile(ID, DeducedType);
2849 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2850 return QualType(AT, 0);
2851 }
2852
2853 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2854 Types.push_back(AT);
2855 if (InsertPos)
2856 AutoTypes.InsertNode(AT, InsertPos);
2857 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002858}
2859
Richard Smith02e85f32011-04-14 22:09:26 +00002860/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2861QualType ASTContext::getAutoDeductType() const {
2862 if (AutoDeductTy.isNull())
2863 AutoDeductTy = getAutoType(QualType());
2864 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2865 return AutoDeductTy;
2866}
2867
2868/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2869QualType ASTContext::getAutoRRefDeductType() const {
2870 if (AutoRRefDeductTy.isNull())
2871 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2872 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2873 return AutoRRefDeductTy;
2874}
2875
Chris Lattnerfb072462007-01-23 05:45:31 +00002876/// getTagDeclType - Return the unique reference to the type for the
2877/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002878QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002879 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002880 // FIXME: What is the design on getTagDeclType when it requires casting
2881 // away const? mutable?
2882 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002883}
2884
Mike Stump11289f42009-09-09 15:08:12 +00002885/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2886/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2887/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002888CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002889 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002890}
Chris Lattnerfb072462007-01-23 05:45:31 +00002891
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002892/// getSignedWCharType - Return the type of "signed wchar_t".
2893/// Used when in C++, as a GCC extension.
2894QualType ASTContext::getSignedWCharType() const {
2895 // FIXME: derive from "Target" ?
2896 return WCharTy;
2897}
2898
2899/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2900/// Used when in C++, as a GCC extension.
2901QualType ASTContext::getUnsignedWCharType() const {
2902 // FIXME: derive from "Target" ?
2903 return UnsignedIntTy;
2904}
2905
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002906/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2907/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2908QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002909 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002910}
2911
Chris Lattnera21ad802008-04-02 05:18:44 +00002912//===----------------------------------------------------------------------===//
2913// Type Operators
2914//===----------------------------------------------------------------------===//
2915
Jay Foad39c79802011-01-12 09:06:06 +00002916CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002917 // Push qualifiers into arrays, and then discard any remaining
2918 // qualifiers.
2919 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002920 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002921 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002922 QualType Result;
2923 if (isa<ArrayType>(Ty)) {
2924 Result = getArrayDecayedType(QualType(Ty,0));
2925 } else if (isa<FunctionType>(Ty)) {
2926 Result = getPointerType(QualType(Ty, 0));
2927 } else {
2928 Result = QualType(Ty, 0);
2929 }
2930
2931 return CanQualType::CreateUnsafe(Result);
2932}
2933
John McCall6c9dd522011-01-18 07:41:22 +00002934QualType ASTContext::getUnqualifiedArrayType(QualType type,
2935 Qualifiers &quals) {
2936 SplitQualType splitType = type.getSplitUnqualifiedType();
2937
2938 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2939 // the unqualified desugared type and then drops it on the floor.
2940 // We then have to strip that sugar back off with
2941 // getUnqualifiedDesugaredType(), which is silly.
2942 const ArrayType *AT =
2943 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2944
2945 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002946 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002947 quals = splitType.second;
2948 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002949 }
2950
John McCall6c9dd522011-01-18 07:41:22 +00002951 // Otherwise, recurse on the array's element type.
2952 QualType elementType = AT->getElementType();
2953 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2954
2955 // If that didn't change the element type, AT has no qualifiers, so we
2956 // can just use the results in splitType.
2957 if (elementType == unqualElementType) {
2958 assert(quals.empty()); // from the recursive call
2959 quals = splitType.second;
2960 return QualType(splitType.first, 0);
2961 }
2962
2963 // Otherwise, add in the qualifiers from the outermost type, then
2964 // build the type back up.
2965 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002966
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002967 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002968 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002969 CAT->getSizeModifier(), 0);
2970 }
2971
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002972 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002973 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002974 }
2975
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002976 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002977 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002978 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002979 VAT->getSizeModifier(),
2980 VAT->getIndexTypeCVRQualifiers(),
2981 VAT->getBracketsRange());
2982 }
2983
2984 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00002985 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002986 DSAT->getSizeModifier(), 0,
2987 SourceRange());
2988}
2989
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002990/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2991/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2992/// they point to and return true. If T1 and T2 aren't pointer types
2993/// or pointer-to-member types, or if they are not similar at this
2994/// level, returns false and leaves T1 and T2 unchanged. Top-level
2995/// qualifiers on T1 and T2 are ignored. This function will typically
2996/// be called in a loop that successively "unwraps" pointer and
2997/// pointer-to-member types to compare them at each level.
2998bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2999 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3000 *T2PtrType = T2->getAs<PointerType>();
3001 if (T1PtrType && T2PtrType) {
3002 T1 = T1PtrType->getPointeeType();
3003 T2 = T2PtrType->getPointeeType();
3004 return true;
3005 }
3006
3007 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3008 *T2MPType = T2->getAs<MemberPointerType>();
3009 if (T1MPType && T2MPType &&
3010 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3011 QualType(T2MPType->getClass(), 0))) {
3012 T1 = T1MPType->getPointeeType();
3013 T2 = T2MPType->getPointeeType();
3014 return true;
3015 }
3016
3017 if (getLangOptions().ObjC1) {
3018 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3019 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3020 if (T1OPType && T2OPType) {
3021 T1 = T1OPType->getPointeeType();
3022 T2 = T2OPType->getPointeeType();
3023 return true;
3024 }
3025 }
3026
3027 // FIXME: Block pointers, too?
3028
3029 return false;
3030}
3031
Jay Foad39c79802011-01-12 09:06:06 +00003032DeclarationNameInfo
3033ASTContext::getNameForTemplate(TemplateName Name,
3034 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00003035 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003036 // DNInfo work in progress: CHECKME: what about DNLoc?
3037 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
3038
John McCall847e2a12009-11-24 18:42:40 +00003039 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003040 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003041 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003042 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3043 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003044 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003045 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3046 // DNInfo work in progress: FIXME: source locations?
3047 DeclarationNameLoc DNLoc;
3048 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3049 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3050 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003051 }
3052 }
3053
John McCalld28ae272009-12-02 08:04:21 +00003054 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3055 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003056 // DNInfo work in progress: CHECKME: what about DNLoc?
3057 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003058}
3059
Jay Foad39c79802011-01-12 09:06:06 +00003060TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003061 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3062 if (TemplateTemplateParmDecl *TTP
3063 = dyn_cast<TemplateTemplateParmDecl>(Template))
3064 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3065
3066 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003067 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003068 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003069
Douglas Gregor5590be02011-01-15 06:45:20 +00003070 if (SubstTemplateTemplateParmPackStorage *SubstPack
3071 = Name.getAsSubstTemplateTemplateParmPack()) {
3072 TemplateTemplateParmDecl *CanonParam
3073 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
3074 TemplateArgument CanonArgPack
3075 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
3076 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
3077 }
3078
John McCalld28ae272009-12-02 08:04:21 +00003079 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00003080
Douglas Gregor6bc50582009-05-07 06:41:52 +00003081 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3082 assert(DTN && "Non-dependent template names must refer to template decls.");
3083 return DTN->CanonicalTemplateName;
3084}
3085
Douglas Gregoradee3e32009-11-11 23:06:43 +00003086bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3087 X = getCanonicalTemplateName(X);
3088 Y = getCanonicalTemplateName(Y);
3089 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3090}
3091
Mike Stump11289f42009-09-09 15:08:12 +00003092TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003093ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003094 switch (Arg.getKind()) {
3095 case TemplateArgument::Null:
3096 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003097
Douglas Gregora8e02e72009-07-28 23:00:59 +00003098 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003099 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003100
Douglas Gregora8e02e72009-07-28 23:00:59 +00003101 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003102 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003103
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003104 case TemplateArgument::Template:
3105 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003106
3107 case TemplateArgument::TemplateExpansion:
3108 return TemplateArgument(getCanonicalTemplateName(
3109 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003110 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003111
Douglas Gregora8e02e72009-07-28 23:00:59 +00003112 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003113 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003114 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003115
Douglas Gregora8e02e72009-07-28 23:00:59 +00003116 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003117 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003118
Douglas Gregora8e02e72009-07-28 23:00:59 +00003119 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003120 if (Arg.pack_size() == 0)
3121 return Arg;
3122
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003123 TemplateArgument *CanonArgs
3124 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003125 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003126 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003127 AEnd = Arg.pack_end();
3128 A != AEnd; (void)++A, ++Idx)
3129 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003130
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003131 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003132 }
3133 }
3134
3135 // Silence GCC warning
3136 assert(false && "Unhandled template argument kind");
3137 return TemplateArgument();
3138}
3139
Douglas Gregor333489b2009-03-27 23:10:48 +00003140NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003141ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003142 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003143 return 0;
3144
3145 switch (NNS->getKind()) {
3146 case NestedNameSpecifier::Identifier:
3147 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003148 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003149 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3150 NNS->getAsIdentifier());
3151
3152 case NestedNameSpecifier::Namespace:
3153 // A namespace is canonical; build a nested-name-specifier with
3154 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003155 return NestedNameSpecifier::Create(*this, 0,
3156 NNS->getAsNamespace()->getOriginalNamespace());
3157
3158 case NestedNameSpecifier::NamespaceAlias:
3159 // A namespace is canonical; build a nested-name-specifier with
3160 // this namespace and no prefix.
3161 return NestedNameSpecifier::Create(*this, 0,
3162 NNS->getAsNamespaceAlias()->getNamespace()
3163 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003164
3165 case NestedNameSpecifier::TypeSpec:
3166 case NestedNameSpecifier::TypeSpecWithTemplate: {
3167 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003168
3169 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3170 // break it apart into its prefix and identifier, then reconsititute those
3171 // as the canonical nested-name-specifier. This is required to canonicalize
3172 // a dependent nested-name-specifier involving typedefs of dependent-name
3173 // types, e.g.,
3174 // typedef typename T::type T1;
3175 // typedef typename T1::type T2;
3176 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3177 NestedNameSpecifier *Prefix
3178 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3179 return NestedNameSpecifier::Create(*this, Prefix,
3180 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3181 }
3182
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003183 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003184 if (const DependentTemplateSpecializationType *DTST
3185 = T->getAs<DependentTemplateSpecializationType>()) {
3186 NestedNameSpecifier *Prefix
3187 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003188
3189 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3190 Prefix, DTST->getIdentifier(),
3191 DTST->getNumArgs(),
3192 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003193 T = getCanonicalType(T);
3194 }
3195
John McCall33ddac02011-01-19 10:06:00 +00003196 return NestedNameSpecifier::Create(*this, 0, false,
3197 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003198 }
3199
3200 case NestedNameSpecifier::Global:
3201 // The global specifier is canonical and unique.
3202 return NNS;
3203 }
3204
3205 // Required to silence a GCC warning
3206 return 0;
3207}
3208
Chris Lattner7adf0762008-08-04 07:31:14 +00003209
Jay Foad39c79802011-01-12 09:06:06 +00003210const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003211 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003212 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003213 // Handle the common positive case fast.
3214 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3215 return AT;
3216 }
Mike Stump11289f42009-09-09 15:08:12 +00003217
John McCall8ccfcb52009-09-24 19:53:00 +00003218 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003219 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003220 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003221
John McCall8ccfcb52009-09-24 19:53:00 +00003222 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003223 // implements C99 6.7.3p8: "If the specification of an array type includes
3224 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003225
Chris Lattner7adf0762008-08-04 07:31:14 +00003226 // If we get here, we either have type qualifiers on the type, or we have
3227 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003228 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003229
John McCall33ddac02011-01-19 10:06:00 +00003230 SplitQualType split = T.getSplitDesugaredType();
3231 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003232
Chris Lattner7adf0762008-08-04 07:31:14 +00003233 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003234 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3235 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003236 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003237
Chris Lattner7adf0762008-08-04 07:31:14 +00003238 // Otherwise, we have an array and we have qualifiers on it. Push the
3239 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003240 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003241
Chris Lattner7adf0762008-08-04 07:31:14 +00003242 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3243 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3244 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003245 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003246 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3247 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3248 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003249 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003250
Mike Stump11289f42009-09-09 15:08:12 +00003251 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003252 = dyn_cast<DependentSizedArrayType>(ATy))
3253 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003254 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003255 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003256 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003257 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003258 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003259
Chris Lattner7adf0762008-08-04 07:31:14 +00003260 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003261 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003262 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003263 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003264 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003265 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003266}
3267
Chris Lattnera21ad802008-04-02 05:18:44 +00003268/// getArrayDecayedType - Return the properly qualified result of decaying the
3269/// specified array type to a pointer. This operation is non-trivial when
3270/// handling typedefs etc. The canonical type of "T" must be an array type,
3271/// this returns a pointer to a properly qualified element of the array.
3272///
3273/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003274QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003275 // Get the element type with 'getAsArrayType' so that we don't lose any
3276 // typedefs in the element type of the array. This also handles propagation
3277 // of type qualifiers from the array type into the element type if present
3278 // (C99 6.7.3p8).
3279 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3280 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003281
Chris Lattner7adf0762008-08-04 07:31:14 +00003282 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003283
3284 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003285 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003286}
3287
John McCall33ddac02011-01-19 10:06:00 +00003288QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3289 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003290}
3291
John McCall33ddac02011-01-19 10:06:00 +00003292QualType ASTContext::getBaseElementType(QualType type) const {
3293 Qualifiers qs;
3294 while (true) {
3295 SplitQualType split = type.getSplitDesugaredType();
3296 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3297 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003298
John McCall33ddac02011-01-19 10:06:00 +00003299 type = array->getElementType();
3300 qs.addConsistentQualifiers(split.second);
3301 }
Mike Stump11289f42009-09-09 15:08:12 +00003302
John McCall33ddac02011-01-19 10:06:00 +00003303 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003304}
3305
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003306/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003307uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003308ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3309 uint64_t ElementCount = 1;
3310 do {
3311 ElementCount *= CA->getSize().getZExtValue();
3312 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3313 } while (CA);
3314 return ElementCount;
3315}
3316
Steve Naroff0af91202007-04-27 21:51:21 +00003317/// getFloatingRank - Return a relative rank for floating point types.
3318/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003319static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003320 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003321 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003322
John McCall9dd450b2009-09-21 23:43:11 +00003323 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3324 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003325 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003326 case BuiltinType::Float: return FloatRank;
3327 case BuiltinType::Double: return DoubleRank;
3328 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003329 }
3330}
3331
Mike Stump11289f42009-09-09 15:08:12 +00003332/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3333/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003334/// 'typeDomain' is a real floating point or complex type.
3335/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003336QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3337 QualType Domain) const {
3338 FloatingRank EltRank = getFloatingRank(Size);
3339 if (Domain->isComplexType()) {
3340 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003341 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003342 case FloatRank: return FloatComplexTy;
3343 case DoubleRank: return DoubleComplexTy;
3344 case LongDoubleRank: return LongDoubleComplexTy;
3345 }
Steve Naroff0af91202007-04-27 21:51:21 +00003346 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003347
3348 assert(Domain->isRealFloatingType() && "Unknown domain!");
3349 switch (EltRank) {
3350 default: assert(0 && "getFloatingRank(): illegal value for rank");
3351 case FloatRank: return FloatTy;
3352 case DoubleRank: return DoubleTy;
3353 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003354 }
Steve Naroffe4718892007-04-27 18:30:00 +00003355}
3356
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003357/// getFloatingTypeOrder - Compare the rank of the two specified floating
3358/// point types, ignoring the domain of the type (i.e. 'double' ==
3359/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003360/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003361int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003362 FloatingRank LHSR = getFloatingRank(LHS);
3363 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003364
Chris Lattnerb90739d2008-04-06 23:38:49 +00003365 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003366 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003367 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003368 return 1;
3369 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003370}
3371
Chris Lattner76a00cf2008-04-06 22:59:24 +00003372/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3373/// routine will assert if passed a built-in type that isn't an integer or enum,
3374/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003375unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003376 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003377 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003378 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003379
Chris Lattnerad3467e2010-12-25 23:25:43 +00003380 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3381 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003382 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3383
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003384 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3385 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3386
3387 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3388 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3389
Chris Lattner76a00cf2008-04-06 22:59:24 +00003390 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003391 default: assert(0 && "getIntegerRank(): not a built-in integer");
3392 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003393 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003394 case BuiltinType::Char_S:
3395 case BuiltinType::Char_U:
3396 case BuiltinType::SChar:
3397 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003398 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003399 case BuiltinType::Short:
3400 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003401 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003402 case BuiltinType::Int:
3403 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003404 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003405 case BuiltinType::Long:
3406 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003407 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003408 case BuiltinType::LongLong:
3409 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003410 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003411 case BuiltinType::Int128:
3412 case BuiltinType::UInt128:
3413 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003414 }
3415}
3416
Eli Friedman629ffb92009-08-20 04:21:42 +00003417/// \brief Whether this is a promotable bitfield reference according
3418/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3419///
3420/// \returns the type this bit-field will promote to, or NULL if no
3421/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003422QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003423 if (E->isTypeDependent() || E->isValueDependent())
3424 return QualType();
3425
Eli Friedman629ffb92009-08-20 04:21:42 +00003426 FieldDecl *Field = E->getBitField();
3427 if (!Field)
3428 return QualType();
3429
3430 QualType FT = Field->getType();
3431
3432 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3433 uint64_t BitWidth = BitWidthAP.getZExtValue();
3434 uint64_t IntSize = getTypeSize(IntTy);
3435 // GCC extension compatibility: if the bit-field size is less than or equal
3436 // to the size of int, it gets promoted no matter what its type is.
3437 // For instance, unsigned long bf : 4 gets promoted to signed int.
3438 if (BitWidth < IntSize)
3439 return IntTy;
3440
3441 if (BitWidth == IntSize)
3442 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3443
3444 // Types bigger than int are not subject to promotions, and therefore act
3445 // like the base type.
3446 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3447 // is ridiculous.
3448 return QualType();
3449}
3450
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003451/// getPromotedIntegerType - Returns the type that Promotable will
3452/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3453/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003454QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003455 assert(!Promotable.isNull());
3456 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003457 if (const EnumType *ET = Promotable->getAs<EnumType>())
3458 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003459 if (Promotable->isSignedIntegerType())
3460 return IntTy;
3461 uint64_t PromotableSize = getTypeSize(Promotable);
3462 uint64_t IntSize = getTypeSize(IntTy);
3463 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3464 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3465}
3466
Mike Stump11289f42009-09-09 15:08:12 +00003467/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003468/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003469/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003470int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003471 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3472 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003473 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003474
Chris Lattner76a00cf2008-04-06 22:59:24 +00003475 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3476 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003477
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003478 unsigned LHSRank = getIntegerRank(LHSC);
3479 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003480
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003481 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3482 if (LHSRank == RHSRank) return 0;
3483 return LHSRank > RHSRank ? 1 : -1;
3484 }
Mike Stump11289f42009-09-09 15:08:12 +00003485
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003486 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3487 if (LHSUnsigned) {
3488 // If the unsigned [LHS] type is larger, return it.
3489 if (LHSRank >= RHSRank)
3490 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003491
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003492 // If the signed type can represent all values of the unsigned type, it
3493 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003494 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003495 return -1;
3496 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003497
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003498 // If the unsigned [RHS] type is larger, return it.
3499 if (RHSRank >= LHSRank)
3500 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003501
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003502 // If the signed type can represent all values of the unsigned type, it
3503 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003504 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003505 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003506}
Anders Carlsson98f07902007-08-17 05:31:46 +00003507
Anders Carlsson6d417272009-11-14 21:45:58 +00003508static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003509CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3510 DeclContext *DC, IdentifierInfo *Id) {
3511 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003512 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003513 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003514 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003515 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003516}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003517
Mike Stump11289f42009-09-09 15:08:12 +00003518// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003519QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003520 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003521 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003522 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003523 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003524 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003525
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003526 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003527
Anders Carlsson98f07902007-08-17 05:31:46 +00003528 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003529 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003530 // int flags;
3531 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003532 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003533 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003534 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003535 FieldTypes[3] = LongTy;
3536
Anders Carlsson98f07902007-08-17 05:31:46 +00003537 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003538 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003539 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003540 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003541 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003542 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003543 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003544 /*Mutable=*/false,
3545 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003546 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003547 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003548 }
3549
Douglas Gregord5058122010-02-11 01:19:42 +00003550 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003551 }
Mike Stump11289f42009-09-09 15:08:12 +00003552
Anders Carlsson98f07902007-08-17 05:31:46 +00003553 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003554}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003555
Douglas Gregor512b0772009-04-23 22:29:11 +00003556void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003557 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003558 assert(Rec && "Invalid CFConstantStringType");
3559 CFConstantStringTypeDecl = Rec->getDecl();
3560}
3561
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003562// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003563QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003564 if (!NSConstantStringTypeDecl) {
3565 NSConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003566 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003567 &Idents.get("__builtin_NSString"));
3568 NSConstantStringTypeDecl->startDefinition();
3569
3570 QualType FieldTypes[3];
3571
3572 // const int *isa;
3573 FieldTypes[0] = getPointerType(IntTy.withConst());
3574 // const char *str;
3575 FieldTypes[1] = getPointerType(CharTy.withConst());
3576 // unsigned int length;
3577 FieldTypes[2] = UnsignedIntTy;
3578
3579 // Create fields
3580 for (unsigned i = 0; i < 3; ++i) {
3581 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003582 SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003583 SourceLocation(), 0,
3584 FieldTypes[i], /*TInfo=*/0,
3585 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003586 /*Mutable=*/false,
3587 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003588 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003589 NSConstantStringTypeDecl->addDecl(Field);
3590 }
3591
3592 NSConstantStringTypeDecl->completeDefinition();
3593 }
3594
3595 return getTagDeclType(NSConstantStringTypeDecl);
3596}
3597
3598void ASTContext::setNSConstantStringType(QualType T) {
3599 const RecordType *Rec = T->getAs<RecordType>();
3600 assert(Rec && "Invalid NSConstantStringType");
3601 NSConstantStringTypeDecl = Rec->getDecl();
3602}
3603
Jay Foad39c79802011-01-12 09:06:06 +00003604QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003605 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003606 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003607 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003608 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003609 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003610
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003611 QualType FieldTypes[] = {
3612 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003613 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003614 getPointerType(UnsignedLongTy),
3615 getConstantArrayType(UnsignedLongTy,
3616 llvm::APInt(32, 5), ArrayType::Normal, 0)
3617 };
Mike Stump11289f42009-09-09 15:08:12 +00003618
Douglas Gregor91f84212008-12-11 16:49:14 +00003619 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003620 FieldDecl *Field = FieldDecl::Create(*this,
3621 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003622 SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003623 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003624 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003625 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003626 /*Mutable=*/false,
3627 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003628 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003629 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003630 }
Mike Stump11289f42009-09-09 15:08:12 +00003631
Douglas Gregord5058122010-02-11 01:19:42 +00003632 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003633 }
Mike Stump11289f42009-09-09 15:08:12 +00003634
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003635 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3636}
3637
Jay Foad39c79802011-01-12 09:06:06 +00003638QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003639 if (BlockDescriptorType)
3640 return getTagDeclType(BlockDescriptorType);
3641
3642 RecordDecl *T;
3643 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003644 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003645 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003646 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003647
3648 QualType FieldTypes[] = {
3649 UnsignedLongTy,
3650 UnsignedLongTy,
3651 };
3652
3653 const char *FieldNames[] = {
3654 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003655 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003656 };
3657
3658 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003659 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003660 SourceLocation(),
3661 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003662 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003663 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003664 /*Mutable=*/false,
3665 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003666 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003667 T->addDecl(Field);
3668 }
3669
Douglas Gregord5058122010-02-11 01:19:42 +00003670 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003671
3672 BlockDescriptorType = T;
3673
3674 return getTagDeclType(BlockDescriptorType);
3675}
3676
3677void ASTContext::setBlockDescriptorType(QualType T) {
3678 const RecordType *Rec = T->getAs<RecordType>();
3679 assert(Rec && "Invalid BlockDescriptorType");
3680 BlockDescriptorType = Rec->getDecl();
3681}
3682
Jay Foad39c79802011-01-12 09:06:06 +00003683QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003684 if (BlockDescriptorExtendedType)
3685 return getTagDeclType(BlockDescriptorExtendedType);
3686
3687 RecordDecl *T;
3688 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003689 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003690 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003691 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003692
3693 QualType FieldTypes[] = {
3694 UnsignedLongTy,
3695 UnsignedLongTy,
3696 getPointerType(VoidPtrTy),
3697 getPointerType(VoidPtrTy)
3698 };
3699
3700 const char *FieldNames[] = {
3701 "reserved",
3702 "Size",
3703 "CopyFuncPtr",
3704 "DestroyFuncPtr"
3705 };
3706
3707 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003708 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003709 SourceLocation(),
3710 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003711 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003712 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003713 /*Mutable=*/false,
3714 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003715 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003716 T->addDecl(Field);
3717 }
3718
Douglas Gregord5058122010-02-11 01:19:42 +00003719 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003720
3721 BlockDescriptorExtendedType = T;
3722
3723 return getTagDeclType(BlockDescriptorExtendedType);
3724}
3725
3726void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3727 const RecordType *Rec = T->getAs<RecordType>();
3728 assert(Rec && "Invalid BlockDescriptorType");
3729 BlockDescriptorExtendedType = Rec->getDecl();
3730}
3731
Jay Foad39c79802011-01-12 09:06:06 +00003732bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003733 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003734 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003735 if (getLangOptions().CPlusPlus) {
3736 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3737 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003738 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003739
3740 }
3741 }
Mike Stump94967902009-10-21 18:16:27 +00003742 return false;
3743}
3744
Jay Foad39c79802011-01-12 09:06:06 +00003745QualType
3746ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003747 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003748 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003749 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003750 // unsigned int __flags;
3751 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003752 // void *__copy_helper; // as needed
3753 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003754 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003755 // } *
3756
Mike Stump94967902009-10-21 18:16:27 +00003757 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3758
3759 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003760 llvm::SmallString<36> Name;
3761 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3762 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003763 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003764 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003765 T->startDefinition();
3766 QualType Int32Ty = IntTy;
3767 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3768 QualType FieldTypes[] = {
3769 getPointerType(VoidPtrTy),
3770 getPointerType(getTagDeclType(T)),
3771 Int32Ty,
3772 Int32Ty,
3773 getPointerType(VoidPtrTy),
3774 getPointerType(VoidPtrTy),
3775 Ty
3776 };
3777
Daniel Dunbar56df9772010-08-17 22:39:59 +00003778 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003779 "__isa",
3780 "__forwarding",
3781 "__flags",
3782 "__size",
3783 "__copy_helper",
3784 "__destroy_helper",
3785 DeclName,
3786 };
3787
3788 for (size_t i = 0; i < 7; ++i) {
3789 if (!HasCopyAndDispose && i >=4 && i <= 5)
3790 continue;
3791 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003792 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003793 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003794 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003795 /*BitWidth=*/0, /*Mutable=*/false,
3796 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003797 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003798 T->addDecl(Field);
3799 }
3800
Douglas Gregord5058122010-02-11 01:19:42 +00003801 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003802
3803 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003804}
3805
Douglas Gregor512b0772009-04-23 22:29:11 +00003806void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003807 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003808 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3809 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3810}
3811
Anders Carlsson18acd442007-10-29 06:33:42 +00003812// This returns true if a type has been typedefed to BOOL:
3813// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003814static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003815 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003816 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3817 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003818
Anders Carlssond8499822007-10-29 05:01:08 +00003819 return false;
3820}
3821
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003822/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003823/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003824CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00003825 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3826 return CharUnits::Zero();
3827
Ken Dyck40775002010-01-11 17:06:35 +00003828 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003829
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003830 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003831 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003832 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003833 // Treat arrays as pointers, since that's how they're passed in.
3834 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003835 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003836 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003837}
3838
3839static inline
3840std::string charUnitsToString(const CharUnits &CU) {
3841 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003842}
3843
John McCall351762c2011-02-07 10:33:21 +00003844/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003845/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003846std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3847 std::string S;
3848
David Chisnall950a9512009-11-17 19:33:30 +00003849 const BlockDecl *Decl = Expr->getBlockDecl();
3850 QualType BlockTy =
3851 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3852 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003853 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003854 // Compute size of all parameters.
3855 // Start with computing size of a pointer in number of bytes.
3856 // FIXME: There might(should) be a better way of doing this computation!
3857 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003858 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3859 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003860 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003861 E = Decl->param_end(); PI != E; ++PI) {
3862 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003863 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003864 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003865 ParmOffset += sz;
3866 }
3867 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003868 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003869 // Block pointer and offset.
3870 S += "@?0";
3871 ParmOffset = PtrSize;
3872
3873 // Argument types.
3874 ParmOffset = PtrSize;
3875 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3876 Decl->param_end(); PI != E; ++PI) {
3877 ParmVarDecl *PVDecl = *PI;
3878 QualType PType = PVDecl->getOriginalType();
3879 if (const ArrayType *AT =
3880 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3881 // Use array's original type only if it has known number of
3882 // elements.
3883 if (!isa<ConstantArrayType>(AT))
3884 PType = PVDecl->getType();
3885 } else if (PType->isFunctionType())
3886 PType = PVDecl->getType();
3887 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003888 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003889 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003890 }
John McCall351762c2011-02-07 10:33:21 +00003891
3892 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003893}
3894
Douglas Gregora9d84932011-05-27 01:19:52 +00003895bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00003896 std::string& S) {
3897 // Encode result type.
3898 getObjCEncodingForType(Decl->getResultType(), S);
3899 CharUnits ParmOffset;
3900 // Compute size of all parameters.
3901 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3902 E = Decl->param_end(); PI != E; ++PI) {
3903 QualType PType = (*PI)->getType();
3904 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00003905 if (sz.isZero())
3906 return true;
3907
David Chisnall50e4eba2010-12-30 14:05:53 +00003908 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00003909 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00003910 ParmOffset += sz;
3911 }
3912 S += charUnitsToString(ParmOffset);
3913 ParmOffset = CharUnits::Zero();
3914
3915 // Argument types.
3916 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3917 E = Decl->param_end(); PI != E; ++PI) {
3918 ParmVarDecl *PVDecl = *PI;
3919 QualType PType = PVDecl->getOriginalType();
3920 if (const ArrayType *AT =
3921 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3922 // Use array's original type only if it has known number of
3923 // elements.
3924 if (!isa<ConstantArrayType>(AT))
3925 PType = PVDecl->getType();
3926 } else if (PType->isFunctionType())
3927 PType = PVDecl->getType();
3928 getObjCEncodingForType(PType, S);
3929 S += charUnitsToString(ParmOffset);
3930 ParmOffset += getObjCEncodingTypeSize(PType);
3931 }
Douglas Gregora9d84932011-05-27 01:19:52 +00003932
3933 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00003934}
3935
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003936/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003937/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00003938bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003939 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003940 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003941 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003942 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003943 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003944 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003945 // Compute size of all parameters.
3946 // Start with computing size of a pointer in number of bytes.
3947 // FIXME: There might(should) be a better way of doing this computation!
3948 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003949 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003950 // The first two arguments (self and _cmd) are pointers; account for
3951 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003952 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003953 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003954 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003955 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003956 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00003957 if (sz.isZero())
3958 return true;
3959
Ken Dyck40775002010-01-11 17:06:35 +00003960 assert (sz.isPositive() &&
3961 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003962 ParmOffset += sz;
3963 }
Ken Dyck40775002010-01-11 17:06:35 +00003964 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003965 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003966 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003967
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003968 // Argument types.
3969 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003970 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003971 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003972 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003973 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003974 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003975 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3976 // Use array's original type only if it has known number of
3977 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003978 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003979 PType = PVDecl->getType();
3980 } else if (PType->isFunctionType())
3981 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003982 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003983 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003984 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003985 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003986 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003987 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003988 }
Douglas Gregora9d84932011-05-27 01:19:52 +00003989
3990 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003991}
3992
Daniel Dunbar4932b362008-08-28 04:38:10 +00003993/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003994/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003995/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3996/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00003997/// Property attributes are stored as a comma-delimited C string. The simple
3998/// attributes readonly and bycopy are encoded as single characters. The
3999/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4000/// encoded as single characters, followed by an identifier. Property types
4001/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004002/// these attributes are defined by the following enumeration:
4003/// @code
4004/// enum PropertyAttributes {
4005/// kPropertyReadOnly = 'R', // property is read-only.
4006/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4007/// kPropertyByref = '&', // property is a reference to the value last assigned
4008/// kPropertyDynamic = 'D', // property is dynamic
4009/// kPropertyGetter = 'G', // followed by getter selector name
4010/// kPropertySetter = 'S', // followed by setter selector name
4011/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4012/// kPropertyType = 't' // followed by old-style type encoding.
4013/// kPropertyWeak = 'W' // 'weak' property
4014/// kPropertyStrong = 'P' // property GC'able
4015/// kPropertyNonAtomic = 'N' // property non-atomic
4016/// };
4017/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004018void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004019 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004020 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004021 // Collect information from the property implementation decl(s).
4022 bool Dynamic = false;
4023 ObjCPropertyImplDecl *SynthesizePID = 0;
4024
4025 // FIXME: Duplicated code due to poor abstraction.
4026 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004027 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004028 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4029 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004030 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004031 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004032 ObjCPropertyImplDecl *PID = *i;
4033 if (PID->getPropertyDecl() == PD) {
4034 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4035 Dynamic = true;
4036 } else {
4037 SynthesizePID = PID;
4038 }
4039 }
4040 }
4041 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004042 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004043 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004044 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004045 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004046 ObjCPropertyImplDecl *PID = *i;
4047 if (PID->getPropertyDecl() == PD) {
4048 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4049 Dynamic = true;
4050 } else {
4051 SynthesizePID = PID;
4052 }
4053 }
Mike Stump11289f42009-09-09 15:08:12 +00004054 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004055 }
4056 }
4057
4058 // FIXME: This is not very efficient.
4059 S = "T";
4060
4061 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004062 // GCC has some special rules regarding encoding of properties which
4063 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004064 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004065 true /* outermost type */,
4066 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004067
4068 if (PD->isReadOnly()) {
4069 S += ",R";
4070 } else {
4071 switch (PD->getSetterKind()) {
4072 case ObjCPropertyDecl::Assign: break;
4073 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004074 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004075 }
4076 }
4077
4078 // It really isn't clear at all what this means, since properties
4079 // are "dynamic by default".
4080 if (Dynamic)
4081 S += ",D";
4082
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004083 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4084 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004085
Daniel Dunbar4932b362008-08-28 04:38:10 +00004086 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4087 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004088 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004089 }
4090
4091 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4092 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004093 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004094 }
4095
4096 if (SynthesizePID) {
4097 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4098 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004099 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004100 }
4101
4102 // FIXME: OBJCGC: weak & strong
4103}
4104
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004105/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004106/// Another legacy compatibility encoding: 32-bit longs are encoded as
4107/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004108/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4109///
4110void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004111 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004112 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004113 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004114 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004115 else
Jay Foad39c79802011-01-12 09:06:06 +00004116 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004117 PointeeTy = IntTy;
4118 }
4119 }
4120}
4121
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004122void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004123 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004124 // We follow the behavior of gcc, expanding structures which are
4125 // directly pointed to, and expanding embedded structures. Note that
4126 // these rules are sufficient to prevent recursive encoding of the
4127 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004128 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004129 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004130}
4131
David Chisnallb190a2c2010-06-04 01:10:52 +00004132static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4133 switch (T->getAs<BuiltinType>()->getKind()) {
4134 default: assert(0 && "Unhandled builtin type kind");
4135 case BuiltinType::Void: return 'v';
4136 case BuiltinType::Bool: return 'B';
4137 case BuiltinType::Char_U:
4138 case BuiltinType::UChar: return 'C';
4139 case BuiltinType::UShort: return 'S';
4140 case BuiltinType::UInt: return 'I';
4141 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004142 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004143 case BuiltinType::UInt128: return 'T';
4144 case BuiltinType::ULongLong: return 'Q';
4145 case BuiltinType::Char_S:
4146 case BuiltinType::SChar: return 'c';
4147 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004148 case BuiltinType::WChar_S:
4149 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004150 case BuiltinType::Int: return 'i';
4151 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004152 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004153 case BuiltinType::LongLong: return 'q';
4154 case BuiltinType::Int128: return 't';
4155 case BuiltinType::Float: return 'f';
4156 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004157 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004158 }
4159}
4160
Jay Foad39c79802011-01-12 09:06:06 +00004161static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004162 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004163 const Expr *E = FD->getBitWidth();
4164 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004165 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004166 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4167 // The GNU runtime requires more information; bitfields are encoded as b,
4168 // then the offset (in bits) of the first element, then the type of the
4169 // bitfield, then the size in bits. For example, in this structure:
4170 //
4171 // struct
4172 // {
4173 // int integer;
4174 // int flags:2;
4175 // };
4176 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4177 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4178 // information is not especially sensible, but we're stuck with it for
4179 // compatibility with GCC, although providing it breaks anything that
4180 // actually uses runtime introspection and wants to work on both runtimes...
4181 if (!Ctx->getLangOptions().NeXTRuntime) {
4182 const RecordDecl *RD = FD->getParent();
4183 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4184 // FIXME: This same linear search is also used in ExprConstant - it might
4185 // be better if the FieldDecl stored its offset. We'd be increasing the
4186 // size of the object slightly, but saving some time every time it is used.
4187 unsigned i = 0;
4188 for (RecordDecl::field_iterator Field = RD->field_begin(),
4189 FieldEnd = RD->field_end();
4190 Field != FieldEnd; (void)++Field, ++i) {
4191 if (*Field == FD)
4192 break;
4193 }
4194 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004195 if (T->isEnumeralType())
4196 S += 'i';
4197 else
Jay Foad39c79802011-01-12 09:06:06 +00004198 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004199 }
4200 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004201 S += llvm::utostr(N);
4202}
4203
Daniel Dunbar07d07852009-10-18 21:17:35 +00004204// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004205void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4206 bool ExpandPointedToStructures,
4207 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004208 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004209 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004210 bool EncodingProperty,
4211 bool StructField) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004212 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004213 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004214 return EncodeBitField(this, S, T, FD);
4215 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004216 return;
4217 }
Mike Stump11289f42009-09-09 15:08:12 +00004218
John McCall9dd450b2009-09-21 23:43:11 +00004219 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004220 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004221 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004222 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004223 return;
4224 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004225
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004226 // encoding for pointer or r3eference types.
4227 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004228 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004229 if (PT->isObjCSelType()) {
4230 S += ':';
4231 return;
4232 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004233 PointeeTy = PT->getPointeeType();
4234 }
4235 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4236 PointeeTy = RT->getPointeeType();
4237 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004238 bool isReadOnly = false;
4239 // For historical/compatibility reasons, the read-only qualifier of the
4240 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4241 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004242 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004243 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004244 if (OutermostType && T.isConstQualified()) {
4245 isReadOnly = true;
4246 S += 'r';
4247 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004248 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004249 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004250 while (P->getAs<PointerType>())
4251 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004252 if (P.isConstQualified()) {
4253 isReadOnly = true;
4254 S += 'r';
4255 }
4256 }
4257 if (isReadOnly) {
4258 // Another legacy compatibility encoding. Some ObjC qualifier and type
4259 // combinations need to be rearranged.
4260 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004261 if (llvm::StringRef(S).endswith("nr"))
4262 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004263 }
Mike Stump11289f42009-09-09 15:08:12 +00004264
Anders Carlssond8499822007-10-29 05:01:08 +00004265 if (PointeeTy->isCharType()) {
4266 // char pointer types should be encoded as '*' unless it is a
4267 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004268 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004269 S += '*';
4270 return;
4271 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004272 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004273 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4274 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4275 S += '#';
4276 return;
4277 }
4278 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4279 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4280 S += '@';
4281 return;
4282 }
4283 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004284 }
Anders Carlssond8499822007-10-29 05:01:08 +00004285 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004286 getLegacyIntegralTypeEncoding(PointeeTy);
4287
Mike Stump11289f42009-09-09 15:08:12 +00004288 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004289 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004290 return;
4291 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004292
Chris Lattnere7cabb92009-07-13 00:10:46 +00004293 if (const ArrayType *AT =
4294 // Ignore type qualifiers etc.
4295 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004296 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004297 // Incomplete arrays are encoded as a pointer to the array element.
4298 S += '^';
4299
Mike Stump11289f42009-09-09 15:08:12 +00004300 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004301 false, ExpandStructures, FD);
4302 } else {
4303 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004304
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004305 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4306 if (getTypeSize(CAT->getElementType()) == 0)
4307 S += '0';
4308 else
4309 S += llvm::utostr(CAT->getSize().getZExtValue());
4310 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004311 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004312 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4313 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004314 S += '0';
4315 }
Mike Stump11289f42009-09-09 15:08:12 +00004316
4317 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004318 false, ExpandStructures, FD);
4319 S += ']';
4320 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004321 return;
4322 }
Mike Stump11289f42009-09-09 15:08:12 +00004323
John McCall9dd450b2009-09-21 23:43:11 +00004324 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004325 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004326 return;
4327 }
Mike Stump11289f42009-09-09 15:08:12 +00004328
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004329 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004330 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004331 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004332 // Anonymous structures print as '?'
4333 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4334 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004335 if (ClassTemplateSpecializationDecl *Spec
4336 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4337 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4338 std::string TemplateArgsStr
4339 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004340 TemplateArgs.data(),
4341 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004342 (*this).PrintingPolicy);
4343
4344 S += TemplateArgsStr;
4345 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004346 } else {
4347 S += '?';
4348 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004349 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004350 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004351 if (!RDecl->isUnion()) {
4352 getObjCEncodingForStructureImpl(RDecl, S, FD);
4353 } else {
4354 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4355 FieldEnd = RDecl->field_end();
4356 Field != FieldEnd; ++Field) {
4357 if (FD) {
4358 S += '"';
4359 S += Field->getNameAsString();
4360 S += '"';
4361 }
Mike Stump11289f42009-09-09 15:08:12 +00004362
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004363 // Special case bit-fields.
4364 if (Field->isBitField()) {
4365 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4366 (*Field));
4367 } else {
4368 QualType qt = Field->getType();
4369 getLegacyIntegralTypeEncoding(qt);
4370 getObjCEncodingForTypeImpl(qt, S, false, true,
4371 FD, /*OutermostType*/false,
4372 /*EncodingProperty*/false,
4373 /*StructField*/true);
4374 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004375 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004376 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004377 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004378 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004379 return;
4380 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004381
Chris Lattnere7cabb92009-07-13 00:10:46 +00004382 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004383 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004384 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004385 else
4386 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004387 return;
4388 }
Mike Stump11289f42009-09-09 15:08:12 +00004389
Chris Lattnere7cabb92009-07-13 00:10:46 +00004390 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004391 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004392 return;
4393 }
Mike Stump11289f42009-09-09 15:08:12 +00004394
John McCall8b07ec22010-05-15 11:32:37 +00004395 // Ignore protocol qualifiers when mangling at this level.
4396 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4397 T = OT->getBaseType();
4398
John McCall8ccfcb52009-09-24 19:53:00 +00004399 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004400 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004401 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004402 S += '{';
4403 const IdentifierInfo *II = OI->getIdentifier();
4404 S += II->getName();
4405 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004406 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4407 DeepCollectObjCIvars(OI, true, Ivars);
4408 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4409 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4410 if (Field->isBitField())
4411 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004412 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004413 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004414 }
4415 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004416 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004417 }
Mike Stump11289f42009-09-09 15:08:12 +00004418
John McCall9dd450b2009-09-21 23:43:11 +00004419 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004420 if (OPT->isObjCIdType()) {
4421 S += '@';
4422 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004423 }
Mike Stump11289f42009-09-09 15:08:12 +00004424
Steve Narofff0c86112009-10-28 22:03:49 +00004425 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4426 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4427 // Since this is a binary compatibility issue, need to consult with runtime
4428 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004429 S += '#';
4430 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004431 }
Mike Stump11289f42009-09-09 15:08:12 +00004432
Chris Lattnere7cabb92009-07-13 00:10:46 +00004433 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004434 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004435 ExpandPointedToStructures,
4436 ExpandStructures, FD);
4437 if (FD || EncodingProperty) {
4438 // Note that we do extended encoding of protocol qualifer list
4439 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004440 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004441 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4442 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004443 S += '<';
4444 S += (*I)->getNameAsString();
4445 S += '>';
4446 }
4447 S += '"';
4448 }
4449 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004450 }
Mike Stump11289f42009-09-09 15:08:12 +00004451
Chris Lattnere7cabb92009-07-13 00:10:46 +00004452 QualType PointeeTy = OPT->getPointeeType();
4453 if (!EncodingProperty &&
4454 isa<TypedefType>(PointeeTy.getTypePtr())) {
4455 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004456 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004457 // {...};
4458 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004459 getObjCEncodingForTypeImpl(PointeeTy, S,
4460 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004461 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004462 return;
4463 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004464
4465 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004466 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004467 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004468 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004469 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4470 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004471 S += '<';
4472 S += (*I)->getNameAsString();
4473 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004474 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004475 S += '"';
4476 }
4477 return;
4478 }
Mike Stump11289f42009-09-09 15:08:12 +00004479
John McCalla9e6e8d2010-05-17 23:56:34 +00004480 // gcc just blithely ignores member pointers.
4481 // TODO: maybe there should be a mangling for these
4482 if (T->getAs<MemberPointerType>())
4483 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004484
4485 if (T->isVectorType()) {
4486 // This matches gcc's encoding, even though technically it is
4487 // insufficient.
4488 // FIXME. We should do a better job than gcc.
4489 return;
4490 }
4491
Chris Lattnere7cabb92009-07-13 00:10:46 +00004492 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004493}
4494
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004495void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4496 std::string &S,
4497 const FieldDecl *FD,
4498 bool includeVBases) const {
4499 assert(RDecl && "Expected non-null RecordDecl");
4500 assert(!RDecl->isUnion() && "Should not be called for unions");
4501 if (!RDecl->getDefinition())
4502 return;
4503
4504 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4505 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4506 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4507
4508 if (CXXRec) {
4509 for (CXXRecordDecl::base_class_iterator
4510 BI = CXXRec->bases_begin(),
4511 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4512 if (!BI->isVirtual()) {
4513 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004514 if (base->isEmpty())
4515 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004516 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4517 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4518 std::make_pair(offs, base));
4519 }
4520 }
4521 }
4522
4523 unsigned i = 0;
4524 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4525 FieldEnd = RDecl->field_end();
4526 Field != FieldEnd; ++Field, ++i) {
4527 uint64_t offs = layout.getFieldOffset(i);
4528 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4529 std::make_pair(offs, *Field));
4530 }
4531
4532 if (CXXRec && includeVBases) {
4533 for (CXXRecordDecl::base_class_iterator
4534 BI = CXXRec->vbases_begin(),
4535 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4536 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004537 if (base->isEmpty())
4538 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004539 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4540 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4541 std::make_pair(offs, base));
4542 }
4543 }
4544
4545 CharUnits size;
4546 if (CXXRec) {
4547 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4548 } else {
4549 size = layout.getSize();
4550 }
4551
4552 uint64_t CurOffs = 0;
4553 std::multimap<uint64_t, NamedDecl *>::iterator
4554 CurLayObj = FieldOrBaseOffsets.begin();
4555
4556 if (CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) {
4557 assert(CXXRec && CXXRec->isDynamicClass() &&
4558 "Offset 0 was empty but no VTable ?");
4559 if (FD) {
4560 S += "\"_vptr$";
4561 std::string recname = CXXRec->getNameAsString();
4562 if (recname.empty()) recname = "?";
4563 S += recname;
4564 S += '"';
4565 }
4566 S += "^^?";
4567 CurOffs += getTypeSize(VoidPtrTy);
4568 }
4569
4570 if (!RDecl->hasFlexibleArrayMember()) {
4571 // Mark the end of the structure.
4572 uint64_t offs = toBits(size);
4573 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4574 std::make_pair(offs, (NamedDecl*)0));
4575 }
4576
4577 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4578 assert(CurOffs <= CurLayObj->first);
4579
4580 if (CurOffs < CurLayObj->first) {
4581 uint64_t padding = CurLayObj->first - CurOffs;
4582 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4583 // packing/alignment of members is different that normal, in which case
4584 // the encoding will be out-of-sync with the real layout.
4585 // If the runtime switches to just consider the size of types without
4586 // taking into account alignment, we could make padding explicit in the
4587 // encoding (e.g. using arrays of chars). The encoding strings would be
4588 // longer then though.
4589 CurOffs += padding;
4590 }
4591
4592 NamedDecl *dcl = CurLayObj->second;
4593 if (dcl == 0)
4594 break; // reached end of structure.
4595
4596 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4597 // We expand the bases without their virtual bases since those are going
4598 // in the initial structure. Note that this differs from gcc which
4599 // expands virtual bases each time one is encountered in the hierarchy,
4600 // making the encoding type bigger than it really is.
4601 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004602 assert(!base->isEmpty());
4603 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004604 } else {
4605 FieldDecl *field = cast<FieldDecl>(dcl);
4606 if (FD) {
4607 S += '"';
4608 S += field->getNameAsString();
4609 S += '"';
4610 }
4611
4612 if (field->isBitField()) {
4613 EncodeBitField(this, S, field->getType(), field);
4614 CurOffs += field->getBitWidth()->EvaluateAsInt(*this).getZExtValue();
4615 } else {
4616 QualType qt = field->getType();
4617 getLegacyIntegralTypeEncoding(qt);
4618 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4619 /*OutermostType*/false,
4620 /*EncodingProperty*/false,
4621 /*StructField*/true);
4622 CurOffs += getTypeSize(field->getType());
4623 }
4624 }
4625 }
4626}
4627
Mike Stump11289f42009-09-09 15:08:12 +00004628void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004629 std::string& S) const {
4630 if (QT & Decl::OBJC_TQ_In)
4631 S += 'n';
4632 if (QT & Decl::OBJC_TQ_Inout)
4633 S += 'N';
4634 if (QT & Decl::OBJC_TQ_Out)
4635 S += 'o';
4636 if (QT & Decl::OBJC_TQ_Bycopy)
4637 S += 'O';
4638 if (QT & Decl::OBJC_TQ_Byref)
4639 S += 'R';
4640 if (QT & Decl::OBJC_TQ_Oneway)
4641 S += 'V';
4642}
4643
Chris Lattnere7cabb92009-07-13 00:10:46 +00004644void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004645 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004646
Anders Carlsson87c149b2007-10-11 01:00:40 +00004647 BuiltinVaListType = T;
4648}
4649
Chris Lattnere7cabb92009-07-13 00:10:46 +00004650void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004651 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004652}
4653
Chris Lattnere7cabb92009-07-13 00:10:46 +00004654void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004655 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004656}
4657
Chris Lattnere7cabb92009-07-13 00:10:46 +00004658void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004659 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004660}
4661
Chris Lattnere7cabb92009-07-13 00:10:46 +00004662void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004663 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004664}
4665
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004666void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004667 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004668 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004669
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004670 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004671}
4672
John McCalld28ae272009-12-02 08:04:21 +00004673/// \brief Retrieve the template name that corresponds to a non-empty
4674/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004675TemplateName
4676ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4677 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004678 unsigned size = End - Begin;
4679 assert(size > 1 && "set is not overloaded!");
4680
4681 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4682 size * sizeof(FunctionTemplateDecl*));
4683 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4684
4685 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004686 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004687 NamedDecl *D = *I;
4688 assert(isa<FunctionTemplateDecl>(D) ||
4689 (isa<UsingShadowDecl>(D) &&
4690 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4691 *Storage++ = D;
4692 }
4693
4694 return TemplateName(OT);
4695}
4696
Douglas Gregordc572a32009-03-30 22:58:21 +00004697/// \brief Retrieve the template name that represents a qualified
4698/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004699TemplateName
4700ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4701 bool TemplateKeyword,
4702 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004703 assert(NNS && "Missing nested-name-specifier in qualified template name");
4704
Douglas Gregorc42075a2010-02-04 18:10:26 +00004705 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004706 llvm::FoldingSetNodeID ID;
4707 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4708
4709 void *InsertPos = 0;
4710 QualifiedTemplateName *QTN =
4711 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4712 if (!QTN) {
4713 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4714 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4715 }
4716
4717 return TemplateName(QTN);
4718}
4719
4720/// \brief Retrieve the template name that represents a dependent
4721/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004722TemplateName
4723ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4724 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004725 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004726 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004727
4728 llvm::FoldingSetNodeID ID;
4729 DependentTemplateName::Profile(ID, NNS, Name);
4730
4731 void *InsertPos = 0;
4732 DependentTemplateName *QTN =
4733 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4734
4735 if (QTN)
4736 return TemplateName(QTN);
4737
4738 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4739 if (CanonNNS == NNS) {
4740 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4741 } else {
4742 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4743 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004744 DependentTemplateName *CheckQTN =
4745 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4746 assert(!CheckQTN && "Dependent type name canonicalization broken");
4747 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004748 }
4749
4750 DependentTemplateNames.InsertNode(QTN, InsertPos);
4751 return TemplateName(QTN);
4752}
4753
Douglas Gregor71395fa2009-11-04 00:56:37 +00004754/// \brief Retrieve the template name that represents a dependent
4755/// template name such as \c MetaFun::template operator+.
4756TemplateName
4757ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004758 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004759 assert((!NNS || NNS->isDependent()) &&
4760 "Nested name specifier must be dependent");
4761
4762 llvm::FoldingSetNodeID ID;
4763 DependentTemplateName::Profile(ID, NNS, Operator);
4764
4765 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004766 DependentTemplateName *QTN
4767 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004768
4769 if (QTN)
4770 return TemplateName(QTN);
4771
4772 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4773 if (CanonNNS == NNS) {
4774 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4775 } else {
4776 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4777 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004778
4779 DependentTemplateName *CheckQTN
4780 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4781 assert(!CheckQTN && "Dependent template name canonicalization broken");
4782 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004783 }
4784
4785 DependentTemplateNames.InsertNode(QTN, InsertPos);
4786 return TemplateName(QTN);
4787}
4788
Douglas Gregor5590be02011-01-15 06:45:20 +00004789TemplateName
4790ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4791 const TemplateArgument &ArgPack) const {
4792 ASTContext &Self = const_cast<ASTContext &>(*this);
4793 llvm::FoldingSetNodeID ID;
4794 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4795
4796 void *InsertPos = 0;
4797 SubstTemplateTemplateParmPackStorage *Subst
4798 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4799
4800 if (!Subst) {
4801 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4802 ArgPack.pack_size(),
4803 ArgPack.pack_begin());
4804 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4805 }
4806
4807 return TemplateName(Subst);
4808}
4809
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004810/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004811/// TargetInfo, produce the corresponding type. The unsigned @p Type
4812/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004813CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004814 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004815 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004816 case TargetInfo::SignedShort: return ShortTy;
4817 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4818 case TargetInfo::SignedInt: return IntTy;
4819 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4820 case TargetInfo::SignedLong: return LongTy;
4821 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4822 case TargetInfo::SignedLongLong: return LongLongTy;
4823 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4824 }
4825
4826 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004827 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004828}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004829
4830//===----------------------------------------------------------------------===//
4831// Type Predicates.
4832//===----------------------------------------------------------------------===//
4833
Fariborz Jahanian96207692009-02-18 21:49:28 +00004834/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4835/// garbage collection attribute.
4836///
John McCall553d45a2011-01-12 00:34:59 +00004837Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4838 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4839 return Qualifiers::GCNone;
4840
4841 assert(getLangOptions().ObjC1);
4842 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4843
4844 // Default behaviour under objective-C's gc is for ObjC pointers
4845 // (or pointers to them) be treated as though they were declared
4846 // as __strong.
4847 if (GCAttrs == Qualifiers::GCNone) {
4848 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4849 return Qualifiers::Strong;
4850 else if (Ty->isPointerType())
4851 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4852 } else {
4853 // It's not valid to set GC attributes on anything that isn't a
4854 // pointer.
4855#ifndef NDEBUG
4856 QualType CT = Ty->getCanonicalTypeInternal();
4857 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4858 CT = AT->getElementType();
4859 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4860#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004861 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004862 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004863}
4864
Chris Lattner49af6a42008-04-07 06:51:04 +00004865//===----------------------------------------------------------------------===//
4866// Type Compatibility Testing
4867//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004868
Mike Stump11289f42009-09-09 15:08:12 +00004869/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004870/// compatible.
4871static bool areCompatVectorTypes(const VectorType *LHS,
4872 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004873 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004874 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004875 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004876}
4877
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004878bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4879 QualType SecondVec) {
4880 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4881 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4882
4883 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4884 return true;
4885
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004886 // Treat Neon vector types and most AltiVec vector types as if they are the
4887 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004888 const VectorType *First = FirstVec->getAs<VectorType>();
4889 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004890 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004891 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004892 First->getVectorKind() != VectorType::AltiVecPixel &&
4893 First->getVectorKind() != VectorType::AltiVecBool &&
4894 Second->getVectorKind() != VectorType::AltiVecPixel &&
4895 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004896 return true;
4897
4898 return false;
4899}
4900
Steve Naroff8e6aee52009-07-23 01:01:38 +00004901//===----------------------------------------------------------------------===//
4902// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4903//===----------------------------------------------------------------------===//
4904
4905/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4906/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004907bool
4908ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4909 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004910 if (lProto == rProto)
4911 return true;
4912 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4913 E = rProto->protocol_end(); PI != E; ++PI)
4914 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4915 return true;
4916 return false;
4917}
4918
Steve Naroff8e6aee52009-07-23 01:01:38 +00004919/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4920/// return true if lhs's protocols conform to rhs's protocol; false
4921/// otherwise.
4922bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4923 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4924 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4925 return false;
4926}
4927
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004928/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4929/// Class<p1, ...>.
4930bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4931 QualType rhs) {
4932 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4933 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4934 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4935
4936 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4937 E = lhsQID->qual_end(); I != E; ++I) {
4938 bool match = false;
4939 ObjCProtocolDecl *lhsProto = *I;
4940 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4941 E = rhsOPT->qual_end(); J != E; ++J) {
4942 ObjCProtocolDecl *rhsProto = *J;
4943 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4944 match = true;
4945 break;
4946 }
4947 }
4948 if (!match)
4949 return false;
4950 }
4951 return true;
4952}
4953
Steve Naroff8e6aee52009-07-23 01:01:38 +00004954/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4955/// ObjCQualifiedIDType.
4956bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4957 bool compare) {
4958 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004959 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004960 lhs->isObjCIdType() || lhs->isObjCClassType())
4961 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004962 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004963 rhs->isObjCIdType() || rhs->isObjCClassType())
4964 return true;
4965
4966 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004967 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004968
Steve Naroff8e6aee52009-07-23 01:01:38 +00004969 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004970
Steve Naroff8e6aee52009-07-23 01:01:38 +00004971 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004972 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004973 // make sure we check the class hierarchy.
4974 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4975 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4976 E = lhsQID->qual_end(); I != E; ++I) {
4977 // when comparing an id<P> on lhs with a static type on rhs,
4978 // see if static class implements all of id's protocols, directly or
4979 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004980 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004981 return false;
4982 }
4983 }
4984 // If there are no qualifiers and no interface, we have an 'id'.
4985 return true;
4986 }
Mike Stump11289f42009-09-09 15:08:12 +00004987 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004988 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4989 E = lhsQID->qual_end(); I != E; ++I) {
4990 ObjCProtocolDecl *lhsProto = *I;
4991 bool match = false;
4992
4993 // when comparing an id<P> on lhs with a static type on rhs,
4994 // see if static class implements all of id's protocols, directly or
4995 // through its super class and categories.
4996 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4997 E = rhsOPT->qual_end(); J != E; ++J) {
4998 ObjCProtocolDecl *rhsProto = *J;
4999 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5000 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5001 match = true;
5002 break;
5003 }
5004 }
Mike Stump11289f42009-09-09 15:08:12 +00005005 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005006 // make sure we check the class hierarchy.
5007 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5008 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5009 E = lhsQID->qual_end(); I != E; ++I) {
5010 // when comparing an id<P> on lhs with a static type on rhs,
5011 // see if static class implements all of id's protocols, directly or
5012 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005013 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005014 match = true;
5015 break;
5016 }
5017 }
5018 }
5019 if (!match)
5020 return false;
5021 }
Mike Stump11289f42009-09-09 15:08:12 +00005022
Steve Naroff8e6aee52009-07-23 01:01:38 +00005023 return true;
5024 }
Mike Stump11289f42009-09-09 15:08:12 +00005025
Steve Naroff8e6aee52009-07-23 01:01:38 +00005026 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5027 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5028
Mike Stump11289f42009-09-09 15:08:12 +00005029 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005030 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005031 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005032 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5033 E = lhsOPT->qual_end(); I != E; ++I) {
5034 ObjCProtocolDecl *lhsProto = *I;
5035 bool match = false;
5036
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005037 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005038 // see if static class implements all of id's protocols, directly or
5039 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005040 // First, lhs protocols in the qualifier list must be found, direct
5041 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005042 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5043 E = rhsQID->qual_end(); J != E; ++J) {
5044 ObjCProtocolDecl *rhsProto = *J;
5045 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5046 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5047 match = true;
5048 break;
5049 }
5050 }
5051 if (!match)
5052 return false;
5053 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005054
5055 // Static class's protocols, or its super class or category protocols
5056 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5057 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5058 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5059 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5060 // This is rather dubious but matches gcc's behavior. If lhs has
5061 // no type qualifier and its class has no static protocol(s)
5062 // assume that it is mismatch.
5063 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5064 return false;
5065 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5066 LHSInheritedProtocols.begin(),
5067 E = LHSInheritedProtocols.end(); I != E; ++I) {
5068 bool match = false;
5069 ObjCProtocolDecl *lhsProto = (*I);
5070 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5071 E = rhsQID->qual_end(); J != E; ++J) {
5072 ObjCProtocolDecl *rhsProto = *J;
5073 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5074 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5075 match = true;
5076 break;
5077 }
5078 }
5079 if (!match)
5080 return false;
5081 }
5082 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005083 return true;
5084 }
5085 return false;
5086}
5087
Eli Friedman47f77112008-08-22 00:56:42 +00005088/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005089/// compatible for assignment from RHS to LHS. This handles validation of any
5090/// protocol qualifiers on the LHS or RHS.
5091///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005092bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5093 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005094 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5095 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5096
Steve Naroff1329fa02009-07-15 18:40:39 +00005097 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005098 if (LHS->isObjCUnqualifiedIdOrClass() ||
5099 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005100 return true;
5101
John McCall8b07ec22010-05-15 11:32:37 +00005102 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005103 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5104 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005105 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005106
5107 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5108 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5109 QualType(RHSOPT,0));
5110
John McCall8b07ec22010-05-15 11:32:37 +00005111 // If we have 2 user-defined types, fall into that path.
5112 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005113 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005114
Steve Naroff8e6aee52009-07-23 01:01:38 +00005115 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005116}
5117
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005118/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005119/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005120/// arguments in block literals. When passed as arguments, passing 'A*' where
5121/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5122/// not OK. For the return type, the opposite is not OK.
5123bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5124 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005125 const ObjCObjectPointerType *RHSOPT,
5126 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005127 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005128 return true;
5129
5130 if (LHSOPT->isObjCBuiltinType()) {
5131 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5132 }
5133
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005134 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005135 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5136 QualType(RHSOPT,0),
5137 false);
5138
5139 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5140 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5141 if (LHS && RHS) { // We have 2 user-defined types.
5142 if (LHS != RHS) {
5143 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005144 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005145 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005146 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005147 }
5148 else
5149 return true;
5150 }
5151 return false;
5152}
5153
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005154/// getIntersectionOfProtocols - This routine finds the intersection of set
5155/// of protocols inherited from two distinct objective-c pointer objects.
5156/// It is used to build composite qualifier list of the composite type of
5157/// the conditional expression involving two objective-c pointer objects.
5158static
5159void getIntersectionOfProtocols(ASTContext &Context,
5160 const ObjCObjectPointerType *LHSOPT,
5161 const ObjCObjectPointerType *RHSOPT,
5162 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
5163
John McCall8b07ec22010-05-15 11:32:37 +00005164 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5165 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5166 assert(LHS->getInterface() && "LHS must have an interface base");
5167 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005168
5169 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5170 unsigned LHSNumProtocols = LHS->getNumProtocols();
5171 if (LHSNumProtocols > 0)
5172 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5173 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005174 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005175 Context.CollectInheritedProtocols(LHS->getInterface(),
5176 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005177 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5178 LHSInheritedProtocols.end());
5179 }
5180
5181 unsigned RHSNumProtocols = RHS->getNumProtocols();
5182 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005183 ObjCProtocolDecl **RHSProtocols =
5184 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005185 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5186 if (InheritedProtocolSet.count(RHSProtocols[i]))
5187 IntersectionOfProtocols.push_back(RHSProtocols[i]);
5188 }
5189 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005190 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005191 Context.CollectInheritedProtocols(RHS->getInterface(),
5192 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005193 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5194 RHSInheritedProtocols.begin(),
5195 E = RHSInheritedProtocols.end(); I != E; ++I)
5196 if (InheritedProtocolSet.count((*I)))
5197 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005198 }
5199}
5200
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005201/// areCommonBaseCompatible - Returns common base class of the two classes if
5202/// one found. Note that this is O'2 algorithm. But it will be called as the
5203/// last type comparison in a ?-exp of ObjC pointer types before a
5204/// warning is issued. So, its invokation is extremely rare.
5205QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005206 const ObjCObjectPointerType *Lptr,
5207 const ObjCObjectPointerType *Rptr) {
5208 const ObjCObjectType *LHS = Lptr->getObjectType();
5209 const ObjCObjectType *RHS = Rptr->getObjectType();
5210 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5211 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005212 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005213 return QualType();
5214
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005215 do {
John McCall8b07ec22010-05-15 11:32:37 +00005216 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005217 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00005218 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
5219 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5220
5221 QualType Result = QualType(LHS, 0);
5222 if (!Protocols.empty())
5223 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5224 Result = getObjCObjectPointerType(Result);
5225 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005226 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005227 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005228
5229 return QualType();
5230}
5231
John McCall8b07ec22010-05-15 11:32:37 +00005232bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5233 const ObjCObjectType *RHS) {
5234 assert(LHS->getInterface() && "LHS is not an interface type");
5235 assert(RHS->getInterface() && "RHS is not an interface type");
5236
Chris Lattner49af6a42008-04-07 06:51:04 +00005237 // Verify that the base decls are compatible: the RHS must be a subclass of
5238 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005239 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005240 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005241
Chris Lattner49af6a42008-04-07 06:51:04 +00005242 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5243 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005244 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005245 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005246
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005247 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5248 // more detailed analysis is required.
5249 if (RHS->getNumProtocols() == 0) {
5250 // OK, if LHS is a superclass of RHS *and*
5251 // this superclass is assignment compatible with LHS.
5252 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005253 bool IsSuperClass =
5254 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5255 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005256 // OK if conversion of LHS to SuperClass results in narrowing of types
5257 // ; i.e., SuperClass may implement at least one of the protocols
5258 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5259 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5260 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005261 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005262 // If super class has no protocols, it is not a match.
5263 if (SuperClassInheritedProtocols.empty())
5264 return false;
5265
5266 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5267 LHSPE = LHS->qual_end();
5268 LHSPI != LHSPE; LHSPI++) {
5269 bool SuperImplementsProtocol = false;
5270 ObjCProtocolDecl *LHSProto = (*LHSPI);
5271
5272 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5273 SuperClassInheritedProtocols.begin(),
5274 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5275 ObjCProtocolDecl *SuperClassProto = (*I);
5276 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5277 SuperImplementsProtocol = true;
5278 break;
5279 }
5280 }
5281 if (!SuperImplementsProtocol)
5282 return false;
5283 }
5284 return true;
5285 }
5286 return false;
5287 }
Mike Stump11289f42009-09-09 15:08:12 +00005288
John McCall8b07ec22010-05-15 11:32:37 +00005289 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5290 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005291 LHSPI != LHSPE; LHSPI++) {
5292 bool RHSImplementsProtocol = false;
5293
5294 // If the RHS doesn't implement the protocol on the left, the types
5295 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005296 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5297 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005298 RHSPI != RHSPE; RHSPI++) {
5299 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005300 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005301 break;
5302 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005303 }
5304 // FIXME: For better diagnostics, consider passing back the protocol name.
5305 if (!RHSImplementsProtocol)
5306 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005307 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005308 // The RHS implements all protocols listed on the LHS.
5309 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005310}
5311
Steve Naroffb7605152009-02-12 17:52:19 +00005312bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5313 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005314 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5315 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005316
Steve Naroff7cae42b2009-07-10 23:34:53 +00005317 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005318 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005319
5320 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5321 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005322}
5323
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005324bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5325 return canAssignObjCInterfaces(
5326 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5327 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5328}
5329
Mike Stump11289f42009-09-09 15:08:12 +00005330/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005331/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005332/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005333/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005334bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5335 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005336 if (getLangOptions().CPlusPlus)
5337 return hasSameType(LHS, RHS);
5338
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005339 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005340}
5341
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005342bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5343 return !mergeTypes(LHS, RHS, true).isNull();
5344}
5345
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005346/// mergeTransparentUnionType - if T is a transparent union type and a member
5347/// of T is compatible with SubType, return the merged type, else return
5348/// QualType()
5349QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5350 bool OfBlockPointer,
5351 bool Unqualified) {
5352 if (const RecordType *UT = T->getAsUnionType()) {
5353 RecordDecl *UD = UT->getDecl();
5354 if (UD->hasAttr<TransparentUnionAttr>()) {
5355 for (RecordDecl::field_iterator it = UD->field_begin(),
5356 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005357 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005358 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5359 if (!MT.isNull())
5360 return MT;
5361 }
5362 }
5363 }
5364
5365 return QualType();
5366}
5367
5368/// mergeFunctionArgumentTypes - merge two types which appear as function
5369/// argument types
5370QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5371 bool OfBlockPointer,
5372 bool Unqualified) {
5373 // GNU extension: two types are compatible if they appear as a function
5374 // argument, one of the types is a transparent union type and the other
5375 // type is compatible with a union member
5376 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5377 Unqualified);
5378 if (!lmerge.isNull())
5379 return lmerge;
5380
5381 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5382 Unqualified);
5383 if (!rmerge.isNull())
5384 return rmerge;
5385
5386 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5387}
5388
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005389QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005390 bool OfBlockPointer,
5391 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005392 const FunctionType *lbase = lhs->getAs<FunctionType>();
5393 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005394 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5395 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005396 bool allLTypes = true;
5397 bool allRTypes = true;
5398
5399 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005400 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005401 if (OfBlockPointer) {
5402 QualType RHS = rbase->getResultType();
5403 QualType LHS = lbase->getResultType();
5404 bool UnqualifiedResult = Unqualified;
5405 if (!UnqualifiedResult)
5406 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005407 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005408 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005409 else
John McCall8c6b56f2010-12-15 01:06:38 +00005410 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5411 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005412 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005413
5414 if (Unqualified)
5415 retType = retType.getUnqualifiedType();
5416
5417 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5418 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5419 if (Unqualified) {
5420 LRetType = LRetType.getUnqualifiedType();
5421 RRetType = RRetType.getUnqualifiedType();
5422 }
5423
5424 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005425 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005426 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005427 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005428
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005429 // FIXME: double check this
5430 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5431 // rbase->getRegParmAttr() != 0 &&
5432 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005433 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5434 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005435
Douglas Gregor8c940862010-01-18 17:14:39 +00005436 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005437 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005438 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005439
John McCall8c6b56f2010-12-15 01:06:38 +00005440 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005441 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5442 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005443 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5444 return QualType();
5445
John McCall31168b02011-06-15 23:02:42 +00005446 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5447 return QualType();
5448
John McCall8c6b56f2010-12-15 01:06:38 +00005449 // It's noreturn if either type is.
5450 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5451 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5452 if (NoReturn != lbaseInfo.getNoReturn())
5453 allLTypes = false;
5454 if (NoReturn != rbaseInfo.getNoReturn())
5455 allRTypes = false;
5456
John McCall31168b02011-06-15 23:02:42 +00005457 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005458
Eli Friedman47f77112008-08-22 00:56:42 +00005459 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005460 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5461 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005462 unsigned lproto_nargs = lproto->getNumArgs();
5463 unsigned rproto_nargs = rproto->getNumArgs();
5464
5465 // Compatible functions must have the same number of arguments
5466 if (lproto_nargs != rproto_nargs)
5467 return QualType();
5468
5469 // Variadic and non-variadic functions aren't compatible
5470 if (lproto->isVariadic() != rproto->isVariadic())
5471 return QualType();
5472
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005473 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5474 return QualType();
5475
Eli Friedman47f77112008-08-22 00:56:42 +00005476 // Check argument compatibility
5477 llvm::SmallVector<QualType, 10> types;
5478 for (unsigned i = 0; i < lproto_nargs; i++) {
5479 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5480 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005481 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5482 OfBlockPointer,
5483 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005484 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005485
5486 if (Unqualified)
5487 argtype = argtype.getUnqualifiedType();
5488
Eli Friedman47f77112008-08-22 00:56:42 +00005489 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005490 if (Unqualified) {
5491 largtype = largtype.getUnqualifiedType();
5492 rargtype = rargtype.getUnqualifiedType();
5493 }
5494
Chris Lattner465fa322008-10-05 17:34:18 +00005495 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5496 allLTypes = false;
5497 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5498 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005499 }
5500 if (allLTypes) return lhs;
5501 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005502
5503 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5504 EPI.ExtInfo = einfo;
5505 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005506 }
5507
5508 if (lproto) allRTypes = false;
5509 if (rproto) allLTypes = false;
5510
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005511 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005512 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005513 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005514 if (proto->isVariadic()) return QualType();
5515 // Check that the types are compatible with the types that
5516 // would result from default argument promotions (C99 6.7.5.3p15).
5517 // The only types actually affected are promotable integer
5518 // types and floats, which would be passed as a different
5519 // type depending on whether the prototype is visible.
5520 unsigned proto_nargs = proto->getNumArgs();
5521 for (unsigned i = 0; i < proto_nargs; ++i) {
5522 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005523
5524 // Look at the promotion type of enum types, since that is the type used
5525 // to pass enum values.
5526 if (const EnumType *Enum = argTy->getAs<EnumType>())
5527 argTy = Enum->getDecl()->getPromotionType();
5528
Eli Friedman47f77112008-08-22 00:56:42 +00005529 if (argTy->isPromotableIntegerType() ||
5530 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5531 return QualType();
5532 }
5533
5534 if (allLTypes) return lhs;
5535 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005536
5537 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5538 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005539 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005540 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005541 }
5542
5543 if (allLTypes) return lhs;
5544 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005545 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005546}
5547
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005548QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005549 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005550 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005551 // C++ [expr]: If an expression initially has the type "reference to T", the
5552 // type is adjusted to "T" prior to any further analysis, the expression
5553 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005554 // expression is an lvalue unless the reference is an rvalue reference and
5555 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005556 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5557 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005558
5559 if (Unqualified) {
5560 LHS = LHS.getUnqualifiedType();
5561 RHS = RHS.getUnqualifiedType();
5562 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005563
Eli Friedman47f77112008-08-22 00:56:42 +00005564 QualType LHSCan = getCanonicalType(LHS),
5565 RHSCan = getCanonicalType(RHS);
5566
5567 // If two types are identical, they are compatible.
5568 if (LHSCan == RHSCan)
5569 return LHS;
5570
John McCall8ccfcb52009-09-24 19:53:00 +00005571 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005572 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5573 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005574 if (LQuals != RQuals) {
5575 // If any of these qualifiers are different, we have a type
5576 // mismatch.
5577 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005578 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5579 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005580 return QualType();
5581
5582 // Exactly one GC qualifier difference is allowed: __strong is
5583 // okay if the other type has no GC qualifier but is an Objective
5584 // C object pointer (i.e. implicitly strong by default). We fix
5585 // this by pretending that the unqualified type was actually
5586 // qualified __strong.
5587 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5588 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5589 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5590
5591 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5592 return QualType();
5593
5594 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5595 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5596 }
5597 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5598 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5599 }
Eli Friedman47f77112008-08-22 00:56:42 +00005600 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005601 }
5602
5603 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005604
Eli Friedmandcca6332009-06-01 01:22:52 +00005605 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5606 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005607
Chris Lattnerfd652912008-01-14 05:45:46 +00005608 // We want to consider the two function types to be the same for these
5609 // comparisons, just force one to the other.
5610 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5611 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005612
5613 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005614 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5615 LHSClass = Type::ConstantArray;
5616 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5617 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005618
John McCall8b07ec22010-05-15 11:32:37 +00005619 // ObjCInterfaces are just specialized ObjCObjects.
5620 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5621 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5622
Nate Begemance4d7fc2008-04-18 23:10:10 +00005623 // Canonicalize ExtVector -> Vector.
5624 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5625 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005626
Chris Lattner95554662008-04-07 05:43:21 +00005627 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005628 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005629 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005630 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005631 // Compatibility is based on the underlying type, not the promotion
5632 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005633 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005634 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5635 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005636 }
John McCall9dd450b2009-09-21 23:43:11 +00005637 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005638 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5639 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005640 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005641
Eli Friedman47f77112008-08-22 00:56:42 +00005642 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005643 }
Eli Friedman47f77112008-08-22 00:56:42 +00005644
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005645 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005646 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005647#define TYPE(Class, Base)
5648#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005649#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005650#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5651#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5652#include "clang/AST/TypeNodes.def"
5653 assert(false && "Non-canonical and dependent types shouldn't get here");
5654 return QualType();
5655
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005656 case Type::LValueReference:
5657 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005658 case Type::MemberPointer:
5659 assert(false && "C++ should never be in mergeTypes");
5660 return QualType();
5661
John McCall8b07ec22010-05-15 11:32:37 +00005662 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005663 case Type::IncompleteArray:
5664 case Type::VariableArray:
5665 case Type::FunctionProto:
5666 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005667 assert(false && "Types are eliminated above");
5668 return QualType();
5669
Chris Lattnerfd652912008-01-14 05:45:46 +00005670 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005671 {
5672 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005673 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5674 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005675 if (Unqualified) {
5676 LHSPointee = LHSPointee.getUnqualifiedType();
5677 RHSPointee = RHSPointee.getUnqualifiedType();
5678 }
5679 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5680 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005681 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005682 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005683 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005684 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005685 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005686 return getPointerType(ResultType);
5687 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005688 case Type::BlockPointer:
5689 {
5690 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005691 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5692 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005693 if (Unqualified) {
5694 LHSPointee = LHSPointee.getUnqualifiedType();
5695 RHSPointee = RHSPointee.getUnqualifiedType();
5696 }
5697 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5698 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005699 if (ResultType.isNull()) return QualType();
5700 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5701 return LHS;
5702 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5703 return RHS;
5704 return getBlockPointerType(ResultType);
5705 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005706 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005707 {
5708 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5709 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5710 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5711 return QualType();
5712
5713 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5714 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005715 if (Unqualified) {
5716 LHSElem = LHSElem.getUnqualifiedType();
5717 RHSElem = RHSElem.getUnqualifiedType();
5718 }
5719
5720 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005721 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005722 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5723 return LHS;
5724 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5725 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005726 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5727 ArrayType::ArraySizeModifier(), 0);
5728 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5729 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005730 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5731 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005732 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5733 return LHS;
5734 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5735 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005736 if (LVAT) {
5737 // FIXME: This isn't correct! But tricky to implement because
5738 // the array's size has to be the size of LHS, but the type
5739 // has to be different.
5740 return LHS;
5741 }
5742 if (RVAT) {
5743 // FIXME: This isn't correct! But tricky to implement because
5744 // the array's size has to be the size of RHS, but the type
5745 // has to be different.
5746 return RHS;
5747 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005748 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5749 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005750 return getIncompleteArrayType(ResultType,
5751 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005752 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005753 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005754 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005755 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005756 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005757 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005758 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005759 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005760 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005761 case Type::Complex:
5762 // Distinct complex types are incompatible.
5763 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005764 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005765 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005766 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5767 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005768 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005769 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005770 case Type::ObjCObject: {
5771 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005772 // FIXME: This should be type compatibility, e.g. whether
5773 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005774 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5775 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5776 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005777 return LHS;
5778
Eli Friedman47f77112008-08-22 00:56:42 +00005779 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005780 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005781 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005782 if (OfBlockPointer) {
5783 if (canAssignObjCInterfacesInBlockPointer(
5784 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005785 RHS->getAs<ObjCObjectPointerType>(),
5786 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005787 return LHS;
5788 return QualType();
5789 }
John McCall9dd450b2009-09-21 23:43:11 +00005790 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5791 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005792 return LHS;
5793
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005794 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005795 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005796 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005797
5798 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005799}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005800
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005801/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5802/// 'RHS' attributes and returns the merged version; including for function
5803/// return types.
5804QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5805 QualType LHSCan = getCanonicalType(LHS),
5806 RHSCan = getCanonicalType(RHS);
5807 // If two types are identical, they are compatible.
5808 if (LHSCan == RHSCan)
5809 return LHS;
5810 if (RHSCan->isFunctionType()) {
5811 if (!LHSCan->isFunctionType())
5812 return QualType();
5813 QualType OldReturnType =
5814 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5815 QualType NewReturnType =
5816 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5817 QualType ResReturnType =
5818 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5819 if (ResReturnType.isNull())
5820 return QualType();
5821 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5822 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5823 // In either case, use OldReturnType to build the new function type.
5824 const FunctionType *F = LHS->getAs<FunctionType>();
5825 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005826 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5827 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005828 QualType ResultType
5829 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005830 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005831 return ResultType;
5832 }
5833 }
5834 return QualType();
5835 }
5836
5837 // If the qualifiers are different, the types can still be merged.
5838 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5839 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5840 if (LQuals != RQuals) {
5841 // If any of these qualifiers are different, we have a type mismatch.
5842 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5843 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5844 return QualType();
5845
5846 // Exactly one GC qualifier difference is allowed: __strong is
5847 // okay if the other type has no GC qualifier but is an Objective
5848 // C object pointer (i.e. implicitly strong by default). We fix
5849 // this by pretending that the unqualified type was actually
5850 // qualified __strong.
5851 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5852 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5853 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5854
5855 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5856 return QualType();
5857
5858 if (GC_L == Qualifiers::Strong)
5859 return LHS;
5860 if (GC_R == Qualifiers::Strong)
5861 return RHS;
5862 return QualType();
5863 }
5864
5865 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5866 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5867 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5868 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5869 if (ResQT == LHSBaseQT)
5870 return LHS;
5871 if (ResQT == RHSBaseQT)
5872 return RHS;
5873 }
5874 return QualType();
5875}
5876
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005877//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005878// Integer Predicates
5879//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005880
Jay Foad39c79802011-01-12 09:06:06 +00005881unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005882 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005883 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005884 if (T->isBooleanType())
5885 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005886 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005887 return (unsigned)getTypeSize(T);
5888}
5889
5890QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005891 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005892
5893 // Turn <4 x signed int> -> <4 x unsigned int>
5894 if (const VectorType *VTy = T->getAs<VectorType>())
5895 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005896 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005897
5898 // For enums, we return the unsigned version of the base type.
5899 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005900 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005901
5902 const BuiltinType *BTy = T->getAs<BuiltinType>();
5903 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005904 switch (BTy->getKind()) {
5905 case BuiltinType::Char_S:
5906 case BuiltinType::SChar:
5907 return UnsignedCharTy;
5908 case BuiltinType::Short:
5909 return UnsignedShortTy;
5910 case BuiltinType::Int:
5911 return UnsignedIntTy;
5912 case BuiltinType::Long:
5913 return UnsignedLongTy;
5914 case BuiltinType::LongLong:
5915 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005916 case BuiltinType::Int128:
5917 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005918 default:
5919 assert(0 && "Unexpected signed integer type");
5920 return QualType();
5921 }
5922}
5923
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005924ASTMutationListener::~ASTMutationListener() { }
5925
Chris Lattnerecd79c62009-06-14 00:45:47 +00005926
5927//===----------------------------------------------------------------------===//
5928// Builtin Type Computation
5929//===----------------------------------------------------------------------===//
5930
5931/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005932/// pointer over the consumed characters. This returns the resultant type. If
5933/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5934/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5935/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005936///
5937/// RequiresICE is filled in on return to indicate whether the value is required
5938/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005939static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005940 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005941 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005942 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005943 // Modifiers.
5944 int HowLong = 0;
5945 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005946 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005947
Chris Lattnerdc226c22010-10-01 22:42:38 +00005948 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005949 bool Done = false;
5950 while (!Done) {
5951 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005952 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005953 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005954 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005955 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005956 case 'S':
5957 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5958 assert(!Signed && "Can't use 'S' modifier multiple times!");
5959 Signed = true;
5960 break;
5961 case 'U':
5962 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5963 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5964 Unsigned = true;
5965 break;
5966 case 'L':
5967 assert(HowLong <= 2 && "Can't have LLLL modifier");
5968 ++HowLong;
5969 break;
5970 }
5971 }
5972
5973 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005974
Chris Lattnerecd79c62009-06-14 00:45:47 +00005975 // Read the base type.
5976 switch (*Str++) {
5977 default: assert(0 && "Unknown builtin type letter!");
5978 case 'v':
5979 assert(HowLong == 0 && !Signed && !Unsigned &&
5980 "Bad modifiers used with 'v'!");
5981 Type = Context.VoidTy;
5982 break;
5983 case 'f':
5984 assert(HowLong == 0 && !Signed && !Unsigned &&
5985 "Bad modifiers used with 'f'!");
5986 Type = Context.FloatTy;
5987 break;
5988 case 'd':
5989 assert(HowLong < 2 && !Signed && !Unsigned &&
5990 "Bad modifiers used with 'd'!");
5991 if (HowLong)
5992 Type = Context.LongDoubleTy;
5993 else
5994 Type = Context.DoubleTy;
5995 break;
5996 case 's':
5997 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5998 if (Unsigned)
5999 Type = Context.UnsignedShortTy;
6000 else
6001 Type = Context.ShortTy;
6002 break;
6003 case 'i':
6004 if (HowLong == 3)
6005 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6006 else if (HowLong == 2)
6007 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6008 else if (HowLong == 1)
6009 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6010 else
6011 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6012 break;
6013 case 'c':
6014 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6015 if (Signed)
6016 Type = Context.SignedCharTy;
6017 else if (Unsigned)
6018 Type = Context.UnsignedCharTy;
6019 else
6020 Type = Context.CharTy;
6021 break;
6022 case 'b': // boolean
6023 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6024 Type = Context.BoolTy;
6025 break;
6026 case 'z': // size_t.
6027 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6028 Type = Context.getSizeType();
6029 break;
6030 case 'F':
6031 Type = Context.getCFConstantStringType();
6032 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006033 case 'G':
6034 Type = Context.getObjCIdType();
6035 break;
6036 case 'H':
6037 Type = Context.getObjCSelType();
6038 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006039 case 'a':
6040 Type = Context.getBuiltinVaListType();
6041 assert(!Type.isNull() && "builtin va list type not initialized!");
6042 break;
6043 case 'A':
6044 // This is a "reference" to a va_list; however, what exactly
6045 // this means depends on how va_list is defined. There are two
6046 // different kinds of va_list: ones passed by value, and ones
6047 // passed by reference. An example of a by-value va_list is
6048 // x86, where va_list is a char*. An example of by-ref va_list
6049 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6050 // we want this argument to be a char*&; for x86-64, we want
6051 // it to be a __va_list_tag*.
6052 Type = Context.getBuiltinVaListType();
6053 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006054 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006055 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006056 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006057 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006058 break;
6059 case 'V': {
6060 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006061 unsigned NumElements = strtoul(Str, &End, 10);
6062 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006063 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006064
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006065 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6066 RequiresICE, false);
6067 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006068
6069 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006070 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006071 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006072 break;
6073 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006074 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006075 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6076 false);
6077 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006078 Type = Context.getComplexType(ElementType);
6079 break;
6080 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006081 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006082 Type = Context.getFILEType();
6083 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006084 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006085 return QualType();
6086 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006087 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006088 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006089 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006090 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006091 else
6092 Type = Context.getjmp_bufType();
6093
Mike Stump2adb4da2009-07-28 23:47:15 +00006094 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006095 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006096 return QualType();
6097 }
6098 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006099 }
Mike Stump11289f42009-09-09 15:08:12 +00006100
Chris Lattnerdc226c22010-10-01 22:42:38 +00006101 // If there are modifiers and if we're allowed to parse them, go for it.
6102 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006103 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006104 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006105 default: Done = true; --Str; break;
6106 case '*':
6107 case '&': {
6108 // Both pointers and references can have their pointee types
6109 // qualified with an address space.
6110 char *End;
6111 unsigned AddrSpace = strtoul(Str, &End, 10);
6112 if (End != Str && AddrSpace != 0) {
6113 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6114 Str = End;
6115 }
6116 if (c == '*')
6117 Type = Context.getPointerType(Type);
6118 else
6119 Type = Context.getLValueReferenceType(Type);
6120 break;
6121 }
6122 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6123 case 'C':
6124 Type = Type.withConst();
6125 break;
6126 case 'D':
6127 Type = Context.getVolatileType(Type);
6128 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006129 }
6130 }
Chris Lattner84733392010-10-01 07:13:18 +00006131
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006132 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006133 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006134
Chris Lattnerecd79c62009-06-14 00:45:47 +00006135 return Type;
6136}
6137
6138/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006139QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006140 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006141 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006142 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006143
Chris Lattnerecd79c62009-06-14 00:45:47 +00006144 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006145
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006146 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006147 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006148 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6149 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006150 if (Error != GE_None)
6151 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006152
6153 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6154
Chris Lattnerecd79c62009-06-14 00:45:47 +00006155 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006156 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006157 if (Error != GE_None)
6158 return QualType();
6159
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006160 // If this argument is required to be an IntegerConstantExpression and the
6161 // caller cares, fill in the bitmask we return.
6162 if (RequiresICE && IntegerConstantArgs)
6163 *IntegerConstantArgs |= 1 << ArgTypes.size();
6164
Chris Lattnerecd79c62009-06-14 00:45:47 +00006165 // Do array -> pointer decay. The builtin should use the decayed type.
6166 if (Ty->isArrayType())
6167 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006168
Chris Lattnerecd79c62009-06-14 00:45:47 +00006169 ArgTypes.push_back(Ty);
6170 }
6171
6172 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6173 "'.' should only occur at end of builtin type list!");
6174
John McCall991eb4b2010-12-21 00:44:39 +00006175 FunctionType::ExtInfo EI;
6176 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6177
6178 bool Variadic = (TypeStr[0] == '.');
6179
6180 // We really shouldn't be making a no-proto type here, especially in C++.
6181 if (ArgTypes.empty() && Variadic)
6182 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006183
John McCalldb40c7f2010-12-14 08:05:40 +00006184 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006185 EPI.ExtInfo = EI;
6186 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006187
6188 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006189}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006190
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006191GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6192 GVALinkage External = GVA_StrongExternal;
6193
6194 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006195 switch (L) {
6196 case NoLinkage:
6197 case InternalLinkage:
6198 case UniqueExternalLinkage:
6199 return GVA_Internal;
6200
6201 case ExternalLinkage:
6202 switch (FD->getTemplateSpecializationKind()) {
6203 case TSK_Undeclared:
6204 case TSK_ExplicitSpecialization:
6205 External = GVA_StrongExternal;
6206 break;
6207
6208 case TSK_ExplicitInstantiationDefinition:
6209 return GVA_ExplicitTemplateInstantiation;
6210
6211 case TSK_ExplicitInstantiationDeclaration:
6212 case TSK_ImplicitInstantiation:
6213 External = GVA_TemplateInstantiation;
6214 break;
6215 }
6216 }
6217
6218 if (!FD->isInlined())
6219 return External;
6220
6221 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6222 // GNU or C99 inline semantics. Determine whether this symbol should be
6223 // externally visible.
6224 if (FD->isInlineDefinitionExternallyVisible())
6225 return External;
6226
6227 // C99 inline semantics, where the symbol is not externally visible.
6228 return GVA_C99Inline;
6229 }
6230
6231 // C++0x [temp.explicit]p9:
6232 // [ Note: The intent is that an inline function that is the subject of
6233 // an explicit instantiation declaration will still be implicitly
6234 // instantiated when used so that the body can be considered for
6235 // inlining, but that no out-of-line copy of the inline function would be
6236 // generated in the translation unit. -- end note ]
6237 if (FD->getTemplateSpecializationKind()
6238 == TSK_ExplicitInstantiationDeclaration)
6239 return GVA_C99Inline;
6240
6241 return GVA_CXXInline;
6242}
6243
6244GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6245 // If this is a static data member, compute the kind of template
6246 // specialization. Otherwise, this variable is not part of a
6247 // template.
6248 TemplateSpecializationKind TSK = TSK_Undeclared;
6249 if (VD->isStaticDataMember())
6250 TSK = VD->getTemplateSpecializationKind();
6251
6252 Linkage L = VD->getLinkage();
6253 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6254 VD->getType()->getLinkage() == UniqueExternalLinkage)
6255 L = UniqueExternalLinkage;
6256
6257 switch (L) {
6258 case NoLinkage:
6259 case InternalLinkage:
6260 case UniqueExternalLinkage:
6261 return GVA_Internal;
6262
6263 case ExternalLinkage:
6264 switch (TSK) {
6265 case TSK_Undeclared:
6266 case TSK_ExplicitSpecialization:
6267 return GVA_StrongExternal;
6268
6269 case TSK_ExplicitInstantiationDeclaration:
6270 llvm_unreachable("Variable should not be instantiated");
6271 // Fall through to treat this like any other instantiation.
6272
6273 case TSK_ExplicitInstantiationDefinition:
6274 return GVA_ExplicitTemplateInstantiation;
6275
6276 case TSK_ImplicitInstantiation:
6277 return GVA_TemplateInstantiation;
6278 }
6279 }
6280
6281 return GVA_StrongExternal;
6282}
6283
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006284bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006285 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6286 if (!VD->isFileVarDecl())
6287 return false;
6288 } else if (!isa<FunctionDecl>(D))
6289 return false;
6290
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006291 // Weak references don't produce any output by themselves.
6292 if (D->hasAttr<WeakRefAttr>())
6293 return false;
6294
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006295 // Aliases and used decls are required.
6296 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6297 return true;
6298
6299 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6300 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006301 if (!FD->doesThisDeclarationHaveABody())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006302 return false;
6303
6304 // Constructors and destructors are required.
6305 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6306 return true;
6307
6308 // The key function for a class is required.
6309 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6310 const CXXRecordDecl *RD = MD->getParent();
6311 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6312 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6313 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6314 return true;
6315 }
6316 }
6317
6318 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6319
6320 // static, static inline, always_inline, and extern inline functions can
6321 // always be deferred. Normal inline functions can be deferred in C99/C++.
6322 // Implicit template instantiations can also be deferred in C++.
6323 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6324 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6325 return false;
6326 return true;
6327 }
6328
6329 const VarDecl *VD = cast<VarDecl>(D);
6330 assert(VD->isFileVarDecl() && "Expected file scoped var");
6331
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006332 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6333 return false;
6334
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006335 // Structs that have non-trivial constructors or destructors are required.
6336
6337 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006338 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006339 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6340 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006341 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6342 RD->hasTrivialCopyConstructor() &&
6343 RD->hasTrivialMoveConstructor() &&
6344 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006345 return true;
6346 }
6347 }
6348
6349 GVALinkage L = GetGVALinkageForVariable(VD);
6350 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6351 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6352 return false;
6353 }
6354
6355 return true;
6356}
Charles Davis53c59df2010-08-16 03:33:14 +00006357
Charles Davis99202b32010-11-09 18:04:24 +00006358CallingConv ASTContext::getDefaultMethodCallConv() {
6359 // Pass through to the C++ ABI object
6360 return ABI->getDefaultMethodCallConv();
6361}
6362
Jay Foad39c79802011-01-12 09:06:06 +00006363bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006364 // Pass through to the C++ ABI object
6365 return ABI->isNearlyEmpty(RD);
6366}
6367
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006368MangleContext *ASTContext::createMangleContext() {
6369 switch (Target.getCXXABI()) {
6370 case CXXABI_ARM:
6371 case CXXABI_Itanium:
6372 return createItaniumMangleContext(*this, getDiagnostics());
6373 case CXXABI_Microsoft:
6374 return createMicrosoftMangleContext(*this, getDiagnostics());
6375 }
6376 assert(0 && "Unsupported ABI");
6377 return 0;
6378}
6379
Charles Davis53c59df2010-08-16 03:33:14 +00006380CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006381
6382size_t ASTContext::getSideTableAllocatedMemory() const {
6383 size_t bytes = 0;
6384 bytes += ASTRecordLayouts.getMemorySize();
6385 bytes += ObjCLayouts.getMemorySize();
6386 bytes += KeyFunctions.getMemorySize();
6387 bytes += ObjCImpls.getMemorySize();
6388 bytes += BlockVarCopyInits.getMemorySize();
6389 bytes += DeclAttrs.getMemorySize();
6390 bytes += InstantiatedFromStaticDataMember.getMemorySize();
6391 bytes += InstantiatedFromUsingDecl.getMemorySize();
6392 bytes += InstantiatedFromUsingShadowDecl.getMemorySize();
6393 bytes += InstantiatedFromUnnamedFieldDecl.getMemorySize();
6394 return bytes;
6395}
6396