blob: 544fc1ababfa55ef26dee570ed3e06a4a5f0671b [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 Jahanianb26d5782011-06-28 18:05:25 +00001092 else {
1093 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1094 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1095 Iv= Iv->getNextIvar())
1096 Ivars.push_back(Iv);
1097 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001098}
1099
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001100/// CollectInheritedProtocols - Collect all protocols in current class and
1101/// those inherited by it.
1102void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001103 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001104 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001105 // We can use protocol_iterator here instead of
1106 // all_referenced_protocol_iterator since we are walking all categories.
1107 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1108 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001109 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001110 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001111 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001112 PE = Proto->protocol_end(); P != PE; ++P) {
1113 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001114 CollectInheritedProtocols(*P, Protocols);
1115 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001116 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001117
1118 // Categories of this Interface.
1119 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1120 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1121 CollectInheritedProtocols(CDeclChain, Protocols);
1122 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1123 while (SD) {
1124 CollectInheritedProtocols(SD, Protocols);
1125 SD = SD->getSuperClass();
1126 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001127 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001128 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001129 PE = OC->protocol_end(); P != PE; ++P) {
1130 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001131 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001132 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1133 PE = Proto->protocol_end(); P != PE; ++P)
1134 CollectInheritedProtocols(*P, Protocols);
1135 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001136 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001137 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1138 PE = OP->protocol_end(); P != PE; ++P) {
1139 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001140 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001141 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1142 PE = Proto->protocol_end(); P != PE; ++P)
1143 CollectInheritedProtocols(*P, Protocols);
1144 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001145 }
1146}
1147
Jay Foad39c79802011-01-12 09:06:06 +00001148unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001149 unsigned count = 0;
1150 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001151 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1152 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001153 count += CDecl->ivar_size();
1154
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001155 // Count ivar defined in this class's implementation. This
1156 // includes synthesized ivars.
1157 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001158 count += ImplDecl->ivar_size();
1159
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001160 return count;
1161}
1162
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001163/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1164ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1165 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1166 I = ObjCImpls.find(D);
1167 if (I != ObjCImpls.end())
1168 return cast<ObjCImplementationDecl>(I->second);
1169 return 0;
1170}
1171/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1172ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1173 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1174 I = ObjCImpls.find(D);
1175 if (I != ObjCImpls.end())
1176 return cast<ObjCCategoryImplDecl>(I->second);
1177 return 0;
1178}
1179
1180/// \brief Set the implementation of ObjCInterfaceDecl.
1181void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1182 ObjCImplementationDecl *ImplD) {
1183 assert(IFaceD && ImplD && "Passed null params");
1184 ObjCImpls[IFaceD] = ImplD;
1185}
1186/// \brief Set the implementation of ObjCCategoryDecl.
1187void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1188 ObjCCategoryImplDecl *ImplD) {
1189 assert(CatD && ImplD && "Passed null params");
1190 ObjCImpls[CatD] = ImplD;
1191}
1192
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001193/// \brief Get the copy initialization expression of VarDecl,or NULL if
1194/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001195Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001196 assert(VD && "Passed null params");
1197 assert(VD->hasAttr<BlocksAttr>() &&
1198 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001199 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001200 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001201 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1202}
1203
1204/// \brief Set the copy inialization expression of a block var decl.
1205void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1206 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001207 assert(VD->hasAttr<BlocksAttr>() &&
1208 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001209 BlockVarCopyInits[VD] = Init;
1210}
1211
John McCallbcd03502009-12-07 02:54:59 +00001212/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001213///
John McCallbcd03502009-12-07 02:54:59 +00001214/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001215/// the TypeLoc wrappers.
1216///
1217/// \param T the type that will be the basis for type source info. This type
1218/// should refer to how the declarator was written in source code, not to
1219/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001220TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001221 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001222 if (!DataSize)
1223 DataSize = TypeLoc::getFullDataSizeForType(T);
1224 else
1225 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001226 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001227
John McCallbcd03502009-12-07 02:54:59 +00001228 TypeSourceInfo *TInfo =
1229 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1230 new (TInfo) TypeSourceInfo(T);
1231 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001232}
1233
John McCallbcd03502009-12-07 02:54:59 +00001234TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001235 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001236 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001237 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001238 return DI;
1239}
1240
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001241const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001242ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001243 return getObjCLayout(D, 0);
1244}
1245
1246const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001247ASTContext::getASTObjCImplementationLayout(
1248 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001249 return getObjCLayout(D->getClassInterface(), D);
1250}
1251
Chris Lattner983a8bb2007-07-13 22:13:22 +00001252//===----------------------------------------------------------------------===//
1253// Type creation/memoization methods
1254//===----------------------------------------------------------------------===//
1255
Jay Foad39c79802011-01-12 09:06:06 +00001256QualType
John McCall33ddac02011-01-19 10:06:00 +00001257ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1258 unsigned fastQuals = quals.getFastQualifiers();
1259 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001260
1261 // Check if we've already instantiated this type.
1262 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001263 ExtQuals::Profile(ID, baseType, quals);
1264 void *insertPos = 0;
1265 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1266 assert(eq->getQualifiers() == quals);
1267 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001268 }
1269
John McCall33ddac02011-01-19 10:06:00 +00001270 // If the base type is not canonical, make the appropriate canonical type.
1271 QualType canon;
1272 if (!baseType->isCanonicalUnqualified()) {
1273 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1274 canonSplit.second.addConsistentQualifiers(quals);
1275 canon = getExtQualType(canonSplit.first, canonSplit.second);
1276
1277 // Re-find the insert position.
1278 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1279 }
1280
1281 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1282 ExtQualNodes.InsertNode(eq, insertPos);
1283 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001284}
1285
Jay Foad39c79802011-01-12 09:06:06 +00001286QualType
1287ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001288 QualType CanT = getCanonicalType(T);
1289 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001290 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001291
John McCall8ccfcb52009-09-24 19:53:00 +00001292 // If we are composing extended qualifiers together, merge together
1293 // into one ExtQuals node.
1294 QualifierCollector Quals;
1295 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001296
John McCall8ccfcb52009-09-24 19:53:00 +00001297 // If this type already has an address space specified, it cannot get
1298 // another one.
1299 assert(!Quals.hasAddressSpace() &&
1300 "Type cannot be in multiple addr spaces!");
1301 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001302
John McCall8ccfcb52009-09-24 19:53:00 +00001303 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001304}
1305
Chris Lattnerd60183d2009-02-18 22:53:11 +00001306QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001307 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001308 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001309 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001310 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001311
John McCall53fa7142010-12-24 02:08:15 +00001312 if (const PointerType *ptr = T->getAs<PointerType>()) {
1313 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001314 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001315 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1316 return getPointerType(ResultType);
1317 }
1318 }
Mike Stump11289f42009-09-09 15:08:12 +00001319
John McCall8ccfcb52009-09-24 19:53:00 +00001320 // If we are composing extended qualifiers together, merge together
1321 // into one ExtQuals node.
1322 QualifierCollector Quals;
1323 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001324
John McCall8ccfcb52009-09-24 19:53:00 +00001325 // If this type already has an ObjCGC specified, it cannot get
1326 // another one.
1327 assert(!Quals.hasObjCGCAttr() &&
1328 "Type cannot have multiple ObjCGCs!");
1329 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001330
John McCall8ccfcb52009-09-24 19:53:00 +00001331 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001332}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001333
John McCall4f5019e2010-12-19 02:44:49 +00001334const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1335 FunctionType::ExtInfo Info) {
1336 if (T->getExtInfo() == Info)
1337 return T;
1338
1339 QualType Result;
1340 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1341 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1342 } else {
1343 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1344 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1345 EPI.ExtInfo = Info;
1346 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1347 FPT->getNumArgs(), EPI);
1348 }
1349
1350 return cast<FunctionType>(Result.getTypePtr());
1351}
1352
Chris Lattnerc6395932007-06-22 20:56:16 +00001353/// getComplexType - Return the uniqued reference to the type for a complex
1354/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001355QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001356 // Unique pointers, to guarantee there is only one pointer of a particular
1357 // structure.
1358 llvm::FoldingSetNodeID ID;
1359 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001360
Chris Lattnerc6395932007-06-22 20:56:16 +00001361 void *InsertPos = 0;
1362 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1363 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001364
Chris Lattnerc6395932007-06-22 20:56:16 +00001365 // If the pointee type isn't canonical, this won't be a canonical type either,
1366 // so fill in the canonical type field.
1367 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001368 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001369 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001370
Chris Lattnerc6395932007-06-22 20:56:16 +00001371 // Get the new insert position for the node we care about.
1372 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001373 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001374 }
John McCall90d1c2d2009-09-24 23:30:46 +00001375 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001376 Types.push_back(New);
1377 ComplexTypes.InsertNode(New, InsertPos);
1378 return QualType(New, 0);
1379}
1380
Chris Lattner970e54e2006-11-12 00:37:36 +00001381/// getPointerType - Return the uniqued reference to the type for a pointer to
1382/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001383QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001384 // Unique pointers, to guarantee there is only one pointer of a particular
1385 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001386 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001387 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001388
Chris Lattner67521df2007-01-27 01:29:36 +00001389 void *InsertPos = 0;
1390 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001391 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001392
Chris Lattner7ccecb92006-11-12 08:50:50 +00001393 // If the pointee type isn't canonical, this won't be a canonical type either,
1394 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001395 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001396 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001397 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001398
Chris Lattner67521df2007-01-27 01:29:36 +00001399 // Get the new insert position for the node we care about.
1400 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001401 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001402 }
John McCall90d1c2d2009-09-24 23:30:46 +00001403 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001404 Types.push_back(New);
1405 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001406 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001407}
1408
Mike Stump11289f42009-09-09 15:08:12 +00001409/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001410/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001411QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001412 assert(T->isFunctionType() && "block of function types only");
1413 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001414 // structure.
1415 llvm::FoldingSetNodeID ID;
1416 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001417
Steve Naroffec33ed92008-08-27 16:04:49 +00001418 void *InsertPos = 0;
1419 if (BlockPointerType *PT =
1420 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1421 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001422
1423 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001424 // type either so fill in the canonical type field.
1425 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001426 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001427 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001428
Steve Naroffec33ed92008-08-27 16:04:49 +00001429 // Get the new insert position for the node we care about.
1430 BlockPointerType *NewIP =
1431 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001432 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001433 }
John McCall90d1c2d2009-09-24 23:30:46 +00001434 BlockPointerType *New
1435 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001436 Types.push_back(New);
1437 BlockPointerTypes.InsertNode(New, InsertPos);
1438 return QualType(New, 0);
1439}
1440
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001441/// getLValueReferenceType - Return the uniqued reference to the type for an
1442/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001443QualType
1444ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001445 assert(getCanonicalType(T) != OverloadTy &&
1446 "Unresolved overloaded function type");
1447
Bill Wendling3708c182007-05-27 10:15:43 +00001448 // Unique pointers, to guarantee there is only one pointer of a particular
1449 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001450 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001451 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001452
1453 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001454 if (LValueReferenceType *RT =
1455 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001456 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001457
John McCallfc93cf92009-10-22 22:37:11 +00001458 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1459
Bill Wendling3708c182007-05-27 10:15:43 +00001460 // If the referencee type isn't canonical, this won't be a canonical type
1461 // either, so fill in the canonical type field.
1462 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001463 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1464 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1465 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001466
Bill Wendling3708c182007-05-27 10:15:43 +00001467 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001468 LValueReferenceType *NewIP =
1469 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001470 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001471 }
1472
John McCall90d1c2d2009-09-24 23:30:46 +00001473 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001474 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1475 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001476 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001477 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001478
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001479 return QualType(New, 0);
1480}
1481
1482/// getRValueReferenceType - Return the uniqued reference to the type for an
1483/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001484QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001485 // Unique pointers, to guarantee there is only one pointer of a particular
1486 // structure.
1487 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001488 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001489
1490 void *InsertPos = 0;
1491 if (RValueReferenceType *RT =
1492 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1493 return QualType(RT, 0);
1494
John McCallfc93cf92009-10-22 22:37:11 +00001495 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1496
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001497 // If the referencee type isn't canonical, this won't be a canonical type
1498 // either, so fill in the canonical type field.
1499 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001500 if (InnerRef || !T.isCanonical()) {
1501 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1502 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001503
1504 // Get the new insert position for the node we care about.
1505 RValueReferenceType *NewIP =
1506 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001507 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001508 }
1509
John McCall90d1c2d2009-09-24 23:30:46 +00001510 RValueReferenceType *New
1511 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001512 Types.push_back(New);
1513 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001514 return QualType(New, 0);
1515}
1516
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001517/// getMemberPointerType - Return the uniqued reference to the type for a
1518/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001519QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001520 // Unique pointers, to guarantee there is only one pointer of a particular
1521 // structure.
1522 llvm::FoldingSetNodeID ID;
1523 MemberPointerType::Profile(ID, T, Cls);
1524
1525 void *InsertPos = 0;
1526 if (MemberPointerType *PT =
1527 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1528 return QualType(PT, 0);
1529
1530 // If the pointee or class type isn't canonical, this won't be a canonical
1531 // type either, so fill in the canonical type field.
1532 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001533 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001534 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1535
1536 // Get the new insert position for the node we care about.
1537 MemberPointerType *NewIP =
1538 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001539 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001540 }
John McCall90d1c2d2009-09-24 23:30:46 +00001541 MemberPointerType *New
1542 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001543 Types.push_back(New);
1544 MemberPointerTypes.InsertNode(New, InsertPos);
1545 return QualType(New, 0);
1546}
1547
Mike Stump11289f42009-09-09 15:08:12 +00001548/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001549/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001550QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001551 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001552 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001553 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001554 assert((EltTy->isDependentType() ||
1555 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001556 "Constant array of VLAs is illegal!");
1557
Chris Lattnere2df3f92009-05-13 04:12:56 +00001558 // Convert the array size into a canonical width matching the pointer size for
1559 // the target.
1560 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001561 ArySize =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001562 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001563
Chris Lattner23b7eb62007-06-15 23:05:46 +00001564 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001565 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001566
Chris Lattner36f8e652007-01-27 08:31:04 +00001567 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001568 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001569 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001570 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001571
John McCall33ddac02011-01-19 10:06:00 +00001572 // If the element type isn't canonical or has qualifiers, this won't
1573 // be a canonical type either, so fill in the canonical type field.
1574 QualType Canon;
1575 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1576 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1577 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001578 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001579 Canon = getQualifiedType(Canon, canonSplit.second);
1580
Chris Lattner36f8e652007-01-27 08:31:04 +00001581 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001582 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001583 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001584 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001585 }
Mike Stump11289f42009-09-09 15:08:12 +00001586
John McCall90d1c2d2009-09-24 23:30:46 +00001587 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001588 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001589 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001590 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001591 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001592}
1593
John McCall06549462011-01-18 08:40:38 +00001594/// getVariableArrayDecayedType - Turns the given type, which may be
1595/// variably-modified, into the corresponding type with all the known
1596/// sizes replaced with [*].
1597QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1598 // Vastly most common case.
1599 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001600
John McCall06549462011-01-18 08:40:38 +00001601 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001602
John McCall06549462011-01-18 08:40:38 +00001603 SplitQualType split = type.getSplitDesugaredType();
1604 const Type *ty = split.first;
1605 switch (ty->getTypeClass()) {
1606#define TYPE(Class, Base)
1607#define ABSTRACT_TYPE(Class, Base)
1608#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1609#include "clang/AST/TypeNodes.def"
1610 llvm_unreachable("didn't desugar past all non-canonical types?");
1611
1612 // These types should never be variably-modified.
1613 case Type::Builtin:
1614 case Type::Complex:
1615 case Type::Vector:
1616 case Type::ExtVector:
1617 case Type::DependentSizedExtVector:
1618 case Type::ObjCObject:
1619 case Type::ObjCInterface:
1620 case Type::ObjCObjectPointer:
1621 case Type::Record:
1622 case Type::Enum:
1623 case Type::UnresolvedUsing:
1624 case Type::TypeOfExpr:
1625 case Type::TypeOf:
1626 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001627 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001628 case Type::DependentName:
1629 case Type::InjectedClassName:
1630 case Type::TemplateSpecialization:
1631 case Type::DependentTemplateSpecialization:
1632 case Type::TemplateTypeParm:
1633 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001634 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001635 case Type::PackExpansion:
1636 llvm_unreachable("type should never be variably-modified");
1637
1638 // These types can be variably-modified but should never need to
1639 // further decay.
1640 case Type::FunctionNoProto:
1641 case Type::FunctionProto:
1642 case Type::BlockPointer:
1643 case Type::MemberPointer:
1644 return type;
1645
1646 // These types can be variably-modified. All these modifications
1647 // preserve structure except as noted by comments.
1648 // TODO: if we ever care about optimizing VLAs, there are no-op
1649 // optimizations available here.
1650 case Type::Pointer:
1651 result = getPointerType(getVariableArrayDecayedType(
1652 cast<PointerType>(ty)->getPointeeType()));
1653 break;
1654
1655 case Type::LValueReference: {
1656 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1657 result = getLValueReferenceType(
1658 getVariableArrayDecayedType(lv->getPointeeType()),
1659 lv->isSpelledAsLValue());
1660 break;
1661 }
1662
1663 case Type::RValueReference: {
1664 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1665 result = getRValueReferenceType(
1666 getVariableArrayDecayedType(lv->getPointeeType()));
1667 break;
1668 }
1669
1670 case Type::ConstantArray: {
1671 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1672 result = getConstantArrayType(
1673 getVariableArrayDecayedType(cat->getElementType()),
1674 cat->getSize(),
1675 cat->getSizeModifier(),
1676 cat->getIndexTypeCVRQualifiers());
1677 break;
1678 }
1679
1680 case Type::DependentSizedArray: {
1681 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1682 result = getDependentSizedArrayType(
1683 getVariableArrayDecayedType(dat->getElementType()),
1684 dat->getSizeExpr(),
1685 dat->getSizeModifier(),
1686 dat->getIndexTypeCVRQualifiers(),
1687 dat->getBracketsRange());
1688 break;
1689 }
1690
1691 // Turn incomplete types into [*] types.
1692 case Type::IncompleteArray: {
1693 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1694 result = getVariableArrayType(
1695 getVariableArrayDecayedType(iat->getElementType()),
1696 /*size*/ 0,
1697 ArrayType::Normal,
1698 iat->getIndexTypeCVRQualifiers(),
1699 SourceRange());
1700 break;
1701 }
1702
1703 // Turn VLA types into [*] types.
1704 case Type::VariableArray: {
1705 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1706 result = getVariableArrayType(
1707 getVariableArrayDecayedType(vat->getElementType()),
1708 /*size*/ 0,
1709 ArrayType::Star,
1710 vat->getIndexTypeCVRQualifiers(),
1711 vat->getBracketsRange());
1712 break;
1713 }
1714 }
1715
1716 // Apply the top-level qualifiers from the original.
1717 return getQualifiedType(result, split.second);
1718}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001719
Steve Naroffcadebd02007-08-30 18:14:25 +00001720/// getVariableArrayType - Returns a non-unique reference to the type for a
1721/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001722QualType ASTContext::getVariableArrayType(QualType EltTy,
1723 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001724 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001725 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001726 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001727 // Since we don't unique expressions, it isn't possible to unique VLA's
1728 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001729 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001730
John McCall33ddac02011-01-19 10:06:00 +00001731 // Be sure to pull qualifiers off the element type.
1732 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1733 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1734 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001735 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001736 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001737 }
1738
John McCall90d1c2d2009-09-24 23:30:46 +00001739 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001740 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001741
1742 VariableArrayTypes.push_back(New);
1743 Types.push_back(New);
1744 return QualType(New, 0);
1745}
1746
Douglas Gregor4619e432008-12-05 23:32:09 +00001747/// getDependentSizedArrayType - Returns a non-unique reference to
1748/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001749/// type.
John McCall33ddac02011-01-19 10:06:00 +00001750QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1751 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001752 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001753 unsigned elementTypeQuals,
1754 SourceRange brackets) const {
1755 assert((!numElements || numElements->isTypeDependent() ||
1756 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001757 "Size must be type- or value-dependent!");
1758
John McCall33ddac02011-01-19 10:06:00 +00001759 // Dependently-sized array types that do not have a specified number
1760 // of elements will have their sizes deduced from a dependent
1761 // initializer. We do no canonicalization here at all, which is okay
1762 // because they can't be used in most locations.
1763 if (!numElements) {
1764 DependentSizedArrayType *newType
1765 = new (*this, TypeAlignment)
1766 DependentSizedArrayType(*this, elementType, QualType(),
1767 numElements, ASM, elementTypeQuals,
1768 brackets);
1769 Types.push_back(newType);
1770 return QualType(newType, 0);
1771 }
1772
1773 // Otherwise, we actually build a new type every time, but we
1774 // also build a canonical type.
1775
1776 SplitQualType canonElementType = getCanonicalType(elementType).split();
1777
1778 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001779 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001780 DependentSizedArrayType::Profile(ID, *this,
1781 QualType(canonElementType.first, 0),
1782 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001783
John McCall33ddac02011-01-19 10:06:00 +00001784 // Look for an existing type with these properties.
1785 DependentSizedArrayType *canonTy =
1786 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001787
John McCall33ddac02011-01-19 10:06:00 +00001788 // If we don't have one, build one.
1789 if (!canonTy) {
1790 canonTy = new (*this, TypeAlignment)
1791 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1792 QualType(), numElements, ASM, elementTypeQuals,
1793 brackets);
1794 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1795 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001796 }
1797
John McCall33ddac02011-01-19 10:06:00 +00001798 // Apply qualifiers from the element type to the array.
1799 QualType canon = getQualifiedType(QualType(canonTy,0),
1800 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001801
John McCall33ddac02011-01-19 10:06:00 +00001802 // If we didn't need extra canonicalization for the element type,
1803 // then just use that as our result.
1804 if (QualType(canonElementType.first, 0) == elementType)
1805 return canon;
1806
1807 // Otherwise, we need to build a type which follows the spelling
1808 // of the element type.
1809 DependentSizedArrayType *sugaredType
1810 = new (*this, TypeAlignment)
1811 DependentSizedArrayType(*this, elementType, canon, numElements,
1812 ASM, elementTypeQuals, brackets);
1813 Types.push_back(sugaredType);
1814 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001815}
1816
John McCall33ddac02011-01-19 10:06:00 +00001817QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001818 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001819 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001820 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001821 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001822
John McCall33ddac02011-01-19 10:06:00 +00001823 void *insertPos = 0;
1824 if (IncompleteArrayType *iat =
1825 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1826 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001827
1828 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001829 // either, so fill in the canonical type field. We also have to pull
1830 // qualifiers off the element type.
1831 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001832
John McCall33ddac02011-01-19 10:06:00 +00001833 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1834 SplitQualType canonSplit = getCanonicalType(elementType).split();
1835 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1836 ASM, elementTypeQuals);
1837 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001838
1839 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001840 IncompleteArrayType *existing =
1841 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1842 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001843 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001844
John McCall33ddac02011-01-19 10:06:00 +00001845 IncompleteArrayType *newType = new (*this, TypeAlignment)
1846 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001847
John McCall33ddac02011-01-19 10:06:00 +00001848 IncompleteArrayTypes.InsertNode(newType, insertPos);
1849 Types.push_back(newType);
1850 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001851}
1852
Steve Naroff91fcddb2007-07-18 18:00:27 +00001853/// getVectorType - Return the unique reference to a vector type of
1854/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001855QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001856 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001857 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001858
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001859 // Check if we've already instantiated a vector of this type.
1860 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001861 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001862
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001863 void *InsertPos = 0;
1864 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1865 return QualType(VTP, 0);
1866
1867 // If the element type isn't canonical, this won't be a canonical type either,
1868 // so fill in the canonical type field.
1869 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001870 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001871 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001872
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001873 // Get the new insert position for the node we care about.
1874 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001875 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001876 }
John McCall90d1c2d2009-09-24 23:30:46 +00001877 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001878 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001879 VectorTypes.InsertNode(New, InsertPos);
1880 Types.push_back(New);
1881 return QualType(New, 0);
1882}
1883
Nate Begemance4d7fc2008-04-18 23:10:10 +00001884/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001885/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001886QualType
1887ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00001888 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00001889
Steve Naroff91fcddb2007-07-18 18:00:27 +00001890 // Check if we've already instantiated a vector of this type.
1891 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001892 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001893 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001894 void *InsertPos = 0;
1895 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1896 return QualType(VTP, 0);
1897
1898 // If the element type isn't canonical, this won't be a canonical type either,
1899 // so fill in the canonical type field.
1900 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001901 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001902 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001903
Steve Naroff91fcddb2007-07-18 18:00:27 +00001904 // Get the new insert position for the node we care about.
1905 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001906 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001907 }
John McCall90d1c2d2009-09-24 23:30:46 +00001908 ExtVectorType *New = new (*this, TypeAlignment)
1909 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001910 VectorTypes.InsertNode(New, InsertPos);
1911 Types.push_back(New);
1912 return QualType(New, 0);
1913}
1914
Jay Foad39c79802011-01-12 09:06:06 +00001915QualType
1916ASTContext::getDependentSizedExtVectorType(QualType vecType,
1917 Expr *SizeExpr,
1918 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001919 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001920 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001921 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001922
Douglas Gregor352169a2009-07-31 03:54:25 +00001923 void *InsertPos = 0;
1924 DependentSizedExtVectorType *Canon
1925 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1926 DependentSizedExtVectorType *New;
1927 if (Canon) {
1928 // We already have a canonical version of this array type; use it as
1929 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001930 New = new (*this, TypeAlignment)
1931 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1932 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001933 } else {
1934 QualType CanonVecTy = getCanonicalType(vecType);
1935 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001936 New = new (*this, TypeAlignment)
1937 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1938 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001939
1940 DependentSizedExtVectorType *CanonCheck
1941 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1942 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1943 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001944 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1945 } else {
1946 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1947 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001948 New = new (*this, TypeAlignment)
1949 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001950 }
1951 }
Mike Stump11289f42009-09-09 15:08:12 +00001952
Douglas Gregor758a8692009-06-17 21:51:59 +00001953 Types.push_back(New);
1954 return QualType(New, 0);
1955}
1956
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001957/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001958///
Jay Foad39c79802011-01-12 09:06:06 +00001959QualType
1960ASTContext::getFunctionNoProtoType(QualType ResultTy,
1961 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00001962 const CallingConv DefaultCC = Info.getCC();
1963 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1964 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001965 // Unique functions, to guarantee there is only one function of a particular
1966 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001967 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001968 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001969
Chris Lattner47955de2007-01-27 08:37:20 +00001970 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001971 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001972 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001973 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001974
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001975 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001976 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001977 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001978 Canonical =
1979 getFunctionNoProtoType(getCanonicalType(ResultTy),
1980 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001981
Chris Lattner47955de2007-01-27 08:37:20 +00001982 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001983 FunctionNoProtoType *NewIP =
1984 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001985 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001986 }
Mike Stump11289f42009-09-09 15:08:12 +00001987
Roman Divacky65b88cd2011-03-01 17:40:53 +00001988 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00001989 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00001990 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00001991 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001992 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001993 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001994}
1995
1996/// getFunctionType - Return a normal function type with a typed argument
1997/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00001998QualType
1999ASTContext::getFunctionType(QualType ResultTy,
2000 const QualType *ArgArray, unsigned NumArgs,
2001 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002002 // Unique functions, to guarantee there is only one function of a particular
2003 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002004 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002005 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002006
2007 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002008 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002009 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002010 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002011
2012 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002013 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002014 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002015 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002016 isCanonical = false;
2017
Roman Divacky65b88cd2011-03-01 17:40:53 +00002018 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2019 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2020 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002021
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002022 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002023 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002024 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002025 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002026 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002027 CanonicalArgs.reserve(NumArgs);
2028 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002029 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002030
John McCalldb40c7f2010-12-14 08:05:40 +00002031 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002032 CanonicalEPI.ExceptionSpecType = EST_None;
2033 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002034 CanonicalEPI.ExtInfo
2035 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2036
Chris Lattner76a00cf2008-04-06 22:59:24 +00002037 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002038 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002039 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002040
Chris Lattnerfd4de792007-01-27 01:15:32 +00002041 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002042 FunctionProtoType *NewIP =
2043 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002044 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002045 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002046
John McCall31168b02011-06-15 23:02:42 +00002047 // FunctionProtoType objects are allocated with extra bytes after
2048 // them for three variable size arrays at the end:
2049 // - parameter types
2050 // - exception types
2051 // - consumed-arguments flags
2052 // Instead of the exception types, there could be a noexcept
2053 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002054 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002055 NumArgs * sizeof(QualType);
2056 if (EPI.ExceptionSpecType == EST_Dynamic)
2057 Size += EPI.NumExceptions * sizeof(QualType);
2058 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002059 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002060 }
John McCall31168b02011-06-15 23:02:42 +00002061 if (EPI.ConsumedArguments)
2062 Size += NumArgs * sizeof(bool);
2063
John McCalldb40c7f2010-12-14 08:05:40 +00002064 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002065 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2066 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002067 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002068 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002069 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002070 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002071}
Chris Lattneref51c202006-11-10 07:17:23 +00002072
John McCalle78aac42010-03-10 03:28:59 +00002073#ifndef NDEBUG
2074static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2075 if (!isa<CXXRecordDecl>(D)) return false;
2076 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2077 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2078 return true;
2079 if (RD->getDescribedClassTemplate() &&
2080 !isa<ClassTemplateSpecializationDecl>(RD))
2081 return true;
2082 return false;
2083}
2084#endif
2085
2086/// getInjectedClassNameType - Return the unique reference to the
2087/// injected class name type for the specified templated declaration.
2088QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002089 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002090 assert(NeedsInjectedClassNameType(Decl));
2091 if (Decl->TypeForDecl) {
2092 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00002093 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00002094 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2095 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2096 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2097 } else {
John McCall424cec92011-01-19 06:33:43 +00002098 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002099 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002100 Decl->TypeForDecl = newType;
2101 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002102 }
2103 return QualType(Decl->TypeForDecl, 0);
2104}
2105
Douglas Gregor83a586e2008-04-13 21:07:44 +00002106/// getTypeDeclType - Return the unique reference to the type for the
2107/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002108QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002109 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002110 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002111
Richard Smithdda56e42011-04-15 14:24:37 +00002112 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002113 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002114
John McCall96f0b5f2010-03-10 06:48:02 +00002115 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2116 "Template type parameter types are always available.");
2117
John McCall81e38502010-02-16 03:57:14 +00002118 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002119 assert(!Record->getPreviousDeclaration() &&
2120 "struct/union has previous declaration");
2121 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002122 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002123 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002124 assert(!Enum->getPreviousDeclaration() &&
2125 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002126 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002127 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002128 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002129 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2130 Decl->TypeForDecl = newType;
2131 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002132 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002133 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002134
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002135 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002136}
2137
Chris Lattner32d920b2007-01-26 02:01:53 +00002138/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002139/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002140QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002141ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2142 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002143 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002144
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002145 if (Canonical.isNull())
2146 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002147 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002148 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002149 Decl->TypeForDecl = newType;
2150 Types.push_back(newType);
2151 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002152}
2153
Jay Foad39c79802011-01-12 09:06:06 +00002154QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002155 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2156
2157 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2158 if (PrevDecl->TypeForDecl)
2159 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2160
John McCall424cec92011-01-19 06:33:43 +00002161 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2162 Decl->TypeForDecl = newType;
2163 Types.push_back(newType);
2164 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002165}
2166
Jay Foad39c79802011-01-12 09:06:06 +00002167QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002168 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2169
2170 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2171 if (PrevDecl->TypeForDecl)
2172 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2173
John McCall424cec92011-01-19 06:33:43 +00002174 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2175 Decl->TypeForDecl = newType;
2176 Types.push_back(newType);
2177 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002178}
2179
John McCall81904512011-01-06 01:58:22 +00002180QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2181 QualType modifiedType,
2182 QualType equivalentType) {
2183 llvm::FoldingSetNodeID id;
2184 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2185
2186 void *insertPos = 0;
2187 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2188 if (type) return QualType(type, 0);
2189
2190 QualType canon = getCanonicalType(equivalentType);
2191 type = new (*this, TypeAlignment)
2192 AttributedType(canon, attrKind, modifiedType, equivalentType);
2193
2194 Types.push_back(type);
2195 AttributedTypes.InsertNode(type, insertPos);
2196
2197 return QualType(type, 0);
2198}
2199
2200
John McCallcebee162009-10-18 09:09:24 +00002201/// \brief Retrieve a substitution-result type.
2202QualType
2203ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002204 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002205 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002206 && "replacement types must always be canonical");
2207
2208 llvm::FoldingSetNodeID ID;
2209 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2210 void *InsertPos = 0;
2211 SubstTemplateTypeParmType *SubstParm
2212 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2213
2214 if (!SubstParm) {
2215 SubstParm = new (*this, TypeAlignment)
2216 SubstTemplateTypeParmType(Parm, Replacement);
2217 Types.push_back(SubstParm);
2218 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2219 }
2220
2221 return QualType(SubstParm, 0);
2222}
2223
Douglas Gregorada4b792011-01-14 02:55:32 +00002224/// \brief Retrieve a
2225QualType ASTContext::getSubstTemplateTypeParmPackType(
2226 const TemplateTypeParmType *Parm,
2227 const TemplateArgument &ArgPack) {
2228#ifndef NDEBUG
2229 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2230 PEnd = ArgPack.pack_end();
2231 P != PEnd; ++P) {
2232 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2233 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2234 }
2235#endif
2236
2237 llvm::FoldingSetNodeID ID;
2238 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2239 void *InsertPos = 0;
2240 if (SubstTemplateTypeParmPackType *SubstParm
2241 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2242 return QualType(SubstParm, 0);
2243
2244 QualType Canon;
2245 if (!Parm->isCanonicalUnqualified()) {
2246 Canon = getCanonicalType(QualType(Parm, 0));
2247 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2248 ArgPack);
2249 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2250 }
2251
2252 SubstTemplateTypeParmPackType *SubstParm
2253 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2254 ArgPack);
2255 Types.push_back(SubstParm);
2256 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2257 return QualType(SubstParm, 0);
2258}
2259
Douglas Gregoreff93e02009-02-05 23:33:38 +00002260/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002261/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002262/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002263QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002264 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002265 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002266 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002267 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002268 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002269 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002270 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2271
2272 if (TypeParm)
2273 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002274
Chandler Carruth08836322011-05-01 00:51:33 +00002275 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002276 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002277 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002278
2279 TemplateTypeParmType *TypeCheck
2280 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2281 assert(!TypeCheck && "Template type parameter canonical type broken");
2282 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002283 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002284 TypeParm = new (*this, TypeAlignment)
2285 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002286
2287 Types.push_back(TypeParm);
2288 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2289
2290 return QualType(TypeParm, 0);
2291}
2292
John McCalle78aac42010-03-10 03:28:59 +00002293TypeSourceInfo *
2294ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2295 SourceLocation NameLoc,
2296 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002297 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002298 assert(!Name.getAsDependentTemplateName() &&
2299 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002300 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002301
2302 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2303 TemplateSpecializationTypeLoc TL
2304 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2305 TL.setTemplateNameLoc(NameLoc);
2306 TL.setLAngleLoc(Args.getLAngleLoc());
2307 TL.setRAngleLoc(Args.getRAngleLoc());
2308 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2309 TL.setArgLocInfo(i, Args[i].getLocInfo());
2310 return DI;
2311}
2312
Mike Stump11289f42009-09-09 15:08:12 +00002313QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002314ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002315 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002316 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002317 assert(!Template.getAsDependentTemplateName() &&
2318 "No dependent template names here!");
2319
John McCall6b51f282009-11-23 01:53:49 +00002320 unsigned NumArgs = Args.size();
2321
John McCall0ad16662009-10-29 08:12:44 +00002322 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2323 ArgVec.reserve(NumArgs);
2324 for (unsigned i = 0; i != NumArgs; ++i)
2325 ArgVec.push_back(Args[i].getArgument());
2326
John McCall2408e322010-04-27 00:57:59 +00002327 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002328 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002329}
2330
2331QualType
2332ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002333 const TemplateArgument *Args,
2334 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002335 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002336 assert(!Template.getAsDependentTemplateName() &&
2337 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002338 // Look through qualified template names.
2339 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2340 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002341
Richard Smith3f1b5d02011-05-05 21:57:07 +00002342 bool isTypeAlias =
2343 Template.getAsTemplateDecl() &&
2344 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2345
2346 QualType CanonType;
2347 if (!Underlying.isNull())
2348 CanonType = getCanonicalType(Underlying);
2349 else {
2350 assert(!isTypeAlias &&
2351 "Underlying type for template alias must be computed by caller");
2352 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2353 NumArgs);
2354 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002355
Douglas Gregora8e02e72009-07-28 23:00:59 +00002356 // Allocate the (non-canonical) template specialization type, but don't
2357 // try to unique it: these types typically have location information that
2358 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002359 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2360 sizeof(TemplateArgument) * NumArgs +
2361 (isTypeAlias ? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002362 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002363 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002364 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002365 Args, NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002366 CanonType,
2367 isTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002368
Douglas Gregor8bf42052009-02-09 18:46:07 +00002369 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002370 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002371}
2372
Mike Stump11289f42009-09-09 15:08:12 +00002373QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002374ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2375 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002376 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002377 assert(!Template.getAsDependentTemplateName() &&
2378 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002379 assert((!Template.getAsTemplateDecl() ||
2380 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2381 "Underlying type for template alias must be computed by caller");
2382
Douglas Gregore29139c2011-03-03 17:04:51 +00002383 // Look through qualified template names.
2384 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2385 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002386
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002387 // Build the canonical template specialization type.
2388 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2389 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2390 CanonArgs.reserve(NumArgs);
2391 for (unsigned I = 0; I != NumArgs; ++I)
2392 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2393
2394 // Determine whether this canonical template specialization type already
2395 // exists.
2396 llvm::FoldingSetNodeID ID;
2397 TemplateSpecializationType::Profile(ID, CanonTemplate,
2398 CanonArgs.data(), NumArgs, *this);
2399
2400 void *InsertPos = 0;
2401 TemplateSpecializationType *Spec
2402 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2403
2404 if (!Spec) {
2405 // Allocate a new canonical template specialization type.
2406 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2407 sizeof(TemplateArgument) * NumArgs),
2408 TypeAlignment);
2409 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2410 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002411 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002412 Types.push_back(Spec);
2413 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2414 }
2415
2416 assert(Spec->isDependentType() &&
2417 "Non-dependent template-id type must have a canonical type");
2418 return QualType(Spec, 0);
2419}
2420
2421QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002422ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2423 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002424 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002425 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002426 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002427
2428 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002429 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002430 if (T)
2431 return QualType(T, 0);
2432
Douglas Gregorc42075a2010-02-04 18:10:26 +00002433 QualType Canon = NamedType;
2434 if (!Canon.isCanonical()) {
2435 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002436 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2437 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002438 (void)CheckT;
2439 }
2440
Abramo Bagnara6150c882010-05-11 21:36:43 +00002441 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002442 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002443 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002444 return QualType(T, 0);
2445}
2446
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002447QualType
Jay Foad39c79802011-01-12 09:06:06 +00002448ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002449 llvm::FoldingSetNodeID ID;
2450 ParenType::Profile(ID, InnerType);
2451
2452 void *InsertPos = 0;
2453 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2454 if (T)
2455 return QualType(T, 0);
2456
2457 QualType Canon = InnerType;
2458 if (!Canon.isCanonical()) {
2459 Canon = getCanonicalType(InnerType);
2460 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2461 assert(!CheckT && "Paren canonical type broken");
2462 (void)CheckT;
2463 }
2464
2465 T = new (*this) ParenType(InnerType, Canon);
2466 Types.push_back(T);
2467 ParenTypes.InsertNode(T, InsertPos);
2468 return QualType(T, 0);
2469}
2470
Douglas Gregor02085352010-03-31 20:19:30 +00002471QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2472 NestedNameSpecifier *NNS,
2473 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002474 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002475 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2476
2477 if (Canon.isNull()) {
2478 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002479 ElaboratedTypeKeyword CanonKeyword = Keyword;
2480 if (Keyword == ETK_None)
2481 CanonKeyword = ETK_Typename;
2482
2483 if (CanonNNS != NNS || CanonKeyword != Keyword)
2484 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002485 }
2486
2487 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002488 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002489
2490 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002491 DependentNameType *T
2492 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002493 if (T)
2494 return QualType(T, 0);
2495
Douglas Gregor02085352010-03-31 20:19:30 +00002496 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002497 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002498 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002499 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002500}
2501
Mike Stump11289f42009-09-09 15:08:12 +00002502QualType
John McCallc392f372010-06-11 00:33:02 +00002503ASTContext::getDependentTemplateSpecializationType(
2504 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002505 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002506 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002507 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002508 // TODO: avoid this copy
2509 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2510 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2511 ArgCopy.push_back(Args[I].getArgument());
2512 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2513 ArgCopy.size(),
2514 ArgCopy.data());
2515}
2516
2517QualType
2518ASTContext::getDependentTemplateSpecializationType(
2519 ElaboratedTypeKeyword Keyword,
2520 NestedNameSpecifier *NNS,
2521 const IdentifierInfo *Name,
2522 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002523 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002524 assert((!NNS || NNS->isDependent()) &&
2525 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002526
Douglas Gregorc42075a2010-02-04 18:10:26 +00002527 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002528 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2529 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002530
2531 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002532 DependentTemplateSpecializationType *T
2533 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002534 if (T)
2535 return QualType(T, 0);
2536
John McCallc392f372010-06-11 00:33:02 +00002537 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002538
John McCallc392f372010-06-11 00:33:02 +00002539 ElaboratedTypeKeyword CanonKeyword = Keyword;
2540 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2541
2542 bool AnyNonCanonArgs = false;
2543 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2544 for (unsigned I = 0; I != NumArgs; ++I) {
2545 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2546 if (!CanonArgs[I].structurallyEquals(Args[I]))
2547 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002548 }
2549
John McCallc392f372010-06-11 00:33:02 +00002550 QualType Canon;
2551 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2552 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2553 Name, NumArgs,
2554 CanonArgs.data());
2555
2556 // Find the insert position again.
2557 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2558 }
2559
2560 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2561 sizeof(TemplateArgument) * NumArgs),
2562 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002563 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002564 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002565 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002566 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002567 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002568}
2569
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002570QualType ASTContext::getPackExpansionType(QualType Pattern,
2571 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002572 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002573 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002574
2575 assert(Pattern->containsUnexpandedParameterPack() &&
2576 "Pack expansions must expand one or more parameter packs");
2577 void *InsertPos = 0;
2578 PackExpansionType *T
2579 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2580 if (T)
2581 return QualType(T, 0);
2582
2583 QualType Canon;
2584 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002585 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002586
2587 // Find the insert position again.
2588 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2589 }
2590
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002591 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002592 Types.push_back(T);
2593 PackExpansionTypes.InsertNode(T, InsertPos);
2594 return QualType(T, 0);
2595}
2596
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002597/// CmpProtocolNames - Comparison predicate for sorting protocols
2598/// alphabetically.
2599static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2600 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002601 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002602}
2603
John McCall8b07ec22010-05-15 11:32:37 +00002604static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002605 unsigned NumProtocols) {
2606 if (NumProtocols == 0) return true;
2607
2608 for (unsigned i = 1; i != NumProtocols; ++i)
2609 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2610 return false;
2611 return true;
2612}
2613
2614static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002615 unsigned &NumProtocols) {
2616 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002617
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002618 // Sort protocols, keyed by name.
2619 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2620
2621 // Remove duplicates.
2622 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2623 NumProtocols = ProtocolsEnd-Protocols;
2624}
2625
John McCall8b07ec22010-05-15 11:32:37 +00002626QualType ASTContext::getObjCObjectType(QualType BaseType,
2627 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002628 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002629 // If the base type is an interface and there aren't any protocols
2630 // to add, then the interface type will do just fine.
2631 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2632 return BaseType;
2633
2634 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002635 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002636 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002637 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002638 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2639 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002640
John McCall8b07ec22010-05-15 11:32:37 +00002641 // Build the canonical type, which has the canonical base type and
2642 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002643 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002644 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2645 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2646 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002647 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2648 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002649 unsigned UniqueCount = NumProtocols;
2650
John McCallfc93cf92009-10-22 22:37:11 +00002651 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002652 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2653 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002654 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002655 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2656 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002657 }
2658
2659 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002660 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2661 }
2662
2663 unsigned Size = sizeof(ObjCObjectTypeImpl);
2664 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2665 void *Mem = Allocate(Size, TypeAlignment);
2666 ObjCObjectTypeImpl *T =
2667 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2668
2669 Types.push_back(T);
2670 ObjCObjectTypes.InsertNode(T, InsertPos);
2671 return QualType(T, 0);
2672}
2673
2674/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2675/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002676QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002677 llvm::FoldingSetNodeID ID;
2678 ObjCObjectPointerType::Profile(ID, ObjectT);
2679
2680 void *InsertPos = 0;
2681 if (ObjCObjectPointerType *QT =
2682 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2683 return QualType(QT, 0);
2684
2685 // Find the canonical object type.
2686 QualType Canonical;
2687 if (!ObjectT.isCanonical()) {
2688 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2689
2690 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002691 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2692 }
2693
Douglas Gregorf85bee62010-02-08 22:59:26 +00002694 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002695 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2696 ObjCObjectPointerType *QType =
2697 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002698
Steve Narofffb4330f2009-06-17 22:40:22 +00002699 Types.push_back(QType);
2700 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002701 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002702}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002703
Douglas Gregor1c283312010-08-11 12:19:30 +00002704/// getObjCInterfaceType - Return the unique reference to the type for the
2705/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002706QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002707 if (Decl->TypeForDecl)
2708 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002709
Douglas Gregor1c283312010-08-11 12:19:30 +00002710 // FIXME: redeclarations?
2711 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2712 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2713 Decl->TypeForDecl = T;
2714 Types.push_back(T);
2715 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002716}
2717
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002718/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2719/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002720/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002721/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002722/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002723QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002724 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002725 if (tofExpr->isTypeDependent()) {
2726 llvm::FoldingSetNodeID ID;
2727 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002728
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002729 void *InsertPos = 0;
2730 DependentTypeOfExprType *Canon
2731 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2732 if (Canon) {
2733 // We already have a "canonical" version of an identical, dependent
2734 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002735 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002736 QualType((TypeOfExprType*)Canon, 0));
2737 }
2738 else {
2739 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002740 Canon
2741 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002742 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2743 toe = Canon;
2744 }
2745 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002746 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002747 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002748 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002749 Types.push_back(toe);
2750 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002751}
2752
Steve Naroffa773cd52007-08-01 18:02:17 +00002753/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2754/// TypeOfType AST's. The only motivation to unique these nodes would be
2755/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002756/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002757/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002758QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002759 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002760 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002761 Types.push_back(tot);
2762 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002763}
2764
Anders Carlssonad6bd352009-06-24 21:24:56 +00002765/// getDecltypeForExpr - Given an expr, will return the decltype for that
2766/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002767static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002768 if (e->isTypeDependent())
2769 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002770
Anders Carlssonad6bd352009-06-24 21:24:56 +00002771 // If e is an id expression or a class member access, decltype(e) is defined
2772 // as the type of the entity named by e.
2773 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2774 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2775 return VD->getType();
2776 }
2777 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2778 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2779 return FD->getType();
2780 }
2781 // If e is a function call or an invocation of an overloaded operator,
2782 // (parentheses around e are ignored), decltype(e) is defined as the
2783 // return type of that function.
2784 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2785 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002786
Anders Carlssonad6bd352009-06-24 21:24:56 +00002787 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002788
2789 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002790 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002791 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002792 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002793
Anders Carlssonad6bd352009-06-24 21:24:56 +00002794 return T;
2795}
2796
Anders Carlsson81df7b82009-06-24 19:06:50 +00002797/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2798/// DecltypeType AST's. The only motivation to unique these nodes would be
2799/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002800/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002801/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002802QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002803 DecltypeType *dt;
Douglas Gregora21f6c32009-07-30 23:36:40 +00002804 if (e->isTypeDependent()) {
2805 llvm::FoldingSetNodeID ID;
2806 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002807
Douglas Gregora21f6c32009-07-30 23:36:40 +00002808 void *InsertPos = 0;
2809 DependentDecltypeType *Canon
2810 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2811 if (Canon) {
2812 // We already have a "canonical" version of an equivalent, dependent
2813 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002814 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002815 QualType((DecltypeType*)Canon, 0));
2816 }
2817 else {
2818 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002819 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002820 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2821 dt = Canon;
2822 }
2823 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002824 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002825 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002826 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002827 Types.push_back(dt);
2828 return QualType(dt, 0);
2829}
2830
Alexis Hunte852b102011-05-24 22:41:36 +00002831/// getUnaryTransformationType - We don't unique these, since the memory
2832/// savings are minimal and these are rare.
2833QualType ASTContext::getUnaryTransformType(QualType BaseType,
2834 QualType UnderlyingType,
2835 UnaryTransformType::UTTKind Kind)
2836 const {
2837 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002838 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2839 Kind,
2840 UnderlyingType->isDependentType() ?
2841 QualType() : UnderlyingType);
Alexis Hunte852b102011-05-24 22:41:36 +00002842 Types.push_back(Ty);
2843 return QualType(Ty, 0);
2844}
2845
Richard Smithb2bc2e62011-02-21 20:05:19 +00002846/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002847QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002848 void *InsertPos = 0;
2849 if (!DeducedType.isNull()) {
2850 // Look in the folding set for an existing type.
2851 llvm::FoldingSetNodeID ID;
2852 AutoType::Profile(ID, DeducedType);
2853 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2854 return QualType(AT, 0);
2855 }
2856
2857 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2858 Types.push_back(AT);
2859 if (InsertPos)
2860 AutoTypes.InsertNode(AT, InsertPos);
2861 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002862}
2863
Richard Smith02e85f32011-04-14 22:09:26 +00002864/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2865QualType ASTContext::getAutoDeductType() const {
2866 if (AutoDeductTy.isNull())
2867 AutoDeductTy = getAutoType(QualType());
2868 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2869 return AutoDeductTy;
2870}
2871
2872/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2873QualType ASTContext::getAutoRRefDeductType() const {
2874 if (AutoRRefDeductTy.isNull())
2875 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2876 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2877 return AutoRRefDeductTy;
2878}
2879
Chris Lattnerfb072462007-01-23 05:45:31 +00002880/// getTagDeclType - Return the unique reference to the type for the
2881/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002882QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002883 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002884 // FIXME: What is the design on getTagDeclType when it requires casting
2885 // away const? mutable?
2886 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002887}
2888
Mike Stump11289f42009-09-09 15:08:12 +00002889/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2890/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2891/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002892CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002893 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002894}
Chris Lattnerfb072462007-01-23 05:45:31 +00002895
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002896/// getSignedWCharType - Return the type of "signed wchar_t".
2897/// Used when in C++, as a GCC extension.
2898QualType ASTContext::getSignedWCharType() const {
2899 // FIXME: derive from "Target" ?
2900 return WCharTy;
2901}
2902
2903/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2904/// Used when in C++, as a GCC extension.
2905QualType ASTContext::getUnsignedWCharType() const {
2906 // FIXME: derive from "Target" ?
2907 return UnsignedIntTy;
2908}
2909
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002910/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2911/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2912QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002913 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002914}
2915
Chris Lattnera21ad802008-04-02 05:18:44 +00002916//===----------------------------------------------------------------------===//
2917// Type Operators
2918//===----------------------------------------------------------------------===//
2919
Jay Foad39c79802011-01-12 09:06:06 +00002920CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002921 // Push qualifiers into arrays, and then discard any remaining
2922 // qualifiers.
2923 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002924 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002925 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002926 QualType Result;
2927 if (isa<ArrayType>(Ty)) {
2928 Result = getArrayDecayedType(QualType(Ty,0));
2929 } else if (isa<FunctionType>(Ty)) {
2930 Result = getPointerType(QualType(Ty, 0));
2931 } else {
2932 Result = QualType(Ty, 0);
2933 }
2934
2935 return CanQualType::CreateUnsafe(Result);
2936}
2937
John McCall6c9dd522011-01-18 07:41:22 +00002938QualType ASTContext::getUnqualifiedArrayType(QualType type,
2939 Qualifiers &quals) {
2940 SplitQualType splitType = type.getSplitUnqualifiedType();
2941
2942 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2943 // the unqualified desugared type and then drops it on the floor.
2944 // We then have to strip that sugar back off with
2945 // getUnqualifiedDesugaredType(), which is silly.
2946 const ArrayType *AT =
2947 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2948
2949 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002950 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002951 quals = splitType.second;
2952 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002953 }
2954
John McCall6c9dd522011-01-18 07:41:22 +00002955 // Otherwise, recurse on the array's element type.
2956 QualType elementType = AT->getElementType();
2957 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2958
2959 // If that didn't change the element type, AT has no qualifiers, so we
2960 // can just use the results in splitType.
2961 if (elementType == unqualElementType) {
2962 assert(quals.empty()); // from the recursive call
2963 quals = splitType.second;
2964 return QualType(splitType.first, 0);
2965 }
2966
2967 // Otherwise, add in the qualifiers from the outermost type, then
2968 // build the type back up.
2969 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002970
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002971 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002972 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002973 CAT->getSizeModifier(), 0);
2974 }
2975
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002976 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002977 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002978 }
2979
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002980 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002981 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002982 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002983 VAT->getSizeModifier(),
2984 VAT->getIndexTypeCVRQualifiers(),
2985 VAT->getBracketsRange());
2986 }
2987
2988 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00002989 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002990 DSAT->getSizeModifier(), 0,
2991 SourceRange());
2992}
2993
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002994/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2995/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2996/// they point to and return true. If T1 and T2 aren't pointer types
2997/// or pointer-to-member types, or if they are not similar at this
2998/// level, returns false and leaves T1 and T2 unchanged. Top-level
2999/// qualifiers on T1 and T2 are ignored. This function will typically
3000/// be called in a loop that successively "unwraps" pointer and
3001/// pointer-to-member types to compare them at each level.
3002bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3003 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3004 *T2PtrType = T2->getAs<PointerType>();
3005 if (T1PtrType && T2PtrType) {
3006 T1 = T1PtrType->getPointeeType();
3007 T2 = T2PtrType->getPointeeType();
3008 return true;
3009 }
3010
3011 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3012 *T2MPType = T2->getAs<MemberPointerType>();
3013 if (T1MPType && T2MPType &&
3014 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3015 QualType(T2MPType->getClass(), 0))) {
3016 T1 = T1MPType->getPointeeType();
3017 T2 = T2MPType->getPointeeType();
3018 return true;
3019 }
3020
3021 if (getLangOptions().ObjC1) {
3022 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3023 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3024 if (T1OPType && T2OPType) {
3025 T1 = T1OPType->getPointeeType();
3026 T2 = T2OPType->getPointeeType();
3027 return true;
3028 }
3029 }
3030
3031 // FIXME: Block pointers, too?
3032
3033 return false;
3034}
3035
Jay Foad39c79802011-01-12 09:06:06 +00003036DeclarationNameInfo
3037ASTContext::getNameForTemplate(TemplateName Name,
3038 SourceLocation NameLoc) const {
John McCall847e2a12009-11-24 18:42:40 +00003039 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003040 // DNInfo work in progress: CHECKME: what about DNLoc?
3041 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
3042
John McCall847e2a12009-11-24 18:42:40 +00003043 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003044 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003045 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003046 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3047 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003048 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003049 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3050 // DNInfo work in progress: FIXME: source locations?
3051 DeclarationNameLoc DNLoc;
3052 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3053 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3054 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003055 }
3056 }
3057
John McCalld28ae272009-12-02 08:04:21 +00003058 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3059 assert(Storage);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003060 // DNInfo work in progress: CHECKME: what about DNLoc?
3061 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003062}
3063
Jay Foad39c79802011-01-12 09:06:06 +00003064TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003065 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3066 if (TemplateTemplateParmDecl *TTP
3067 = dyn_cast<TemplateTemplateParmDecl>(Template))
3068 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3069
3070 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003071 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003072 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003073
Douglas Gregor5590be02011-01-15 06:45:20 +00003074 if (SubstTemplateTemplateParmPackStorage *SubstPack
3075 = Name.getAsSubstTemplateTemplateParmPack()) {
3076 TemplateTemplateParmDecl *CanonParam
3077 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
3078 TemplateArgument CanonArgPack
3079 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
3080 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
3081 }
3082
John McCalld28ae272009-12-02 08:04:21 +00003083 assert(!Name.getAsOverloadedTemplate());
Mike Stump11289f42009-09-09 15:08:12 +00003084
Douglas Gregor6bc50582009-05-07 06:41:52 +00003085 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3086 assert(DTN && "Non-dependent template names must refer to template decls.");
3087 return DTN->CanonicalTemplateName;
3088}
3089
Douglas Gregoradee3e32009-11-11 23:06:43 +00003090bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3091 X = getCanonicalTemplateName(X);
3092 Y = getCanonicalTemplateName(Y);
3093 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3094}
3095
Mike Stump11289f42009-09-09 15:08:12 +00003096TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003097ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003098 switch (Arg.getKind()) {
3099 case TemplateArgument::Null:
3100 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003101
Douglas Gregora8e02e72009-07-28 23:00:59 +00003102 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003103 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003104
Douglas Gregora8e02e72009-07-28 23:00:59 +00003105 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003106 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003107
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003108 case TemplateArgument::Template:
3109 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003110
3111 case TemplateArgument::TemplateExpansion:
3112 return TemplateArgument(getCanonicalTemplateName(
3113 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003114 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003115
Douglas Gregora8e02e72009-07-28 23:00:59 +00003116 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003117 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003118 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003119
Douglas Gregora8e02e72009-07-28 23:00:59 +00003120 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003121 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003122
Douglas Gregora8e02e72009-07-28 23:00:59 +00003123 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003124 if (Arg.pack_size() == 0)
3125 return Arg;
3126
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003127 TemplateArgument *CanonArgs
3128 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003129 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003130 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003131 AEnd = Arg.pack_end();
3132 A != AEnd; (void)++A, ++Idx)
3133 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003134
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003135 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003136 }
3137 }
3138
3139 // Silence GCC warning
3140 assert(false && "Unhandled template argument kind");
3141 return TemplateArgument();
3142}
3143
Douglas Gregor333489b2009-03-27 23:10:48 +00003144NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003145ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003146 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003147 return 0;
3148
3149 switch (NNS->getKind()) {
3150 case NestedNameSpecifier::Identifier:
3151 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003152 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003153 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3154 NNS->getAsIdentifier());
3155
3156 case NestedNameSpecifier::Namespace:
3157 // A namespace is canonical; build a nested-name-specifier with
3158 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003159 return NestedNameSpecifier::Create(*this, 0,
3160 NNS->getAsNamespace()->getOriginalNamespace());
3161
3162 case NestedNameSpecifier::NamespaceAlias:
3163 // A namespace is canonical; build a nested-name-specifier with
3164 // this namespace and no prefix.
3165 return NestedNameSpecifier::Create(*this, 0,
3166 NNS->getAsNamespaceAlias()->getNamespace()
3167 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003168
3169 case NestedNameSpecifier::TypeSpec:
3170 case NestedNameSpecifier::TypeSpecWithTemplate: {
3171 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003172
3173 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3174 // break it apart into its prefix and identifier, then reconsititute those
3175 // as the canonical nested-name-specifier. This is required to canonicalize
3176 // a dependent nested-name-specifier involving typedefs of dependent-name
3177 // types, e.g.,
3178 // typedef typename T::type T1;
3179 // typedef typename T1::type T2;
3180 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3181 NestedNameSpecifier *Prefix
3182 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3183 return NestedNameSpecifier::Create(*this, Prefix,
3184 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3185 }
3186
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003187 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003188 if (const DependentTemplateSpecializationType *DTST
3189 = T->getAs<DependentTemplateSpecializationType>()) {
3190 NestedNameSpecifier *Prefix
3191 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003192
3193 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3194 Prefix, DTST->getIdentifier(),
3195 DTST->getNumArgs(),
3196 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003197 T = getCanonicalType(T);
3198 }
3199
John McCall33ddac02011-01-19 10:06:00 +00003200 return NestedNameSpecifier::Create(*this, 0, false,
3201 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003202 }
3203
3204 case NestedNameSpecifier::Global:
3205 // The global specifier is canonical and unique.
3206 return NNS;
3207 }
3208
3209 // Required to silence a GCC warning
3210 return 0;
3211}
3212
Chris Lattner7adf0762008-08-04 07:31:14 +00003213
Jay Foad39c79802011-01-12 09:06:06 +00003214const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003215 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003216 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003217 // Handle the common positive case fast.
3218 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3219 return AT;
3220 }
Mike Stump11289f42009-09-09 15:08:12 +00003221
John McCall8ccfcb52009-09-24 19:53:00 +00003222 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003223 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003224 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003225
John McCall8ccfcb52009-09-24 19:53:00 +00003226 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003227 // implements C99 6.7.3p8: "If the specification of an array type includes
3228 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003229
Chris Lattner7adf0762008-08-04 07:31:14 +00003230 // If we get here, we either have type qualifiers on the type, or we have
3231 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003232 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003233
John McCall33ddac02011-01-19 10:06:00 +00003234 SplitQualType split = T.getSplitDesugaredType();
3235 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003236
Chris Lattner7adf0762008-08-04 07:31:14 +00003237 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003238 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3239 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003240 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003241
Chris Lattner7adf0762008-08-04 07:31:14 +00003242 // Otherwise, we have an array and we have qualifiers on it. Push the
3243 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003244 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003245
Chris Lattner7adf0762008-08-04 07:31:14 +00003246 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3247 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3248 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003249 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003250 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3251 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3252 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003253 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003254
Mike Stump11289f42009-09-09 15:08:12 +00003255 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003256 = dyn_cast<DependentSizedArrayType>(ATy))
3257 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003258 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003259 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003260 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003261 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003262 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003263
Chris Lattner7adf0762008-08-04 07:31:14 +00003264 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003265 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003266 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003267 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003268 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003269 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003270}
3271
Chris Lattnera21ad802008-04-02 05:18:44 +00003272/// getArrayDecayedType - Return the properly qualified result of decaying the
3273/// specified array type to a pointer. This operation is non-trivial when
3274/// handling typedefs etc. The canonical type of "T" must be an array type,
3275/// this returns a pointer to a properly qualified element of the array.
3276///
3277/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003278QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003279 // Get the element type with 'getAsArrayType' so that we don't lose any
3280 // typedefs in the element type of the array. This also handles propagation
3281 // of type qualifiers from the array type into the element type if present
3282 // (C99 6.7.3p8).
3283 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3284 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003285
Chris Lattner7adf0762008-08-04 07:31:14 +00003286 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003287
3288 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003289 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003290}
3291
John McCall33ddac02011-01-19 10:06:00 +00003292QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3293 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003294}
3295
John McCall33ddac02011-01-19 10:06:00 +00003296QualType ASTContext::getBaseElementType(QualType type) const {
3297 Qualifiers qs;
3298 while (true) {
3299 SplitQualType split = type.getSplitDesugaredType();
3300 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3301 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003302
John McCall33ddac02011-01-19 10:06:00 +00003303 type = array->getElementType();
3304 qs.addConsistentQualifiers(split.second);
3305 }
Mike Stump11289f42009-09-09 15:08:12 +00003306
John McCall33ddac02011-01-19 10:06:00 +00003307 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003308}
3309
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003310/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003311uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003312ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3313 uint64_t ElementCount = 1;
3314 do {
3315 ElementCount *= CA->getSize().getZExtValue();
3316 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3317 } while (CA);
3318 return ElementCount;
3319}
3320
Steve Naroff0af91202007-04-27 21:51:21 +00003321/// getFloatingRank - Return a relative rank for floating point types.
3322/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003323static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003324 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003325 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003326
John McCall9dd450b2009-09-21 23:43:11 +00003327 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3328 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003329 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003330 case BuiltinType::Float: return FloatRank;
3331 case BuiltinType::Double: return DoubleRank;
3332 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003333 }
3334}
3335
Mike Stump11289f42009-09-09 15:08:12 +00003336/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3337/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003338/// 'typeDomain' is a real floating point or complex type.
3339/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003340QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3341 QualType Domain) const {
3342 FloatingRank EltRank = getFloatingRank(Size);
3343 if (Domain->isComplexType()) {
3344 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003345 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003346 case FloatRank: return FloatComplexTy;
3347 case DoubleRank: return DoubleComplexTy;
3348 case LongDoubleRank: return LongDoubleComplexTy;
3349 }
Steve Naroff0af91202007-04-27 21:51:21 +00003350 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003351
3352 assert(Domain->isRealFloatingType() && "Unknown domain!");
3353 switch (EltRank) {
3354 default: assert(0 && "getFloatingRank(): illegal value for rank");
3355 case FloatRank: return FloatTy;
3356 case DoubleRank: return DoubleTy;
3357 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003358 }
Steve Naroffe4718892007-04-27 18:30:00 +00003359}
3360
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003361/// getFloatingTypeOrder - Compare the rank of the two specified floating
3362/// point types, ignoring the domain of the type (i.e. 'double' ==
3363/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003364/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003365int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003366 FloatingRank LHSR = getFloatingRank(LHS);
3367 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003368
Chris Lattnerb90739d2008-04-06 23:38:49 +00003369 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003370 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003371 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003372 return 1;
3373 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003374}
3375
Chris Lattner76a00cf2008-04-06 22:59:24 +00003376/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3377/// routine will assert if passed a built-in type that isn't an integer or enum,
3378/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003379unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003380 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003381 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003382 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003383
Chris Lattnerad3467e2010-12-25 23:25:43 +00003384 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3385 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003386 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3387
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003388 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3389 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3390
3391 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3392 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3393
Chris Lattner76a00cf2008-04-06 22:59:24 +00003394 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003395 default: assert(0 && "getIntegerRank(): not a built-in integer");
3396 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003397 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003398 case BuiltinType::Char_S:
3399 case BuiltinType::Char_U:
3400 case BuiltinType::SChar:
3401 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003402 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003403 case BuiltinType::Short:
3404 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003405 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003406 case BuiltinType::Int:
3407 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003408 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003409 case BuiltinType::Long:
3410 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003411 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003412 case BuiltinType::LongLong:
3413 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003414 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003415 case BuiltinType::Int128:
3416 case BuiltinType::UInt128:
3417 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003418 }
3419}
3420
Eli Friedman629ffb92009-08-20 04:21:42 +00003421/// \brief Whether this is a promotable bitfield reference according
3422/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3423///
3424/// \returns the type this bit-field will promote to, or NULL if no
3425/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003426QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003427 if (E->isTypeDependent() || E->isValueDependent())
3428 return QualType();
3429
Eli Friedman629ffb92009-08-20 04:21:42 +00003430 FieldDecl *Field = E->getBitField();
3431 if (!Field)
3432 return QualType();
3433
3434 QualType FT = Field->getType();
3435
3436 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3437 uint64_t BitWidth = BitWidthAP.getZExtValue();
3438 uint64_t IntSize = getTypeSize(IntTy);
3439 // GCC extension compatibility: if the bit-field size is less than or equal
3440 // to the size of int, it gets promoted no matter what its type is.
3441 // For instance, unsigned long bf : 4 gets promoted to signed int.
3442 if (BitWidth < IntSize)
3443 return IntTy;
3444
3445 if (BitWidth == IntSize)
3446 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3447
3448 // Types bigger than int are not subject to promotions, and therefore act
3449 // like the base type.
3450 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3451 // is ridiculous.
3452 return QualType();
3453}
3454
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003455/// getPromotedIntegerType - Returns the type that Promotable will
3456/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3457/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003458QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003459 assert(!Promotable.isNull());
3460 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003461 if (const EnumType *ET = Promotable->getAs<EnumType>())
3462 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003463 if (Promotable->isSignedIntegerType())
3464 return IntTy;
3465 uint64_t PromotableSize = getTypeSize(Promotable);
3466 uint64_t IntSize = getTypeSize(IntTy);
3467 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3468 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3469}
3470
Mike Stump11289f42009-09-09 15:08:12 +00003471/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003472/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003473/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003474int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003475 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3476 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003477 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003478
Chris Lattner76a00cf2008-04-06 22:59:24 +00003479 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3480 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003481
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003482 unsigned LHSRank = getIntegerRank(LHSC);
3483 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003484
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003485 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3486 if (LHSRank == RHSRank) return 0;
3487 return LHSRank > RHSRank ? 1 : -1;
3488 }
Mike Stump11289f42009-09-09 15:08:12 +00003489
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003490 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3491 if (LHSUnsigned) {
3492 // If the unsigned [LHS] type is larger, return it.
3493 if (LHSRank >= RHSRank)
3494 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003495
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003496 // If the signed type can represent all values of the unsigned type, it
3497 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003498 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003499 return -1;
3500 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003501
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003502 // If the unsigned [RHS] type is larger, return it.
3503 if (RHSRank >= LHSRank)
3504 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003505
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003506 // If the signed type can represent all values of the unsigned type, it
3507 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003508 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003509 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003510}
Anders Carlsson98f07902007-08-17 05:31:46 +00003511
Anders Carlsson6d417272009-11-14 21:45:58 +00003512static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003513CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3514 DeclContext *DC, IdentifierInfo *Id) {
3515 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003516 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003517 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003518 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003519 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003520}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003521
Mike Stump11289f42009-09-09 15:08:12 +00003522// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003523QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003524 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003525 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003526 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003527 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003528 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003529
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003530 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003531
Anders Carlsson98f07902007-08-17 05:31:46 +00003532 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003533 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003534 // int flags;
3535 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003536 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003537 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003538 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003539 FieldTypes[3] = LongTy;
3540
Anders Carlsson98f07902007-08-17 05:31:46 +00003541 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003542 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003543 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003544 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003545 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003546 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003547 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003548 /*Mutable=*/false,
3549 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003550 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003551 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003552 }
3553
Douglas Gregord5058122010-02-11 01:19:42 +00003554 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003555 }
Mike Stump11289f42009-09-09 15:08:12 +00003556
Anders Carlsson98f07902007-08-17 05:31:46 +00003557 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003558}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003559
Douglas Gregor512b0772009-04-23 22:29:11 +00003560void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003561 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003562 assert(Rec && "Invalid CFConstantStringType");
3563 CFConstantStringTypeDecl = Rec->getDecl();
3564}
3565
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003566// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003567QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003568 if (!NSConstantStringTypeDecl) {
3569 NSConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003570 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003571 &Idents.get("__builtin_NSString"));
3572 NSConstantStringTypeDecl->startDefinition();
3573
3574 QualType FieldTypes[3];
3575
3576 // const int *isa;
3577 FieldTypes[0] = getPointerType(IntTy.withConst());
3578 // const char *str;
3579 FieldTypes[1] = getPointerType(CharTy.withConst());
3580 // unsigned int length;
3581 FieldTypes[2] = UnsignedIntTy;
3582
3583 // Create fields
3584 for (unsigned i = 0; i < 3; ++i) {
3585 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003586 SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003587 SourceLocation(), 0,
3588 FieldTypes[i], /*TInfo=*/0,
3589 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003590 /*Mutable=*/false,
3591 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003592 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003593 NSConstantStringTypeDecl->addDecl(Field);
3594 }
3595
3596 NSConstantStringTypeDecl->completeDefinition();
3597 }
3598
3599 return getTagDeclType(NSConstantStringTypeDecl);
3600}
3601
3602void ASTContext::setNSConstantStringType(QualType T) {
3603 const RecordType *Rec = T->getAs<RecordType>();
3604 assert(Rec && "Invalid NSConstantStringType");
3605 NSConstantStringTypeDecl = Rec->getDecl();
3606}
3607
Jay Foad39c79802011-01-12 09:06:06 +00003608QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003609 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003610 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003611 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003612 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003613 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003614
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003615 QualType FieldTypes[] = {
3616 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003617 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003618 getPointerType(UnsignedLongTy),
3619 getConstantArrayType(UnsignedLongTy,
3620 llvm::APInt(32, 5), ArrayType::Normal, 0)
3621 };
Mike Stump11289f42009-09-09 15:08:12 +00003622
Douglas Gregor91f84212008-12-11 16:49:14 +00003623 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003624 FieldDecl *Field = FieldDecl::Create(*this,
3625 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003626 SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003627 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003628 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003629 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003630 /*Mutable=*/false,
3631 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003632 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003633 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003634 }
Mike Stump11289f42009-09-09 15:08:12 +00003635
Douglas Gregord5058122010-02-11 01:19:42 +00003636 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003637 }
Mike Stump11289f42009-09-09 15:08:12 +00003638
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003639 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3640}
3641
Jay Foad39c79802011-01-12 09:06:06 +00003642QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003643 if (BlockDescriptorType)
3644 return getTagDeclType(BlockDescriptorType);
3645
3646 RecordDecl *T;
3647 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003648 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003649 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003650 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003651
3652 QualType FieldTypes[] = {
3653 UnsignedLongTy,
3654 UnsignedLongTy,
3655 };
3656
3657 const char *FieldNames[] = {
3658 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003659 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003660 };
3661
3662 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003663 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003664 SourceLocation(),
3665 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003666 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003667 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003668 /*Mutable=*/false,
3669 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003670 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003671 T->addDecl(Field);
3672 }
3673
Douglas Gregord5058122010-02-11 01:19:42 +00003674 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003675
3676 BlockDescriptorType = T;
3677
3678 return getTagDeclType(BlockDescriptorType);
3679}
3680
3681void ASTContext::setBlockDescriptorType(QualType T) {
3682 const RecordType *Rec = T->getAs<RecordType>();
3683 assert(Rec && "Invalid BlockDescriptorType");
3684 BlockDescriptorType = Rec->getDecl();
3685}
3686
Jay Foad39c79802011-01-12 09:06:06 +00003687QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003688 if (BlockDescriptorExtendedType)
3689 return getTagDeclType(BlockDescriptorExtendedType);
3690
3691 RecordDecl *T;
3692 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003693 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003694 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003695 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003696
3697 QualType FieldTypes[] = {
3698 UnsignedLongTy,
3699 UnsignedLongTy,
3700 getPointerType(VoidPtrTy),
3701 getPointerType(VoidPtrTy)
3702 };
3703
3704 const char *FieldNames[] = {
3705 "reserved",
3706 "Size",
3707 "CopyFuncPtr",
3708 "DestroyFuncPtr"
3709 };
3710
3711 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003712 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003713 SourceLocation(),
3714 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003715 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003716 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003717 /*Mutable=*/false,
3718 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003719 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003720 T->addDecl(Field);
3721 }
3722
Douglas Gregord5058122010-02-11 01:19:42 +00003723 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003724
3725 BlockDescriptorExtendedType = T;
3726
3727 return getTagDeclType(BlockDescriptorExtendedType);
3728}
3729
3730void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3731 const RecordType *Rec = T->getAs<RecordType>();
3732 assert(Rec && "Invalid BlockDescriptorType");
3733 BlockDescriptorExtendedType = Rec->getDecl();
3734}
3735
Jay Foad39c79802011-01-12 09:06:06 +00003736bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003737 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003738 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003739 if (getLangOptions().CPlusPlus) {
3740 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3741 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003742 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003743
3744 }
3745 }
Mike Stump94967902009-10-21 18:16:27 +00003746 return false;
3747}
3748
Jay Foad39c79802011-01-12 09:06:06 +00003749QualType
3750ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003751 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003752 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003753 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003754 // unsigned int __flags;
3755 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003756 // void *__copy_helper; // as needed
3757 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003758 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003759 // } *
3760
Mike Stump94967902009-10-21 18:16:27 +00003761 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3762
3763 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003764 llvm::SmallString<36> Name;
3765 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3766 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003767 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003768 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003769 T->startDefinition();
3770 QualType Int32Ty = IntTy;
3771 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3772 QualType FieldTypes[] = {
3773 getPointerType(VoidPtrTy),
3774 getPointerType(getTagDeclType(T)),
3775 Int32Ty,
3776 Int32Ty,
3777 getPointerType(VoidPtrTy),
3778 getPointerType(VoidPtrTy),
3779 Ty
3780 };
3781
Daniel Dunbar56df9772010-08-17 22:39:59 +00003782 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003783 "__isa",
3784 "__forwarding",
3785 "__flags",
3786 "__size",
3787 "__copy_helper",
3788 "__destroy_helper",
3789 DeclName,
3790 };
3791
3792 for (size_t i = 0; i < 7; ++i) {
3793 if (!HasCopyAndDispose && i >=4 && i <= 5)
3794 continue;
3795 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003796 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003797 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003798 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003799 /*BitWidth=*/0, /*Mutable=*/false,
3800 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003801 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003802 T->addDecl(Field);
3803 }
3804
Douglas Gregord5058122010-02-11 01:19:42 +00003805 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003806
3807 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003808}
3809
Douglas Gregor512b0772009-04-23 22:29:11 +00003810void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003811 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003812 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3813 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3814}
3815
Anders Carlsson18acd442007-10-29 06:33:42 +00003816// This returns true if a type has been typedefed to BOOL:
3817// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003818static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003819 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003820 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3821 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003822
Anders Carlssond8499822007-10-29 05:01:08 +00003823 return false;
3824}
3825
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003826/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003827/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003828CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00003829 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3830 return CharUnits::Zero();
3831
Ken Dyck40775002010-01-11 17:06:35 +00003832 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003833
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003834 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003835 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003836 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003837 // Treat arrays as pointers, since that's how they're passed in.
3838 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003839 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003840 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003841}
3842
3843static inline
3844std::string charUnitsToString(const CharUnits &CU) {
3845 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003846}
3847
John McCall351762c2011-02-07 10:33:21 +00003848/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003849/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003850std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3851 std::string S;
3852
David Chisnall950a9512009-11-17 19:33:30 +00003853 const BlockDecl *Decl = Expr->getBlockDecl();
3854 QualType BlockTy =
3855 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3856 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003857 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003858 // Compute size of all parameters.
3859 // Start with computing size of a pointer in number of bytes.
3860 // FIXME: There might(should) be a better way of doing this computation!
3861 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003862 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3863 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003864 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003865 E = Decl->param_end(); PI != E; ++PI) {
3866 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003867 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003868 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003869 ParmOffset += sz;
3870 }
3871 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003872 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003873 // Block pointer and offset.
3874 S += "@?0";
3875 ParmOffset = PtrSize;
3876
3877 // Argument types.
3878 ParmOffset = PtrSize;
3879 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3880 Decl->param_end(); PI != E; ++PI) {
3881 ParmVarDecl *PVDecl = *PI;
3882 QualType PType = PVDecl->getOriginalType();
3883 if (const ArrayType *AT =
3884 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3885 // Use array's original type only if it has known number of
3886 // elements.
3887 if (!isa<ConstantArrayType>(AT))
3888 PType = PVDecl->getType();
3889 } else if (PType->isFunctionType())
3890 PType = PVDecl->getType();
3891 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003892 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003893 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003894 }
John McCall351762c2011-02-07 10:33:21 +00003895
3896 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003897}
3898
Douglas Gregora9d84932011-05-27 01:19:52 +00003899bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00003900 std::string& S) {
3901 // Encode result type.
3902 getObjCEncodingForType(Decl->getResultType(), S);
3903 CharUnits ParmOffset;
3904 // Compute size of all parameters.
3905 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3906 E = Decl->param_end(); PI != E; ++PI) {
3907 QualType PType = (*PI)->getType();
3908 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00003909 if (sz.isZero())
3910 return true;
3911
David Chisnall50e4eba2010-12-30 14:05:53 +00003912 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00003913 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00003914 ParmOffset += sz;
3915 }
3916 S += charUnitsToString(ParmOffset);
3917 ParmOffset = CharUnits::Zero();
3918
3919 // Argument types.
3920 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3921 E = Decl->param_end(); PI != E; ++PI) {
3922 ParmVarDecl *PVDecl = *PI;
3923 QualType PType = PVDecl->getOriginalType();
3924 if (const ArrayType *AT =
3925 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3926 // Use array's original type only if it has known number of
3927 // elements.
3928 if (!isa<ConstantArrayType>(AT))
3929 PType = PVDecl->getType();
3930 } else if (PType->isFunctionType())
3931 PType = PVDecl->getType();
3932 getObjCEncodingForType(PType, S);
3933 S += charUnitsToString(ParmOffset);
3934 ParmOffset += getObjCEncodingTypeSize(PType);
3935 }
Douglas Gregora9d84932011-05-27 01:19:52 +00003936
3937 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00003938}
3939
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003940/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003941/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00003942bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003943 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00003944 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003945 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003946 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003947 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003948 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003949 // Compute size of all parameters.
3950 // Start with computing size of a pointer in number of bytes.
3951 // FIXME: There might(should) be a better way of doing this computation!
3952 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003953 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003954 // The first two arguments (self and _cmd) are pointers; account for
3955 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00003956 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003957 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003958 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003959 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003960 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00003961 if (sz.isZero())
3962 return true;
3963
Ken Dyck40775002010-01-11 17:06:35 +00003964 assert (sz.isPositive() &&
3965 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003966 ParmOffset += sz;
3967 }
Ken Dyck40775002010-01-11 17:06:35 +00003968 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003969 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00003970 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00003971
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003972 // Argument types.
3973 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00003974 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00003975 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00003976 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00003977 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003978 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00003979 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3980 // Use array's original type only if it has known number of
3981 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00003982 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00003983 PType = PVDecl->getType();
3984 } else if (PType->isFunctionType())
3985 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00003986 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003987 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00003988 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00003989 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003990 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003991 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003992 }
Douglas Gregora9d84932011-05-27 01:19:52 +00003993
3994 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003995}
3996
Daniel Dunbar4932b362008-08-28 04:38:10 +00003997/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00003998/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00003999/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4000/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004001/// Property attributes are stored as a comma-delimited C string. The simple
4002/// attributes readonly and bycopy are encoded as single characters. The
4003/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4004/// encoded as single characters, followed by an identifier. Property types
4005/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004006/// these attributes are defined by the following enumeration:
4007/// @code
4008/// enum PropertyAttributes {
4009/// kPropertyReadOnly = 'R', // property is read-only.
4010/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4011/// kPropertyByref = '&', // property is a reference to the value last assigned
4012/// kPropertyDynamic = 'D', // property is dynamic
4013/// kPropertyGetter = 'G', // followed by getter selector name
4014/// kPropertySetter = 'S', // followed by setter selector name
4015/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4016/// kPropertyType = 't' // followed by old-style type encoding.
4017/// kPropertyWeak = 'W' // 'weak' property
4018/// kPropertyStrong = 'P' // property GC'able
4019/// kPropertyNonAtomic = 'N' // property non-atomic
4020/// };
4021/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004022void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004023 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004024 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004025 // Collect information from the property implementation decl(s).
4026 bool Dynamic = false;
4027 ObjCPropertyImplDecl *SynthesizePID = 0;
4028
4029 // FIXME: Duplicated code due to poor abstraction.
4030 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004031 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004032 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4033 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004034 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004035 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004036 ObjCPropertyImplDecl *PID = *i;
4037 if (PID->getPropertyDecl() == PD) {
4038 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4039 Dynamic = true;
4040 } else {
4041 SynthesizePID = PID;
4042 }
4043 }
4044 }
4045 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004046 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004047 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004048 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004049 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004050 ObjCPropertyImplDecl *PID = *i;
4051 if (PID->getPropertyDecl() == PD) {
4052 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4053 Dynamic = true;
4054 } else {
4055 SynthesizePID = PID;
4056 }
4057 }
Mike Stump11289f42009-09-09 15:08:12 +00004058 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004059 }
4060 }
4061
4062 // FIXME: This is not very efficient.
4063 S = "T";
4064
4065 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004066 // GCC has some special rules regarding encoding of properties which
4067 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004068 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004069 true /* outermost type */,
4070 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004071
4072 if (PD->isReadOnly()) {
4073 S += ",R";
4074 } else {
4075 switch (PD->getSetterKind()) {
4076 case ObjCPropertyDecl::Assign: break;
4077 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004078 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004079 }
4080 }
4081
4082 // It really isn't clear at all what this means, since properties
4083 // are "dynamic by default".
4084 if (Dynamic)
4085 S += ",D";
4086
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004087 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4088 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004089
Daniel Dunbar4932b362008-08-28 04:38:10 +00004090 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4091 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004092 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004093 }
4094
4095 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4096 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004097 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004098 }
4099
4100 if (SynthesizePID) {
4101 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4102 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004103 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004104 }
4105
4106 // FIXME: OBJCGC: weak & strong
4107}
4108
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004109/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004110/// Another legacy compatibility encoding: 32-bit longs are encoded as
4111/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004112/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4113///
4114void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004115 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004116 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004117 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004118 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004119 else
Jay Foad39c79802011-01-12 09:06:06 +00004120 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004121 PointeeTy = IntTy;
4122 }
4123 }
4124}
4125
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004126void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004127 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004128 // We follow the behavior of gcc, expanding structures which are
4129 // directly pointed to, and expanding embedded structures. Note that
4130 // these rules are sufficient to prevent recursive encoding of the
4131 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004132 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004133 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004134}
4135
David Chisnallb190a2c2010-06-04 01:10:52 +00004136static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4137 switch (T->getAs<BuiltinType>()->getKind()) {
4138 default: assert(0 && "Unhandled builtin type kind");
4139 case BuiltinType::Void: return 'v';
4140 case BuiltinType::Bool: return 'B';
4141 case BuiltinType::Char_U:
4142 case BuiltinType::UChar: return 'C';
4143 case BuiltinType::UShort: return 'S';
4144 case BuiltinType::UInt: return 'I';
4145 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004146 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004147 case BuiltinType::UInt128: return 'T';
4148 case BuiltinType::ULongLong: return 'Q';
4149 case BuiltinType::Char_S:
4150 case BuiltinType::SChar: return 'c';
4151 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004152 case BuiltinType::WChar_S:
4153 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004154 case BuiltinType::Int: return 'i';
4155 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004156 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004157 case BuiltinType::LongLong: return 'q';
4158 case BuiltinType::Int128: return 't';
4159 case BuiltinType::Float: return 'f';
4160 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004161 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004162 }
4163}
4164
Jay Foad39c79802011-01-12 09:06:06 +00004165static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004166 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004167 const Expr *E = FD->getBitWidth();
4168 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004169 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004170 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4171 // The GNU runtime requires more information; bitfields are encoded as b,
4172 // then the offset (in bits) of the first element, then the type of the
4173 // bitfield, then the size in bits. For example, in this structure:
4174 //
4175 // struct
4176 // {
4177 // int integer;
4178 // int flags:2;
4179 // };
4180 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4181 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4182 // information is not especially sensible, but we're stuck with it for
4183 // compatibility with GCC, although providing it breaks anything that
4184 // actually uses runtime introspection and wants to work on both runtimes...
4185 if (!Ctx->getLangOptions().NeXTRuntime) {
4186 const RecordDecl *RD = FD->getParent();
4187 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4188 // FIXME: This same linear search is also used in ExprConstant - it might
4189 // be better if the FieldDecl stored its offset. We'd be increasing the
4190 // size of the object slightly, but saving some time every time it is used.
4191 unsigned i = 0;
4192 for (RecordDecl::field_iterator Field = RD->field_begin(),
4193 FieldEnd = RD->field_end();
4194 Field != FieldEnd; (void)++Field, ++i) {
4195 if (*Field == FD)
4196 break;
4197 }
4198 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004199 if (T->isEnumeralType())
4200 S += 'i';
4201 else
Jay Foad39c79802011-01-12 09:06:06 +00004202 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004203 }
4204 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004205 S += llvm::utostr(N);
4206}
4207
Daniel Dunbar07d07852009-10-18 21:17:35 +00004208// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004209void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4210 bool ExpandPointedToStructures,
4211 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004212 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004213 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004214 bool EncodingProperty,
4215 bool StructField) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004216 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004217 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004218 return EncodeBitField(this, S, T, FD);
4219 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004220 return;
4221 }
Mike Stump11289f42009-09-09 15:08:12 +00004222
John McCall9dd450b2009-09-21 23:43:11 +00004223 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004224 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004225 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004226 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004227 return;
4228 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004229
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004230 // encoding for pointer or r3eference types.
4231 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004232 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004233 if (PT->isObjCSelType()) {
4234 S += ':';
4235 return;
4236 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004237 PointeeTy = PT->getPointeeType();
4238 }
4239 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4240 PointeeTy = RT->getPointeeType();
4241 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004242 bool isReadOnly = false;
4243 // For historical/compatibility reasons, the read-only qualifier of the
4244 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4245 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004246 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004247 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004248 if (OutermostType && T.isConstQualified()) {
4249 isReadOnly = true;
4250 S += 'r';
4251 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004252 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004253 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004254 while (P->getAs<PointerType>())
4255 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004256 if (P.isConstQualified()) {
4257 isReadOnly = true;
4258 S += 'r';
4259 }
4260 }
4261 if (isReadOnly) {
4262 // Another legacy compatibility encoding. Some ObjC qualifier and type
4263 // combinations need to be rearranged.
4264 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004265 if (llvm::StringRef(S).endswith("nr"))
4266 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004267 }
Mike Stump11289f42009-09-09 15:08:12 +00004268
Anders Carlssond8499822007-10-29 05:01:08 +00004269 if (PointeeTy->isCharType()) {
4270 // char pointer types should be encoded as '*' unless it is a
4271 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004272 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004273 S += '*';
4274 return;
4275 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004276 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004277 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4278 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4279 S += '#';
4280 return;
4281 }
4282 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4283 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4284 S += '@';
4285 return;
4286 }
4287 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004288 }
Anders Carlssond8499822007-10-29 05:01:08 +00004289 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004290 getLegacyIntegralTypeEncoding(PointeeTy);
4291
Mike Stump11289f42009-09-09 15:08:12 +00004292 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004293 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004294 return;
4295 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004296
Chris Lattnere7cabb92009-07-13 00:10:46 +00004297 if (const ArrayType *AT =
4298 // Ignore type qualifiers etc.
4299 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004300 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004301 // Incomplete arrays are encoded as a pointer to the array element.
4302 S += '^';
4303
Mike Stump11289f42009-09-09 15:08:12 +00004304 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004305 false, ExpandStructures, FD);
4306 } else {
4307 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004308
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004309 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4310 if (getTypeSize(CAT->getElementType()) == 0)
4311 S += '0';
4312 else
4313 S += llvm::utostr(CAT->getSize().getZExtValue());
4314 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004315 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004316 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4317 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004318 S += '0';
4319 }
Mike Stump11289f42009-09-09 15:08:12 +00004320
4321 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004322 false, ExpandStructures, FD);
4323 S += ']';
4324 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004325 return;
4326 }
Mike Stump11289f42009-09-09 15:08:12 +00004327
John McCall9dd450b2009-09-21 23:43:11 +00004328 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004329 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004330 return;
4331 }
Mike Stump11289f42009-09-09 15:08:12 +00004332
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004333 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004334 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004335 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004336 // Anonymous structures print as '?'
4337 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4338 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004339 if (ClassTemplateSpecializationDecl *Spec
4340 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4341 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4342 std::string TemplateArgsStr
4343 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004344 TemplateArgs.data(),
4345 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004346 (*this).PrintingPolicy);
4347
4348 S += TemplateArgsStr;
4349 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004350 } else {
4351 S += '?';
4352 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004353 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004354 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004355 if (!RDecl->isUnion()) {
4356 getObjCEncodingForStructureImpl(RDecl, S, FD);
4357 } else {
4358 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4359 FieldEnd = RDecl->field_end();
4360 Field != FieldEnd; ++Field) {
4361 if (FD) {
4362 S += '"';
4363 S += Field->getNameAsString();
4364 S += '"';
4365 }
Mike Stump11289f42009-09-09 15:08:12 +00004366
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004367 // Special case bit-fields.
4368 if (Field->isBitField()) {
4369 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4370 (*Field));
4371 } else {
4372 QualType qt = Field->getType();
4373 getLegacyIntegralTypeEncoding(qt);
4374 getObjCEncodingForTypeImpl(qt, S, false, true,
4375 FD, /*OutermostType*/false,
4376 /*EncodingProperty*/false,
4377 /*StructField*/true);
4378 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004379 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004380 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004381 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004382 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004383 return;
4384 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004385
Chris Lattnere7cabb92009-07-13 00:10:46 +00004386 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004387 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004388 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004389 else
4390 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004391 return;
4392 }
Mike Stump11289f42009-09-09 15:08:12 +00004393
Chris Lattnere7cabb92009-07-13 00:10:46 +00004394 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004395 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004396 return;
4397 }
Mike Stump11289f42009-09-09 15:08:12 +00004398
John McCall8b07ec22010-05-15 11:32:37 +00004399 // Ignore protocol qualifiers when mangling at this level.
4400 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4401 T = OT->getBaseType();
4402
John McCall8ccfcb52009-09-24 19:53:00 +00004403 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004404 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004405 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004406 S += '{';
4407 const IdentifierInfo *II = OI->getIdentifier();
4408 S += II->getName();
4409 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004410 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4411 DeepCollectObjCIvars(OI, true, Ivars);
4412 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4413 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4414 if (Field->isBitField())
4415 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004416 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004417 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004418 }
4419 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004420 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004421 }
Mike Stump11289f42009-09-09 15:08:12 +00004422
John McCall9dd450b2009-09-21 23:43:11 +00004423 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004424 if (OPT->isObjCIdType()) {
4425 S += '@';
4426 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004427 }
Mike Stump11289f42009-09-09 15:08:12 +00004428
Steve Narofff0c86112009-10-28 22:03:49 +00004429 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4430 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4431 // Since this is a binary compatibility issue, need to consult with runtime
4432 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004433 S += '#';
4434 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004435 }
Mike Stump11289f42009-09-09 15:08:12 +00004436
Chris Lattnere7cabb92009-07-13 00:10:46 +00004437 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004438 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004439 ExpandPointedToStructures,
4440 ExpandStructures, FD);
4441 if (FD || EncodingProperty) {
4442 // Note that we do extended encoding of protocol qualifer list
4443 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004444 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004445 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4446 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004447 S += '<';
4448 S += (*I)->getNameAsString();
4449 S += '>';
4450 }
4451 S += '"';
4452 }
4453 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004454 }
Mike Stump11289f42009-09-09 15:08:12 +00004455
Chris Lattnere7cabb92009-07-13 00:10:46 +00004456 QualType PointeeTy = OPT->getPointeeType();
4457 if (!EncodingProperty &&
4458 isa<TypedefType>(PointeeTy.getTypePtr())) {
4459 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004460 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004461 // {...};
4462 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004463 getObjCEncodingForTypeImpl(PointeeTy, S,
4464 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004465 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004466 return;
4467 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004468
4469 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004470 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004471 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004472 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004473 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4474 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004475 S += '<';
4476 S += (*I)->getNameAsString();
4477 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004478 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004479 S += '"';
4480 }
4481 return;
4482 }
Mike Stump11289f42009-09-09 15:08:12 +00004483
John McCalla9e6e8d2010-05-17 23:56:34 +00004484 // gcc just blithely ignores member pointers.
4485 // TODO: maybe there should be a mangling for these
4486 if (T->getAs<MemberPointerType>())
4487 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004488
4489 if (T->isVectorType()) {
4490 // This matches gcc's encoding, even though technically it is
4491 // insufficient.
4492 // FIXME. We should do a better job than gcc.
4493 return;
4494 }
4495
Chris Lattnere7cabb92009-07-13 00:10:46 +00004496 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004497}
4498
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004499void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4500 std::string &S,
4501 const FieldDecl *FD,
4502 bool includeVBases) const {
4503 assert(RDecl && "Expected non-null RecordDecl");
4504 assert(!RDecl->isUnion() && "Should not be called for unions");
4505 if (!RDecl->getDefinition())
4506 return;
4507
4508 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4509 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4510 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4511
4512 if (CXXRec) {
4513 for (CXXRecordDecl::base_class_iterator
4514 BI = CXXRec->bases_begin(),
4515 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4516 if (!BI->isVirtual()) {
4517 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004518 if (base->isEmpty())
4519 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004520 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4521 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4522 std::make_pair(offs, base));
4523 }
4524 }
4525 }
4526
4527 unsigned i = 0;
4528 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4529 FieldEnd = RDecl->field_end();
4530 Field != FieldEnd; ++Field, ++i) {
4531 uint64_t offs = layout.getFieldOffset(i);
4532 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4533 std::make_pair(offs, *Field));
4534 }
4535
4536 if (CXXRec && includeVBases) {
4537 for (CXXRecordDecl::base_class_iterator
4538 BI = CXXRec->vbases_begin(),
4539 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4540 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004541 if (base->isEmpty())
4542 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004543 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4544 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4545 std::make_pair(offs, base));
4546 }
4547 }
4548
4549 CharUnits size;
4550 if (CXXRec) {
4551 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4552 } else {
4553 size = layout.getSize();
4554 }
4555
4556 uint64_t CurOffs = 0;
4557 std::multimap<uint64_t, NamedDecl *>::iterator
4558 CurLayObj = FieldOrBaseOffsets.begin();
4559
4560 if (CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) {
4561 assert(CXXRec && CXXRec->isDynamicClass() &&
4562 "Offset 0 was empty but no VTable ?");
4563 if (FD) {
4564 S += "\"_vptr$";
4565 std::string recname = CXXRec->getNameAsString();
4566 if (recname.empty()) recname = "?";
4567 S += recname;
4568 S += '"';
4569 }
4570 S += "^^?";
4571 CurOffs += getTypeSize(VoidPtrTy);
4572 }
4573
4574 if (!RDecl->hasFlexibleArrayMember()) {
4575 // Mark the end of the structure.
4576 uint64_t offs = toBits(size);
4577 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4578 std::make_pair(offs, (NamedDecl*)0));
4579 }
4580
4581 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4582 assert(CurOffs <= CurLayObj->first);
4583
4584 if (CurOffs < CurLayObj->first) {
4585 uint64_t padding = CurLayObj->first - CurOffs;
4586 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4587 // packing/alignment of members is different that normal, in which case
4588 // the encoding will be out-of-sync with the real layout.
4589 // If the runtime switches to just consider the size of types without
4590 // taking into account alignment, we could make padding explicit in the
4591 // encoding (e.g. using arrays of chars). The encoding strings would be
4592 // longer then though.
4593 CurOffs += padding;
4594 }
4595
4596 NamedDecl *dcl = CurLayObj->second;
4597 if (dcl == 0)
4598 break; // reached end of structure.
4599
4600 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4601 // We expand the bases without their virtual bases since those are going
4602 // in the initial structure. Note that this differs from gcc which
4603 // expands virtual bases each time one is encountered in the hierarchy,
4604 // making the encoding type bigger than it really is.
4605 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004606 assert(!base->isEmpty());
4607 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004608 } else {
4609 FieldDecl *field = cast<FieldDecl>(dcl);
4610 if (FD) {
4611 S += '"';
4612 S += field->getNameAsString();
4613 S += '"';
4614 }
4615
4616 if (field->isBitField()) {
4617 EncodeBitField(this, S, field->getType(), field);
4618 CurOffs += field->getBitWidth()->EvaluateAsInt(*this).getZExtValue();
4619 } else {
4620 QualType qt = field->getType();
4621 getLegacyIntegralTypeEncoding(qt);
4622 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4623 /*OutermostType*/false,
4624 /*EncodingProperty*/false,
4625 /*StructField*/true);
4626 CurOffs += getTypeSize(field->getType());
4627 }
4628 }
4629 }
4630}
4631
Mike Stump11289f42009-09-09 15:08:12 +00004632void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004633 std::string& S) const {
4634 if (QT & Decl::OBJC_TQ_In)
4635 S += 'n';
4636 if (QT & Decl::OBJC_TQ_Inout)
4637 S += 'N';
4638 if (QT & Decl::OBJC_TQ_Out)
4639 S += 'o';
4640 if (QT & Decl::OBJC_TQ_Bycopy)
4641 S += 'O';
4642 if (QT & Decl::OBJC_TQ_Byref)
4643 S += 'R';
4644 if (QT & Decl::OBJC_TQ_Oneway)
4645 S += 'V';
4646}
4647
Chris Lattnere7cabb92009-07-13 00:10:46 +00004648void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004649 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004650
Anders Carlsson87c149b2007-10-11 01:00:40 +00004651 BuiltinVaListType = T;
4652}
4653
Chris Lattnere7cabb92009-07-13 00:10:46 +00004654void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004655 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004656}
4657
Chris Lattnere7cabb92009-07-13 00:10:46 +00004658void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004659 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004660}
4661
Chris Lattnere7cabb92009-07-13 00:10:46 +00004662void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004663 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004664}
4665
Chris Lattnere7cabb92009-07-13 00:10:46 +00004666void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004667 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004668}
4669
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004670void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004671 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004672 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004673
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004674 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004675}
4676
John McCalld28ae272009-12-02 08:04:21 +00004677/// \brief Retrieve the template name that corresponds to a non-empty
4678/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004679TemplateName
4680ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4681 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004682 unsigned size = End - Begin;
4683 assert(size > 1 && "set is not overloaded!");
4684
4685 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4686 size * sizeof(FunctionTemplateDecl*));
4687 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4688
4689 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004690 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004691 NamedDecl *D = *I;
4692 assert(isa<FunctionTemplateDecl>(D) ||
4693 (isa<UsingShadowDecl>(D) &&
4694 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4695 *Storage++ = D;
4696 }
4697
4698 return TemplateName(OT);
4699}
4700
Douglas Gregordc572a32009-03-30 22:58:21 +00004701/// \brief Retrieve the template name that represents a qualified
4702/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004703TemplateName
4704ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4705 bool TemplateKeyword,
4706 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004707 assert(NNS && "Missing nested-name-specifier in qualified template name");
4708
Douglas Gregorc42075a2010-02-04 18:10:26 +00004709 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004710 llvm::FoldingSetNodeID ID;
4711 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4712
4713 void *InsertPos = 0;
4714 QualifiedTemplateName *QTN =
4715 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4716 if (!QTN) {
4717 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4718 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4719 }
4720
4721 return TemplateName(QTN);
4722}
4723
4724/// \brief Retrieve the template name that represents a dependent
4725/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004726TemplateName
4727ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4728 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004729 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004730 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004731
4732 llvm::FoldingSetNodeID ID;
4733 DependentTemplateName::Profile(ID, NNS, Name);
4734
4735 void *InsertPos = 0;
4736 DependentTemplateName *QTN =
4737 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4738
4739 if (QTN)
4740 return TemplateName(QTN);
4741
4742 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4743 if (CanonNNS == NNS) {
4744 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4745 } else {
4746 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4747 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004748 DependentTemplateName *CheckQTN =
4749 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4750 assert(!CheckQTN && "Dependent type name canonicalization broken");
4751 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004752 }
4753
4754 DependentTemplateNames.InsertNode(QTN, InsertPos);
4755 return TemplateName(QTN);
4756}
4757
Douglas Gregor71395fa2009-11-04 00:56:37 +00004758/// \brief Retrieve the template name that represents a dependent
4759/// template name such as \c MetaFun::template operator+.
4760TemplateName
4761ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004762 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004763 assert((!NNS || NNS->isDependent()) &&
4764 "Nested name specifier must be dependent");
4765
4766 llvm::FoldingSetNodeID ID;
4767 DependentTemplateName::Profile(ID, NNS, Operator);
4768
4769 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004770 DependentTemplateName *QTN
4771 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004772
4773 if (QTN)
4774 return TemplateName(QTN);
4775
4776 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4777 if (CanonNNS == NNS) {
4778 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4779 } else {
4780 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4781 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004782
4783 DependentTemplateName *CheckQTN
4784 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4785 assert(!CheckQTN && "Dependent template name canonicalization broken");
4786 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004787 }
4788
4789 DependentTemplateNames.InsertNode(QTN, InsertPos);
4790 return TemplateName(QTN);
4791}
4792
Douglas Gregor5590be02011-01-15 06:45:20 +00004793TemplateName
4794ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4795 const TemplateArgument &ArgPack) const {
4796 ASTContext &Self = const_cast<ASTContext &>(*this);
4797 llvm::FoldingSetNodeID ID;
4798 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4799
4800 void *InsertPos = 0;
4801 SubstTemplateTemplateParmPackStorage *Subst
4802 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4803
4804 if (!Subst) {
4805 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4806 ArgPack.pack_size(),
4807 ArgPack.pack_begin());
4808 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4809 }
4810
4811 return TemplateName(Subst);
4812}
4813
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004814/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004815/// TargetInfo, produce the corresponding type. The unsigned @p Type
4816/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004817CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004818 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004819 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004820 case TargetInfo::SignedShort: return ShortTy;
4821 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4822 case TargetInfo::SignedInt: return IntTy;
4823 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4824 case TargetInfo::SignedLong: return LongTy;
4825 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4826 case TargetInfo::SignedLongLong: return LongLongTy;
4827 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4828 }
4829
4830 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004831 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004832}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004833
4834//===----------------------------------------------------------------------===//
4835// Type Predicates.
4836//===----------------------------------------------------------------------===//
4837
Fariborz Jahanian96207692009-02-18 21:49:28 +00004838/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4839/// garbage collection attribute.
4840///
John McCall553d45a2011-01-12 00:34:59 +00004841Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4842 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4843 return Qualifiers::GCNone;
4844
4845 assert(getLangOptions().ObjC1);
4846 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4847
4848 // Default behaviour under objective-C's gc is for ObjC pointers
4849 // (or pointers to them) be treated as though they were declared
4850 // as __strong.
4851 if (GCAttrs == Qualifiers::GCNone) {
4852 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4853 return Qualifiers::Strong;
4854 else if (Ty->isPointerType())
4855 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4856 } else {
4857 // It's not valid to set GC attributes on anything that isn't a
4858 // pointer.
4859#ifndef NDEBUG
4860 QualType CT = Ty->getCanonicalTypeInternal();
4861 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4862 CT = AT->getElementType();
4863 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4864#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004865 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004866 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004867}
4868
Chris Lattner49af6a42008-04-07 06:51:04 +00004869//===----------------------------------------------------------------------===//
4870// Type Compatibility Testing
4871//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004872
Mike Stump11289f42009-09-09 15:08:12 +00004873/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004874/// compatible.
4875static bool areCompatVectorTypes(const VectorType *LHS,
4876 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004877 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004878 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004879 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004880}
4881
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004882bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4883 QualType SecondVec) {
4884 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4885 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4886
4887 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4888 return true;
4889
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004890 // Treat Neon vector types and most AltiVec vector types as if they are the
4891 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004892 const VectorType *First = FirstVec->getAs<VectorType>();
4893 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004894 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004895 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004896 First->getVectorKind() != VectorType::AltiVecPixel &&
4897 First->getVectorKind() != VectorType::AltiVecBool &&
4898 Second->getVectorKind() != VectorType::AltiVecPixel &&
4899 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004900 return true;
4901
4902 return false;
4903}
4904
Steve Naroff8e6aee52009-07-23 01:01:38 +00004905//===----------------------------------------------------------------------===//
4906// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4907//===----------------------------------------------------------------------===//
4908
4909/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4910/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00004911bool
4912ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4913 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00004914 if (lProto == rProto)
4915 return true;
4916 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4917 E = rProto->protocol_end(); PI != E; ++PI)
4918 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4919 return true;
4920 return false;
4921}
4922
Steve Naroff8e6aee52009-07-23 01:01:38 +00004923/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4924/// return true if lhs's protocols conform to rhs's protocol; false
4925/// otherwise.
4926bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4927 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4928 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4929 return false;
4930}
4931
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00004932/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4933/// Class<p1, ...>.
4934bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4935 QualType rhs) {
4936 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4937 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4938 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4939
4940 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4941 E = lhsQID->qual_end(); I != E; ++I) {
4942 bool match = false;
4943 ObjCProtocolDecl *lhsProto = *I;
4944 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4945 E = rhsOPT->qual_end(); J != E; ++J) {
4946 ObjCProtocolDecl *rhsProto = *J;
4947 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4948 match = true;
4949 break;
4950 }
4951 }
4952 if (!match)
4953 return false;
4954 }
4955 return true;
4956}
4957
Steve Naroff8e6aee52009-07-23 01:01:38 +00004958/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4959/// ObjCQualifiedIDType.
4960bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4961 bool compare) {
4962 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00004963 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004964 lhs->isObjCIdType() || lhs->isObjCClassType())
4965 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004966 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00004967 rhs->isObjCIdType() || rhs->isObjCClassType())
4968 return true;
4969
4970 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004971 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00004972
Steve Naroff8e6aee52009-07-23 01:01:38 +00004973 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00004974
Steve Naroff8e6aee52009-07-23 01:01:38 +00004975 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00004976 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00004977 // make sure we check the class hierarchy.
4978 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4979 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4980 E = lhsQID->qual_end(); I != E; ++I) {
4981 // when comparing an id<P> on lhs with a static type on rhs,
4982 // see if static class implements all of id's protocols, directly or
4983 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00004984 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00004985 return false;
4986 }
4987 }
4988 // If there are no qualifiers and no interface, we have an 'id'.
4989 return true;
4990 }
Mike Stump11289f42009-09-09 15:08:12 +00004991 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00004992 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4993 E = lhsQID->qual_end(); I != E; ++I) {
4994 ObjCProtocolDecl *lhsProto = *I;
4995 bool match = false;
4996
4997 // when comparing an id<P> on lhs with a static type on rhs,
4998 // see if static class implements all of id's protocols, directly or
4999 // through its super class and categories.
5000 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5001 E = rhsOPT->qual_end(); J != E; ++J) {
5002 ObjCProtocolDecl *rhsProto = *J;
5003 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5004 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5005 match = true;
5006 break;
5007 }
5008 }
Mike Stump11289f42009-09-09 15:08:12 +00005009 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005010 // make sure we check the class hierarchy.
5011 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5012 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5013 E = lhsQID->qual_end(); I != E; ++I) {
5014 // when comparing an id<P> on lhs with a static type on rhs,
5015 // see if static class implements all of id's protocols, directly or
5016 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005017 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005018 match = true;
5019 break;
5020 }
5021 }
5022 }
5023 if (!match)
5024 return false;
5025 }
Mike Stump11289f42009-09-09 15:08:12 +00005026
Steve Naroff8e6aee52009-07-23 01:01:38 +00005027 return true;
5028 }
Mike Stump11289f42009-09-09 15:08:12 +00005029
Steve Naroff8e6aee52009-07-23 01:01:38 +00005030 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5031 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5032
Mike Stump11289f42009-09-09 15:08:12 +00005033 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005034 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005035 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005036 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5037 E = lhsOPT->qual_end(); I != E; ++I) {
5038 ObjCProtocolDecl *lhsProto = *I;
5039 bool match = false;
5040
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005041 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005042 // see if static class implements all of id's protocols, directly or
5043 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005044 // First, lhs protocols in the qualifier list must be found, direct
5045 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005046 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5047 E = rhsQID->qual_end(); J != E; ++J) {
5048 ObjCProtocolDecl *rhsProto = *J;
5049 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5050 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5051 match = true;
5052 break;
5053 }
5054 }
5055 if (!match)
5056 return false;
5057 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005058
5059 // Static class's protocols, or its super class or category protocols
5060 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5061 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5062 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5063 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5064 // This is rather dubious but matches gcc's behavior. If lhs has
5065 // no type qualifier and its class has no static protocol(s)
5066 // assume that it is mismatch.
5067 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5068 return false;
5069 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5070 LHSInheritedProtocols.begin(),
5071 E = LHSInheritedProtocols.end(); I != E; ++I) {
5072 bool match = false;
5073 ObjCProtocolDecl *lhsProto = (*I);
5074 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5075 E = rhsQID->qual_end(); J != E; ++J) {
5076 ObjCProtocolDecl *rhsProto = *J;
5077 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5078 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5079 match = true;
5080 break;
5081 }
5082 }
5083 if (!match)
5084 return false;
5085 }
5086 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005087 return true;
5088 }
5089 return false;
5090}
5091
Eli Friedman47f77112008-08-22 00:56:42 +00005092/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005093/// compatible for assignment from RHS to LHS. This handles validation of any
5094/// protocol qualifiers on the LHS or RHS.
5095///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005096bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5097 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005098 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5099 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5100
Steve Naroff1329fa02009-07-15 18:40:39 +00005101 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005102 if (LHS->isObjCUnqualifiedIdOrClass() ||
5103 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005104 return true;
5105
John McCall8b07ec22010-05-15 11:32:37 +00005106 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005107 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5108 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005109 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005110
5111 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5112 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5113 QualType(RHSOPT,0));
5114
John McCall8b07ec22010-05-15 11:32:37 +00005115 // If we have 2 user-defined types, fall into that path.
5116 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005117 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005118
Steve Naroff8e6aee52009-07-23 01:01:38 +00005119 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005120}
5121
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005122/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005123/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005124/// arguments in block literals. When passed as arguments, passing 'A*' where
5125/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5126/// not OK. For the return type, the opposite is not OK.
5127bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5128 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005129 const ObjCObjectPointerType *RHSOPT,
5130 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005131 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005132 return true;
5133
5134 if (LHSOPT->isObjCBuiltinType()) {
5135 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5136 }
5137
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005138 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005139 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5140 QualType(RHSOPT,0),
5141 false);
5142
5143 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5144 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5145 if (LHS && RHS) { // We have 2 user-defined types.
5146 if (LHS != RHS) {
5147 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005148 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005149 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005150 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005151 }
5152 else
5153 return true;
5154 }
5155 return false;
5156}
5157
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005158/// getIntersectionOfProtocols - This routine finds the intersection of set
5159/// of protocols inherited from two distinct objective-c pointer objects.
5160/// It is used to build composite qualifier list of the composite type of
5161/// the conditional expression involving two objective-c pointer objects.
5162static
5163void getIntersectionOfProtocols(ASTContext &Context,
5164 const ObjCObjectPointerType *LHSOPT,
5165 const ObjCObjectPointerType *RHSOPT,
5166 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
5167
John McCall8b07ec22010-05-15 11:32:37 +00005168 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5169 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5170 assert(LHS->getInterface() && "LHS must have an interface base");
5171 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005172
5173 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5174 unsigned LHSNumProtocols = LHS->getNumProtocols();
5175 if (LHSNumProtocols > 0)
5176 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5177 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005178 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005179 Context.CollectInheritedProtocols(LHS->getInterface(),
5180 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005181 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5182 LHSInheritedProtocols.end());
5183 }
5184
5185 unsigned RHSNumProtocols = RHS->getNumProtocols();
5186 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005187 ObjCProtocolDecl **RHSProtocols =
5188 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005189 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5190 if (InheritedProtocolSet.count(RHSProtocols[i]))
5191 IntersectionOfProtocols.push_back(RHSProtocols[i]);
5192 }
5193 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005194 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005195 Context.CollectInheritedProtocols(RHS->getInterface(),
5196 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005197 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5198 RHSInheritedProtocols.begin(),
5199 E = RHSInheritedProtocols.end(); I != E; ++I)
5200 if (InheritedProtocolSet.count((*I)))
5201 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005202 }
5203}
5204
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005205/// areCommonBaseCompatible - Returns common base class of the two classes if
5206/// one found. Note that this is O'2 algorithm. But it will be called as the
5207/// last type comparison in a ?-exp of ObjC pointer types before a
5208/// warning is issued. So, its invokation is extremely rare.
5209QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005210 const ObjCObjectPointerType *Lptr,
5211 const ObjCObjectPointerType *Rptr) {
5212 const ObjCObjectType *LHS = Lptr->getObjectType();
5213 const ObjCObjectType *RHS = Rptr->getObjectType();
5214 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5215 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005216 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005217 return QualType();
5218
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005219 do {
John McCall8b07ec22010-05-15 11:32:37 +00005220 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005221 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00005222 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
5223 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5224
5225 QualType Result = QualType(LHS, 0);
5226 if (!Protocols.empty())
5227 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5228 Result = getObjCObjectPointerType(Result);
5229 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005230 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005231 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005232
5233 return QualType();
5234}
5235
John McCall8b07ec22010-05-15 11:32:37 +00005236bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5237 const ObjCObjectType *RHS) {
5238 assert(LHS->getInterface() && "LHS is not an interface type");
5239 assert(RHS->getInterface() && "RHS is not an interface type");
5240
Chris Lattner49af6a42008-04-07 06:51:04 +00005241 // Verify that the base decls are compatible: the RHS must be a subclass of
5242 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005243 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005244 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005245
Chris Lattner49af6a42008-04-07 06:51:04 +00005246 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5247 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005248 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005249 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005250
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005251 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5252 // more detailed analysis is required.
5253 if (RHS->getNumProtocols() == 0) {
5254 // OK, if LHS is a superclass of RHS *and*
5255 // this superclass is assignment compatible with LHS.
5256 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005257 bool IsSuperClass =
5258 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5259 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005260 // OK if conversion of LHS to SuperClass results in narrowing of types
5261 // ; i.e., SuperClass may implement at least one of the protocols
5262 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5263 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5264 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005265 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005266 // If super class has no protocols, it is not a match.
5267 if (SuperClassInheritedProtocols.empty())
5268 return false;
5269
5270 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5271 LHSPE = LHS->qual_end();
5272 LHSPI != LHSPE; LHSPI++) {
5273 bool SuperImplementsProtocol = false;
5274 ObjCProtocolDecl *LHSProto = (*LHSPI);
5275
5276 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5277 SuperClassInheritedProtocols.begin(),
5278 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5279 ObjCProtocolDecl *SuperClassProto = (*I);
5280 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5281 SuperImplementsProtocol = true;
5282 break;
5283 }
5284 }
5285 if (!SuperImplementsProtocol)
5286 return false;
5287 }
5288 return true;
5289 }
5290 return false;
5291 }
Mike Stump11289f42009-09-09 15:08:12 +00005292
John McCall8b07ec22010-05-15 11:32:37 +00005293 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5294 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005295 LHSPI != LHSPE; LHSPI++) {
5296 bool RHSImplementsProtocol = false;
5297
5298 // If the RHS doesn't implement the protocol on the left, the types
5299 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005300 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5301 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005302 RHSPI != RHSPE; RHSPI++) {
5303 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005304 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005305 break;
5306 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005307 }
5308 // FIXME: For better diagnostics, consider passing back the protocol name.
5309 if (!RHSImplementsProtocol)
5310 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005311 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005312 // The RHS implements all protocols listed on the LHS.
5313 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005314}
5315
Steve Naroffb7605152009-02-12 17:52:19 +00005316bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5317 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005318 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5319 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005320
Steve Naroff7cae42b2009-07-10 23:34:53 +00005321 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005322 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005323
5324 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5325 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005326}
5327
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005328bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5329 return canAssignObjCInterfaces(
5330 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5331 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5332}
5333
Mike Stump11289f42009-09-09 15:08:12 +00005334/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005335/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005336/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005337/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005338bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5339 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005340 if (getLangOptions().CPlusPlus)
5341 return hasSameType(LHS, RHS);
5342
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005343 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005344}
5345
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005346bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5347 return !mergeTypes(LHS, RHS, true).isNull();
5348}
5349
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005350/// mergeTransparentUnionType - if T is a transparent union type and a member
5351/// of T is compatible with SubType, return the merged type, else return
5352/// QualType()
5353QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5354 bool OfBlockPointer,
5355 bool Unqualified) {
5356 if (const RecordType *UT = T->getAsUnionType()) {
5357 RecordDecl *UD = UT->getDecl();
5358 if (UD->hasAttr<TransparentUnionAttr>()) {
5359 for (RecordDecl::field_iterator it = UD->field_begin(),
5360 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005361 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005362 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5363 if (!MT.isNull())
5364 return MT;
5365 }
5366 }
5367 }
5368
5369 return QualType();
5370}
5371
5372/// mergeFunctionArgumentTypes - merge two types which appear as function
5373/// argument types
5374QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5375 bool OfBlockPointer,
5376 bool Unqualified) {
5377 // GNU extension: two types are compatible if they appear as a function
5378 // argument, one of the types is a transparent union type and the other
5379 // type is compatible with a union member
5380 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5381 Unqualified);
5382 if (!lmerge.isNull())
5383 return lmerge;
5384
5385 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5386 Unqualified);
5387 if (!rmerge.isNull())
5388 return rmerge;
5389
5390 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5391}
5392
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005393QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005394 bool OfBlockPointer,
5395 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005396 const FunctionType *lbase = lhs->getAs<FunctionType>();
5397 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005398 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5399 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005400 bool allLTypes = true;
5401 bool allRTypes = true;
5402
5403 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005404 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005405 if (OfBlockPointer) {
5406 QualType RHS = rbase->getResultType();
5407 QualType LHS = lbase->getResultType();
5408 bool UnqualifiedResult = Unqualified;
5409 if (!UnqualifiedResult)
5410 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005411 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005412 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005413 else
John McCall8c6b56f2010-12-15 01:06:38 +00005414 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5415 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005416 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005417
5418 if (Unqualified)
5419 retType = retType.getUnqualifiedType();
5420
5421 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5422 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5423 if (Unqualified) {
5424 LRetType = LRetType.getUnqualifiedType();
5425 RRetType = RRetType.getUnqualifiedType();
5426 }
5427
5428 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005429 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005430 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005431 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005432
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005433 // FIXME: double check this
5434 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5435 // rbase->getRegParmAttr() != 0 &&
5436 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005437 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5438 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005439
Douglas Gregor8c940862010-01-18 17:14:39 +00005440 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005441 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005442 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005443
John McCall8c6b56f2010-12-15 01:06:38 +00005444 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005445 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5446 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005447 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5448 return QualType();
5449
John McCall31168b02011-06-15 23:02:42 +00005450 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5451 return QualType();
5452
John McCall8c6b56f2010-12-15 01:06:38 +00005453 // It's noreturn if either type is.
5454 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5455 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5456 if (NoReturn != lbaseInfo.getNoReturn())
5457 allLTypes = false;
5458 if (NoReturn != rbaseInfo.getNoReturn())
5459 allRTypes = false;
5460
John McCall31168b02011-06-15 23:02:42 +00005461 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005462
Eli Friedman47f77112008-08-22 00:56:42 +00005463 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005464 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5465 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005466 unsigned lproto_nargs = lproto->getNumArgs();
5467 unsigned rproto_nargs = rproto->getNumArgs();
5468
5469 // Compatible functions must have the same number of arguments
5470 if (lproto_nargs != rproto_nargs)
5471 return QualType();
5472
5473 // Variadic and non-variadic functions aren't compatible
5474 if (lproto->isVariadic() != rproto->isVariadic())
5475 return QualType();
5476
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005477 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5478 return QualType();
5479
Eli Friedman47f77112008-08-22 00:56:42 +00005480 // Check argument compatibility
5481 llvm::SmallVector<QualType, 10> types;
5482 for (unsigned i = 0; i < lproto_nargs; i++) {
5483 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5484 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005485 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5486 OfBlockPointer,
5487 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005488 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005489
5490 if (Unqualified)
5491 argtype = argtype.getUnqualifiedType();
5492
Eli Friedman47f77112008-08-22 00:56:42 +00005493 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005494 if (Unqualified) {
5495 largtype = largtype.getUnqualifiedType();
5496 rargtype = rargtype.getUnqualifiedType();
5497 }
5498
Chris Lattner465fa322008-10-05 17:34:18 +00005499 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5500 allLTypes = false;
5501 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5502 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005503 }
5504 if (allLTypes) return lhs;
5505 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005506
5507 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5508 EPI.ExtInfo = einfo;
5509 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005510 }
5511
5512 if (lproto) allRTypes = false;
5513 if (rproto) allLTypes = false;
5514
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005515 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005516 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005517 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005518 if (proto->isVariadic()) return QualType();
5519 // Check that the types are compatible with the types that
5520 // would result from default argument promotions (C99 6.7.5.3p15).
5521 // The only types actually affected are promotable integer
5522 // types and floats, which would be passed as a different
5523 // type depending on whether the prototype is visible.
5524 unsigned proto_nargs = proto->getNumArgs();
5525 for (unsigned i = 0; i < proto_nargs; ++i) {
5526 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005527
5528 // Look at the promotion type of enum types, since that is the type used
5529 // to pass enum values.
5530 if (const EnumType *Enum = argTy->getAs<EnumType>())
5531 argTy = Enum->getDecl()->getPromotionType();
5532
Eli Friedman47f77112008-08-22 00:56:42 +00005533 if (argTy->isPromotableIntegerType() ||
5534 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5535 return QualType();
5536 }
5537
5538 if (allLTypes) return lhs;
5539 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005540
5541 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5542 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005543 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005544 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005545 }
5546
5547 if (allLTypes) return lhs;
5548 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005549 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005550}
5551
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005552QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005553 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005554 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005555 // C++ [expr]: If an expression initially has the type "reference to T", the
5556 // type is adjusted to "T" prior to any further analysis, the expression
5557 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005558 // expression is an lvalue unless the reference is an rvalue reference and
5559 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005560 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5561 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005562
5563 if (Unqualified) {
5564 LHS = LHS.getUnqualifiedType();
5565 RHS = RHS.getUnqualifiedType();
5566 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005567
Eli Friedman47f77112008-08-22 00:56:42 +00005568 QualType LHSCan = getCanonicalType(LHS),
5569 RHSCan = getCanonicalType(RHS);
5570
5571 // If two types are identical, they are compatible.
5572 if (LHSCan == RHSCan)
5573 return LHS;
5574
John McCall8ccfcb52009-09-24 19:53:00 +00005575 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005576 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5577 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005578 if (LQuals != RQuals) {
5579 // If any of these qualifiers are different, we have a type
5580 // mismatch.
5581 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005582 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5583 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005584 return QualType();
5585
5586 // Exactly one GC qualifier difference is allowed: __strong is
5587 // okay if the other type has no GC qualifier but is an Objective
5588 // C object pointer (i.e. implicitly strong by default). We fix
5589 // this by pretending that the unqualified type was actually
5590 // qualified __strong.
5591 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5592 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5593 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5594
5595 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5596 return QualType();
5597
5598 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5599 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5600 }
5601 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5602 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5603 }
Eli Friedman47f77112008-08-22 00:56:42 +00005604 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005605 }
5606
5607 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005608
Eli Friedmandcca6332009-06-01 01:22:52 +00005609 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5610 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005611
Chris Lattnerfd652912008-01-14 05:45:46 +00005612 // We want to consider the two function types to be the same for these
5613 // comparisons, just force one to the other.
5614 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5615 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005616
5617 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005618 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5619 LHSClass = Type::ConstantArray;
5620 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5621 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005622
John McCall8b07ec22010-05-15 11:32:37 +00005623 // ObjCInterfaces are just specialized ObjCObjects.
5624 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5625 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5626
Nate Begemance4d7fc2008-04-18 23:10:10 +00005627 // Canonicalize ExtVector -> Vector.
5628 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5629 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005630
Chris Lattner95554662008-04-07 05:43:21 +00005631 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005632 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005633 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005634 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005635 // Compatibility is based on the underlying type, not the promotion
5636 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005637 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005638 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5639 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005640 }
John McCall9dd450b2009-09-21 23:43:11 +00005641 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005642 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5643 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005644 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005645
Eli Friedman47f77112008-08-22 00:56:42 +00005646 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005647 }
Eli Friedman47f77112008-08-22 00:56:42 +00005648
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005649 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005650 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005651#define TYPE(Class, Base)
5652#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005653#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005654#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5655#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5656#include "clang/AST/TypeNodes.def"
5657 assert(false && "Non-canonical and dependent types shouldn't get here");
5658 return QualType();
5659
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005660 case Type::LValueReference:
5661 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005662 case Type::MemberPointer:
5663 assert(false && "C++ should never be in mergeTypes");
5664 return QualType();
5665
John McCall8b07ec22010-05-15 11:32:37 +00005666 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005667 case Type::IncompleteArray:
5668 case Type::VariableArray:
5669 case Type::FunctionProto:
5670 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005671 assert(false && "Types are eliminated above");
5672 return QualType();
5673
Chris Lattnerfd652912008-01-14 05:45:46 +00005674 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005675 {
5676 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005677 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5678 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005679 if (Unqualified) {
5680 LHSPointee = LHSPointee.getUnqualifiedType();
5681 RHSPointee = RHSPointee.getUnqualifiedType();
5682 }
5683 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5684 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005685 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005686 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005687 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005688 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005689 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005690 return getPointerType(ResultType);
5691 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005692 case Type::BlockPointer:
5693 {
5694 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005695 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5696 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005697 if (Unqualified) {
5698 LHSPointee = LHSPointee.getUnqualifiedType();
5699 RHSPointee = RHSPointee.getUnqualifiedType();
5700 }
5701 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5702 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005703 if (ResultType.isNull()) return QualType();
5704 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5705 return LHS;
5706 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5707 return RHS;
5708 return getBlockPointerType(ResultType);
5709 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005710 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005711 {
5712 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5713 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5714 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5715 return QualType();
5716
5717 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5718 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005719 if (Unqualified) {
5720 LHSElem = LHSElem.getUnqualifiedType();
5721 RHSElem = RHSElem.getUnqualifiedType();
5722 }
5723
5724 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005725 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005726 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5727 return LHS;
5728 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5729 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005730 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5731 ArrayType::ArraySizeModifier(), 0);
5732 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5733 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005734 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5735 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005736 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5737 return LHS;
5738 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5739 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005740 if (LVAT) {
5741 // FIXME: This isn't correct! But tricky to implement because
5742 // the array's size has to be the size of LHS, but the type
5743 // has to be different.
5744 return LHS;
5745 }
5746 if (RVAT) {
5747 // FIXME: This isn't correct! But tricky to implement because
5748 // the array's size has to be the size of RHS, but the type
5749 // has to be different.
5750 return RHS;
5751 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005752 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5753 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005754 return getIncompleteArrayType(ResultType,
5755 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005756 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005757 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005758 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005759 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005760 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005761 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005762 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005763 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005764 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005765 case Type::Complex:
5766 // Distinct complex types are incompatible.
5767 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005768 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005769 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005770 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5771 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005772 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005773 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005774 case Type::ObjCObject: {
5775 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005776 // FIXME: This should be type compatibility, e.g. whether
5777 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005778 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5779 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5780 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005781 return LHS;
5782
Eli Friedman47f77112008-08-22 00:56:42 +00005783 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005784 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005785 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005786 if (OfBlockPointer) {
5787 if (canAssignObjCInterfacesInBlockPointer(
5788 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005789 RHS->getAs<ObjCObjectPointerType>(),
5790 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005791 return LHS;
5792 return QualType();
5793 }
John McCall9dd450b2009-09-21 23:43:11 +00005794 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5795 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005796 return LHS;
5797
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005798 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005799 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005800 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005801
5802 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005803}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005804
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005805/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5806/// 'RHS' attributes and returns the merged version; including for function
5807/// return types.
5808QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5809 QualType LHSCan = getCanonicalType(LHS),
5810 RHSCan = getCanonicalType(RHS);
5811 // If two types are identical, they are compatible.
5812 if (LHSCan == RHSCan)
5813 return LHS;
5814 if (RHSCan->isFunctionType()) {
5815 if (!LHSCan->isFunctionType())
5816 return QualType();
5817 QualType OldReturnType =
5818 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5819 QualType NewReturnType =
5820 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5821 QualType ResReturnType =
5822 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5823 if (ResReturnType.isNull())
5824 return QualType();
5825 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5826 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5827 // In either case, use OldReturnType to build the new function type.
5828 const FunctionType *F = LHS->getAs<FunctionType>();
5829 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005830 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5831 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005832 QualType ResultType
5833 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005834 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005835 return ResultType;
5836 }
5837 }
5838 return QualType();
5839 }
5840
5841 // If the qualifiers are different, the types can still be merged.
5842 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5843 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5844 if (LQuals != RQuals) {
5845 // If any of these qualifiers are different, we have a type mismatch.
5846 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5847 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5848 return QualType();
5849
5850 // Exactly one GC qualifier difference is allowed: __strong is
5851 // okay if the other type has no GC qualifier but is an Objective
5852 // C object pointer (i.e. implicitly strong by default). We fix
5853 // this by pretending that the unqualified type was actually
5854 // qualified __strong.
5855 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5856 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5857 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5858
5859 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5860 return QualType();
5861
5862 if (GC_L == Qualifiers::Strong)
5863 return LHS;
5864 if (GC_R == Qualifiers::Strong)
5865 return RHS;
5866 return QualType();
5867 }
5868
5869 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5870 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5871 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5872 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5873 if (ResQT == LHSBaseQT)
5874 return LHS;
5875 if (ResQT == RHSBaseQT)
5876 return RHS;
5877 }
5878 return QualType();
5879}
5880
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005881//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005882// Integer Predicates
5883//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005884
Jay Foad39c79802011-01-12 09:06:06 +00005885unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005886 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005887 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005888 if (T->isBooleanType())
5889 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005890 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005891 return (unsigned)getTypeSize(T);
5892}
5893
5894QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005895 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005896
5897 // Turn <4 x signed int> -> <4 x unsigned int>
5898 if (const VectorType *VTy = T->getAs<VectorType>())
5899 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005900 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005901
5902 // For enums, we return the unsigned version of the base type.
5903 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005904 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00005905
5906 const BuiltinType *BTy = T->getAs<BuiltinType>();
5907 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005908 switch (BTy->getKind()) {
5909 case BuiltinType::Char_S:
5910 case BuiltinType::SChar:
5911 return UnsignedCharTy;
5912 case BuiltinType::Short:
5913 return UnsignedShortTy;
5914 case BuiltinType::Int:
5915 return UnsignedIntTy;
5916 case BuiltinType::Long:
5917 return UnsignedLongTy;
5918 case BuiltinType::LongLong:
5919 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00005920 case BuiltinType::Int128:
5921 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005922 default:
5923 assert(0 && "Unexpected signed integer type");
5924 return QualType();
5925 }
5926}
5927
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005928ASTMutationListener::~ASTMutationListener() { }
5929
Chris Lattnerecd79c62009-06-14 00:45:47 +00005930
5931//===----------------------------------------------------------------------===//
5932// Builtin Type Computation
5933//===----------------------------------------------------------------------===//
5934
5935/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00005936/// pointer over the consumed characters. This returns the resultant type. If
5937/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5938/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5939/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005940///
5941/// RequiresICE is filled in on return to indicate whether the value is required
5942/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00005943static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00005944 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005945 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00005946 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00005947 // Modifiers.
5948 int HowLong = 0;
5949 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005950 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00005951
Chris Lattnerdc226c22010-10-01 22:42:38 +00005952 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00005953 bool Done = false;
5954 while (!Done) {
5955 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00005956 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00005957 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00005958 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00005959 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00005960 case 'S':
5961 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5962 assert(!Signed && "Can't use 'S' modifier multiple times!");
5963 Signed = true;
5964 break;
5965 case 'U':
5966 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5967 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5968 Unsigned = true;
5969 break;
5970 case 'L':
5971 assert(HowLong <= 2 && "Can't have LLLL modifier");
5972 ++HowLong;
5973 break;
5974 }
5975 }
5976
5977 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00005978
Chris Lattnerecd79c62009-06-14 00:45:47 +00005979 // Read the base type.
5980 switch (*Str++) {
5981 default: assert(0 && "Unknown builtin type letter!");
5982 case 'v':
5983 assert(HowLong == 0 && !Signed && !Unsigned &&
5984 "Bad modifiers used with 'v'!");
5985 Type = Context.VoidTy;
5986 break;
5987 case 'f':
5988 assert(HowLong == 0 && !Signed && !Unsigned &&
5989 "Bad modifiers used with 'f'!");
5990 Type = Context.FloatTy;
5991 break;
5992 case 'd':
5993 assert(HowLong < 2 && !Signed && !Unsigned &&
5994 "Bad modifiers used with 'd'!");
5995 if (HowLong)
5996 Type = Context.LongDoubleTy;
5997 else
5998 Type = Context.DoubleTy;
5999 break;
6000 case 's':
6001 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6002 if (Unsigned)
6003 Type = Context.UnsignedShortTy;
6004 else
6005 Type = Context.ShortTy;
6006 break;
6007 case 'i':
6008 if (HowLong == 3)
6009 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6010 else if (HowLong == 2)
6011 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6012 else if (HowLong == 1)
6013 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6014 else
6015 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6016 break;
6017 case 'c':
6018 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6019 if (Signed)
6020 Type = Context.SignedCharTy;
6021 else if (Unsigned)
6022 Type = Context.UnsignedCharTy;
6023 else
6024 Type = Context.CharTy;
6025 break;
6026 case 'b': // boolean
6027 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6028 Type = Context.BoolTy;
6029 break;
6030 case 'z': // size_t.
6031 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6032 Type = Context.getSizeType();
6033 break;
6034 case 'F':
6035 Type = Context.getCFConstantStringType();
6036 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006037 case 'G':
6038 Type = Context.getObjCIdType();
6039 break;
6040 case 'H':
6041 Type = Context.getObjCSelType();
6042 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006043 case 'a':
6044 Type = Context.getBuiltinVaListType();
6045 assert(!Type.isNull() && "builtin va list type not initialized!");
6046 break;
6047 case 'A':
6048 // This is a "reference" to a va_list; however, what exactly
6049 // this means depends on how va_list is defined. There are two
6050 // different kinds of va_list: ones passed by value, and ones
6051 // passed by reference. An example of a by-value va_list is
6052 // x86, where va_list is a char*. An example of by-ref va_list
6053 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6054 // we want this argument to be a char*&; for x86-64, we want
6055 // it to be a __va_list_tag*.
6056 Type = Context.getBuiltinVaListType();
6057 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006058 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006059 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006060 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006061 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006062 break;
6063 case 'V': {
6064 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006065 unsigned NumElements = strtoul(Str, &End, 10);
6066 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006067 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006068
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006069 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6070 RequiresICE, false);
6071 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006072
6073 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006074 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006075 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006076 break;
6077 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006078 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006079 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6080 false);
6081 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006082 Type = Context.getComplexType(ElementType);
6083 break;
6084 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006085 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006086 Type = Context.getFILEType();
6087 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006088 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006089 return QualType();
6090 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006091 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006092 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006093 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006094 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006095 else
6096 Type = Context.getjmp_bufType();
6097
Mike Stump2adb4da2009-07-28 23:47:15 +00006098 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006099 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006100 return QualType();
6101 }
6102 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006103 }
Mike Stump11289f42009-09-09 15:08:12 +00006104
Chris Lattnerdc226c22010-10-01 22:42:38 +00006105 // If there are modifiers and if we're allowed to parse them, go for it.
6106 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006107 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006108 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006109 default: Done = true; --Str; break;
6110 case '*':
6111 case '&': {
6112 // Both pointers and references can have their pointee types
6113 // qualified with an address space.
6114 char *End;
6115 unsigned AddrSpace = strtoul(Str, &End, 10);
6116 if (End != Str && AddrSpace != 0) {
6117 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6118 Str = End;
6119 }
6120 if (c == '*')
6121 Type = Context.getPointerType(Type);
6122 else
6123 Type = Context.getLValueReferenceType(Type);
6124 break;
6125 }
6126 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6127 case 'C':
6128 Type = Type.withConst();
6129 break;
6130 case 'D':
6131 Type = Context.getVolatileType(Type);
6132 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006133 }
6134 }
Chris Lattner84733392010-10-01 07:13:18 +00006135
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006136 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006137 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006138
Chris Lattnerecd79c62009-06-14 00:45:47 +00006139 return Type;
6140}
6141
6142/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006143QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006144 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006145 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006146 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006147
Chris Lattnerecd79c62009-06-14 00:45:47 +00006148 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006149
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006150 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006151 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006152 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6153 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006154 if (Error != GE_None)
6155 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006156
6157 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6158
Chris Lattnerecd79c62009-06-14 00:45:47 +00006159 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006160 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006161 if (Error != GE_None)
6162 return QualType();
6163
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006164 // If this argument is required to be an IntegerConstantExpression and the
6165 // caller cares, fill in the bitmask we return.
6166 if (RequiresICE && IntegerConstantArgs)
6167 *IntegerConstantArgs |= 1 << ArgTypes.size();
6168
Chris Lattnerecd79c62009-06-14 00:45:47 +00006169 // Do array -> pointer decay. The builtin should use the decayed type.
6170 if (Ty->isArrayType())
6171 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006172
Chris Lattnerecd79c62009-06-14 00:45:47 +00006173 ArgTypes.push_back(Ty);
6174 }
6175
6176 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6177 "'.' should only occur at end of builtin type list!");
6178
John McCall991eb4b2010-12-21 00:44:39 +00006179 FunctionType::ExtInfo EI;
6180 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6181
6182 bool Variadic = (TypeStr[0] == '.');
6183
6184 // We really shouldn't be making a no-proto type here, especially in C++.
6185 if (ArgTypes.empty() && Variadic)
6186 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006187
John McCalldb40c7f2010-12-14 08:05:40 +00006188 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006189 EPI.ExtInfo = EI;
6190 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006191
6192 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006193}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006194
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006195GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6196 GVALinkage External = GVA_StrongExternal;
6197
6198 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006199 switch (L) {
6200 case NoLinkage:
6201 case InternalLinkage:
6202 case UniqueExternalLinkage:
6203 return GVA_Internal;
6204
6205 case ExternalLinkage:
6206 switch (FD->getTemplateSpecializationKind()) {
6207 case TSK_Undeclared:
6208 case TSK_ExplicitSpecialization:
6209 External = GVA_StrongExternal;
6210 break;
6211
6212 case TSK_ExplicitInstantiationDefinition:
6213 return GVA_ExplicitTemplateInstantiation;
6214
6215 case TSK_ExplicitInstantiationDeclaration:
6216 case TSK_ImplicitInstantiation:
6217 External = GVA_TemplateInstantiation;
6218 break;
6219 }
6220 }
6221
6222 if (!FD->isInlined())
6223 return External;
6224
6225 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6226 // GNU or C99 inline semantics. Determine whether this symbol should be
6227 // externally visible.
6228 if (FD->isInlineDefinitionExternallyVisible())
6229 return External;
6230
6231 // C99 inline semantics, where the symbol is not externally visible.
6232 return GVA_C99Inline;
6233 }
6234
6235 // C++0x [temp.explicit]p9:
6236 // [ Note: The intent is that an inline function that is the subject of
6237 // an explicit instantiation declaration will still be implicitly
6238 // instantiated when used so that the body can be considered for
6239 // inlining, but that no out-of-line copy of the inline function would be
6240 // generated in the translation unit. -- end note ]
6241 if (FD->getTemplateSpecializationKind()
6242 == TSK_ExplicitInstantiationDeclaration)
6243 return GVA_C99Inline;
6244
6245 return GVA_CXXInline;
6246}
6247
6248GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6249 // If this is a static data member, compute the kind of template
6250 // specialization. Otherwise, this variable is not part of a
6251 // template.
6252 TemplateSpecializationKind TSK = TSK_Undeclared;
6253 if (VD->isStaticDataMember())
6254 TSK = VD->getTemplateSpecializationKind();
6255
6256 Linkage L = VD->getLinkage();
6257 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6258 VD->getType()->getLinkage() == UniqueExternalLinkage)
6259 L = UniqueExternalLinkage;
6260
6261 switch (L) {
6262 case NoLinkage:
6263 case InternalLinkage:
6264 case UniqueExternalLinkage:
6265 return GVA_Internal;
6266
6267 case ExternalLinkage:
6268 switch (TSK) {
6269 case TSK_Undeclared:
6270 case TSK_ExplicitSpecialization:
6271 return GVA_StrongExternal;
6272
6273 case TSK_ExplicitInstantiationDeclaration:
6274 llvm_unreachable("Variable should not be instantiated");
6275 // Fall through to treat this like any other instantiation.
6276
6277 case TSK_ExplicitInstantiationDefinition:
6278 return GVA_ExplicitTemplateInstantiation;
6279
6280 case TSK_ImplicitInstantiation:
6281 return GVA_TemplateInstantiation;
6282 }
6283 }
6284
6285 return GVA_StrongExternal;
6286}
6287
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006288bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006289 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6290 if (!VD->isFileVarDecl())
6291 return false;
6292 } else if (!isa<FunctionDecl>(D))
6293 return false;
6294
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006295 // Weak references don't produce any output by themselves.
6296 if (D->hasAttr<WeakRefAttr>())
6297 return false;
6298
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006299 // Aliases and used decls are required.
6300 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6301 return true;
6302
6303 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6304 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006305 if (!FD->doesThisDeclarationHaveABody())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006306 return false;
6307
6308 // Constructors and destructors are required.
6309 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6310 return true;
6311
6312 // The key function for a class is required.
6313 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6314 const CXXRecordDecl *RD = MD->getParent();
6315 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6316 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6317 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6318 return true;
6319 }
6320 }
6321
6322 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6323
6324 // static, static inline, always_inline, and extern inline functions can
6325 // always be deferred. Normal inline functions can be deferred in C99/C++.
6326 // Implicit template instantiations can also be deferred in C++.
6327 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6328 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6329 return false;
6330 return true;
6331 }
6332
6333 const VarDecl *VD = cast<VarDecl>(D);
6334 assert(VD->isFileVarDecl() && "Expected file scoped var");
6335
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006336 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6337 return false;
6338
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006339 // Structs that have non-trivial constructors or destructors are required.
6340
6341 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006342 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006343 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6344 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006345 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6346 RD->hasTrivialCopyConstructor() &&
6347 RD->hasTrivialMoveConstructor() &&
6348 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006349 return true;
6350 }
6351 }
6352
6353 GVALinkage L = GetGVALinkageForVariable(VD);
6354 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6355 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6356 return false;
6357 }
6358
6359 return true;
6360}
Charles Davis53c59df2010-08-16 03:33:14 +00006361
Charles Davis99202b32010-11-09 18:04:24 +00006362CallingConv ASTContext::getDefaultMethodCallConv() {
6363 // Pass through to the C++ ABI object
6364 return ABI->getDefaultMethodCallConv();
6365}
6366
Jay Foad39c79802011-01-12 09:06:06 +00006367bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006368 // Pass through to the C++ ABI object
6369 return ABI->isNearlyEmpty(RD);
6370}
6371
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006372MangleContext *ASTContext::createMangleContext() {
6373 switch (Target.getCXXABI()) {
6374 case CXXABI_ARM:
6375 case CXXABI_Itanium:
6376 return createItaniumMangleContext(*this, getDiagnostics());
6377 case CXXABI_Microsoft:
6378 return createMicrosoftMangleContext(*this, getDiagnostics());
6379 }
6380 assert(0 && "Unsupported ABI");
6381 return 0;
6382}
6383
Charles Davis53c59df2010-08-16 03:33:14 +00006384CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006385
6386size_t ASTContext::getSideTableAllocatedMemory() const {
6387 size_t bytes = 0;
6388 bytes += ASTRecordLayouts.getMemorySize();
6389 bytes += ObjCLayouts.getMemorySize();
6390 bytes += KeyFunctions.getMemorySize();
6391 bytes += ObjCImpls.getMemorySize();
6392 bytes += BlockVarCopyInits.getMemorySize();
6393 bytes += DeclAttrs.getMemorySize();
6394 bytes += InstantiatedFromStaticDataMember.getMemorySize();
6395 bytes += InstantiatedFromUsingDecl.getMemorySize();
6396 bytes += InstantiatedFromUsingShadowDecl.getMemorySize();
6397 bytes += InstantiatedFromUnnamedFieldDecl.getMemorySize();
6398 return bytes;
6399}
6400