blob: c844adea3e95673f7735f3478971986ff5db1601 [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_()),
John McCalld9dfe3a2011-06-30 08:33:18 +0000222 SubstTemplateTemplateParmPacks(this_()),
Argyrios Kyrtzidise862cbc2010-07-04 21:44:19 +0000223 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
224 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
John McCall31168b02011-06-15 23:02:42 +0000225 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0),
226 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
227 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
John McCall8cb7bdf2010-06-04 23:28:52 +0000228 NullTypeSourceInfo(QualType()),
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000229 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
230 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000231 Idents(idents), Selectors(sels),
Ted Kremenek6aead3a2010-05-10 20:40:08 +0000232 BuiltinInfo(builtins),
233 DeclarationNames(*this),
Argyrios Kyrtzidis440ea322010-10-28 09:29:35 +0000234 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenek520f47b2010-06-18 00:31:04 +0000235 LastSDM(0, 0),
John McCall147d0212011-02-22 22:38:33 +0000236 UniqueBlockByRefTypeID(0) {
David Chisnall9f57c292009-08-17 16:35:33 +0000237 ObjCIdRedefinitionType = QualType();
238 ObjCClassRedefinitionType = QualType();
Douglas Gregor5b11d492010-07-25 17:53:33 +0000239 ObjCSelRedefinitionType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000240 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000241 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000242 InitBuiltinTypes();
Daniel Dunbar221fa942008-08-11 04:54:23 +0000243}
244
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000245ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000246 // Release the DenseMaps associated with DeclContext objects.
247 // FIXME: Is this the ideal solution?
248 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000249
Douglas Gregor5b11d492010-07-25 17:53:33 +0000250 // Call all of the deallocation functions.
251 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
252 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000253
Douglas Gregor832940b2010-03-02 23:58:15 +0000254 // Release all of the memory associated with overridden C++ methods.
255 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
256 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
257 OM != OMEnd; ++OM)
258 OM->second.Destroy();
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000259
Ted Kremenek076baeb2010-06-08 23:00:58 +0000260 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000261 // because they can contain DenseMaps.
262 for (llvm::DenseMap<const ObjCContainerDecl*,
263 const ASTRecordLayout*>::iterator
264 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
265 // Increment in loop to prevent using deallocated memory.
266 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
267 R->Destroy(*this);
268
Ted Kremenek076baeb2010-06-08 23:00:58 +0000269 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
270 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
271 // Increment in loop to prevent using deallocated memory.
272 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
273 R->Destroy(*this);
274 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000275
276 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
277 AEnd = DeclAttrs.end();
278 A != AEnd; ++A)
279 A->second->~AttrVec();
280}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000281
Douglas Gregor1a809332010-05-23 18:26:36 +0000282void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
283 Deallocations.push_back(std::make_pair(Callback, Data));
284}
285
Mike Stump11289f42009-09-09 15:08:12 +0000286void
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000287ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
288 ExternalSource.reset(Source.take());
289}
290
Chris Lattner4eb445d2007-01-26 01:27:23 +0000291void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000292 llvm::errs() << "\n*** AST Context Stats:\n";
293 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000294
Douglas Gregora30d0462009-05-26 14:40:08 +0000295 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000296#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000297#define ABSTRACT_TYPE(Name, Parent)
298#include "clang/AST/TypeNodes.def"
299 0 // Extra
300 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000301
Chris Lattner4eb445d2007-01-26 01:27:23 +0000302 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
303 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000304 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000305 }
306
Douglas Gregora30d0462009-05-26 14:40:08 +0000307 unsigned Idx = 0;
308 unsigned TotalBytes = 0;
309#define TYPE(Name, Parent) \
310 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000311 llvm::errs() << " " << counts[Idx] << " " << #Name \
312 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000313 TotalBytes += counts[Idx] * sizeof(Name##Type); \
314 ++Idx;
315#define ABSTRACT_TYPE(Name, Parent)
316#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000317
Chandler Carruth3c147a72011-07-04 05:32:14 +0000318 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
319
Douglas Gregor7454c562010-07-02 20:37:36 +0000320 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000321 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
322 << NumImplicitDefaultConstructors
323 << " implicit default constructors created\n";
324 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
325 << NumImplicitCopyConstructors
326 << " implicit copy constructors created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000327 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000328 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
329 << NumImplicitMoveConstructors
330 << " implicit move constructors created\n";
331 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
332 << NumImplicitCopyAssignmentOperators
333 << " implicit copy assignment operators created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000334 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000335 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
336 << NumImplicitMoveAssignmentOperators
337 << " implicit move assignment operators created\n";
338 llvm::errs() << NumImplicitDestructorsDeclared << "/"
339 << NumImplicitDestructors
340 << " implicit destructors created\n";
341
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000342 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000343 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000344 ExternalSource->PrintStats();
345 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000346
Douglas Gregor5b11d492010-07-25 17:53:33 +0000347 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000348}
349
350
John McCall48f2d582009-10-23 23:03:21 +0000351void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000352 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000353 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000354 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000355}
356
Chris Lattner970e54e2006-11-12 00:37:36 +0000357void ASTContext::InitBuiltinTypes() {
358 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000359
Chris Lattner970e54e2006-11-12 00:37:36 +0000360 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000361 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000362
Chris Lattner970e54e2006-11-12 00:37:36 +0000363 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000364 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000365 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000366 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000367 InitBuiltinType(CharTy, BuiltinType::Char_S);
368 else
369 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000370 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000371 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
372 InitBuiltinType(ShortTy, BuiltinType::Short);
373 InitBuiltinType(IntTy, BuiltinType::Int);
374 InitBuiltinType(LongTy, BuiltinType::Long);
375 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000376
Chris Lattner970e54e2006-11-12 00:37:36 +0000377 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000378 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
379 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
380 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
381 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
382 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000383
Chris Lattner970e54e2006-11-12 00:37:36 +0000384 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000385 InitBuiltinType(FloatTy, BuiltinType::Float);
386 InitBuiltinType(DoubleTy, BuiltinType::Double);
387 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000388
Chris Lattnerf122cef2009-04-30 02:43:43 +0000389 // GNU extension, 128-bit integers.
390 InitBuiltinType(Int128Ty, BuiltinType::Int128);
391 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
392
Chris Lattnerad3467e2010-12-25 23:25:43 +0000393 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000394 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000395 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
396 else // -fshort-wchar makes wchar_t be unsigned.
397 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
398 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000399 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000400
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000401 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
402 InitBuiltinType(Char16Ty, BuiltinType::Char16);
403 else // C99
404 Char16Ty = getFromTargetType(Target.getChar16Type());
405
406 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
407 InitBuiltinType(Char32Ty, BuiltinType::Char32);
408 else // C99
409 Char32Ty = getFromTargetType(Target.getChar32Type());
410
Douglas Gregor4619e432008-12-05 23:32:09 +0000411 // Placeholder type for type-dependent expressions whose type is
412 // completely unknown. No code should ever check a type against
413 // DependentTy and users should never see it; however, it is here to
414 // help diagnose failures to properly check for type-dependent
415 // expressions.
416 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000417
John McCall36e7fe32010-10-12 00:20:44 +0000418 // Placeholder type for functions.
419 InitBuiltinType(OverloadTy, BuiltinType::Overload);
420
John McCall0009fcc2011-04-26 20:42:42 +0000421 // Placeholder type for bound members.
422 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
423
John McCall31996342011-04-07 08:22:57 +0000424 // "any" type; useful for debugger-like clients.
425 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
426
Chris Lattner970e54e2006-11-12 00:37:36 +0000427 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000428 FloatComplexTy = getComplexType(FloatTy);
429 DoubleComplexTy = getComplexType(DoubleTy);
430 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000431
Steve Naroff66e9f332007-10-15 14:41:52 +0000432 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000433
Steve Naroff1329fa02009-07-15 18:40:39 +0000434 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
435 ObjCIdTypedefType = QualType();
436 ObjCClassTypedefType = QualType();
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000437 ObjCSelTypedefType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000438
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000439 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000440 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
441 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000442 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff7cae42b2009-07-10 23:34:53 +0000443
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000444 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000445
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000446 // void * type
447 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000448
449 // nullptr type (C++0x 2.14.7)
450 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Chris Lattner970e54e2006-11-12 00:37:36 +0000451}
452
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000453Diagnostic &ASTContext::getDiagnostics() const {
454 return SourceMgr.getDiagnostics();
455}
456
Douglas Gregor561eceb2010-08-30 16:49:28 +0000457AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
458 AttrVec *&Result = DeclAttrs[D];
459 if (!Result) {
460 void *Mem = Allocate(sizeof(AttrVec));
461 Result = new (Mem) AttrVec;
462 }
463
464 return *Result;
465}
466
467/// \brief Erase the attributes corresponding to the given declaration.
468void ASTContext::eraseDeclAttrs(const Decl *D) {
469 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
470 if (Pos != DeclAttrs.end()) {
471 Pos->second->~AttrVec();
472 DeclAttrs.erase(Pos);
473 }
474}
475
Douglas Gregor86d142a2009-10-08 07:24:58 +0000476MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000477ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000478 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000479 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000480 = InstantiatedFromStaticDataMember.find(Var);
481 if (Pos == InstantiatedFromStaticDataMember.end())
482 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000483
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000484 return Pos->second;
485}
486
Mike Stump11289f42009-09-09 15:08:12 +0000487void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000488ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000489 TemplateSpecializationKind TSK,
490 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000491 assert(Inst->isStaticDataMember() && "Not a static data member");
492 assert(Tmpl->isStaticDataMember() && "Not a static data member");
493 assert(!InstantiatedFromStaticDataMember[Inst] &&
494 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000495 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000496 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000497}
498
John McCalle61f2ba2009-11-18 02:36:19 +0000499NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000500ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000501 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000502 = InstantiatedFromUsingDecl.find(UUD);
503 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000504 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000505
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000506 return Pos->second;
507}
508
509void
John McCallb96ec562009-12-04 22:46:56 +0000510ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
511 assert((isa<UsingDecl>(Pattern) ||
512 isa<UnresolvedUsingValueDecl>(Pattern) ||
513 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
514 "pattern decl is not a using decl");
515 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
516 InstantiatedFromUsingDecl[Inst] = Pattern;
517}
518
519UsingShadowDecl *
520ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
521 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
522 = InstantiatedFromUsingShadowDecl.find(Inst);
523 if (Pos == InstantiatedFromUsingShadowDecl.end())
524 return 0;
525
526 return Pos->second;
527}
528
529void
530ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
531 UsingShadowDecl *Pattern) {
532 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
533 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000534}
535
Anders Carlsson5da84842009-09-01 04:26:58 +0000536FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
537 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
538 = InstantiatedFromUnnamedFieldDecl.find(Field);
539 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
540 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000541
Anders Carlsson5da84842009-09-01 04:26:58 +0000542 return Pos->second;
543}
544
545void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
546 FieldDecl *Tmpl) {
547 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
548 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
549 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
550 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000551
Anders Carlsson5da84842009-09-01 04:26:58 +0000552 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
553}
554
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000555bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
556 const FieldDecl *LastFD) const {
557 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
558 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0);
559
560}
561
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000562bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
563 const FieldDecl *LastFD) const {
564 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Fariborz Jahanian759e4a12011-05-03 22:07:14 +0000565 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0 &&
566 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000567
568}
569
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000570bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
571 const FieldDecl *LastFD) const {
572 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
573 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() &&
574 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
575}
576
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000577bool ASTContext::NoneBitfieldFollowsBitfield(const FieldDecl *FD,
578 const FieldDecl *LastFD) const {
579 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
580 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
581}
582
583bool ASTContext::BitfieldFollowsNoneBitfield(const FieldDecl *FD,
584 const FieldDecl *LastFD) const {
585 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
586 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
587}
588
Douglas Gregor832940b2010-03-02 23:58:15 +0000589ASTContext::overridden_cxx_method_iterator
590ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
591 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
592 = OverriddenMethods.find(Method);
593 if (Pos == OverriddenMethods.end())
594 return 0;
595
596 return Pos->second.begin();
597}
598
599ASTContext::overridden_cxx_method_iterator
600ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
601 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
602 = OverriddenMethods.find(Method);
603 if (Pos == OverriddenMethods.end())
604 return 0;
605
606 return Pos->second.end();
607}
608
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000609unsigned
610ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
611 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
612 = OverriddenMethods.find(Method);
613 if (Pos == OverriddenMethods.end())
614 return 0;
615
616 return Pos->second.size();
617}
618
Douglas Gregor832940b2010-03-02 23:58:15 +0000619void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
620 const CXXMethodDecl *Overridden) {
621 OverriddenMethods[Method].push_back(Overridden);
622}
623
Chris Lattner53cfe802007-07-18 17:52:12 +0000624//===----------------------------------------------------------------------===//
625// Type Sizing and Analysis
626//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000627
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000628/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
629/// scalar floating point type.
630const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000631 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000632 assert(BT && "Not a floating point type!");
633 switch (BT->getKind()) {
634 default: assert(0 && "Not a floating point type!");
635 case BuiltinType::Float: return Target.getFloatFormat();
636 case BuiltinType::Double: return Target.getDoubleFormat();
637 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
638 }
639}
640
Ken Dyck160146e2010-01-27 17:10:57 +0000641/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000642/// specified decl. Note that bitfields do not have a valid alignment, so
643/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000644/// If @p RefAsPointee, references are treated like their underlying type
645/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000646CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedman19a546c2009-02-22 02:56:25 +0000647 unsigned Align = Target.getCharWidth();
648
John McCall94268702010-10-08 18:24:19 +0000649 bool UseAlignAttrOnly = false;
650 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
651 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000652
John McCall94268702010-10-08 18:24:19 +0000653 // __attribute__((aligned)) can increase or decrease alignment
654 // *except* on a struct or struct member, where it only increases
655 // alignment unless 'packed' is also specified.
656 //
657 // It is an error for [[align]] to decrease alignment, so we can
658 // ignore that possibility; Sema should diagnose it.
659 if (isa<FieldDecl>(D)) {
660 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
661 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
662 } else {
663 UseAlignAttrOnly = true;
664 }
665 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000666 else if (isa<FieldDecl>(D))
667 UseAlignAttrOnly =
668 D->hasAttr<PackedAttr>() ||
669 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000670
John McCall4e819612011-01-20 07:57:12 +0000671 // If we're using the align attribute only, just ignore everything
672 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000673 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000674 // do nothing
675
John McCall94268702010-10-08 18:24:19 +0000676 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000677 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000678 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000679 if (RefAsPointee)
680 T = RT->getPointeeType();
681 else
682 T = getPointerType(RT->getPointeeType());
683 }
684 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000685 // Adjust alignments of declarations with array type by the
686 // large-array alignment on the target.
Rafael Espindolae971b9a2010-06-04 23:15:27 +0000687 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000688 const ArrayType *arrayType;
689 if (MinWidth && (arrayType = getAsArrayType(T))) {
690 if (isa<VariableArrayType>(arrayType))
691 Align = std::max(Align, Target.getLargeArrayAlign());
692 else if (isa<ConstantArrayType>(arrayType) &&
693 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
694 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000695
John McCall33ddac02011-01-19 10:06:00 +0000696 // Walk through any array types while we're at it.
697 T = getBaseElementType(arrayType);
698 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000699 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
700 }
John McCall4e819612011-01-20 07:57:12 +0000701
702 // Fields can be subject to extra alignment constraints, like if
703 // the field is packed, the struct is packed, or the struct has a
704 // a max-field-alignment constraint (#pragma pack). So calculate
705 // the actual alignment of the field within the struct, and then
706 // (as we're expected to) constrain that by the alignment of the type.
707 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
708 // So calculate the alignment of the field.
709 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
710
711 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000712 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000713
714 // Use the GCD of that and the offset within the record.
715 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
716 if (offset > 0) {
717 // Alignment is always a power of 2, so the GCD will be a power of 2,
718 // which means we get to do this crazy thing instead of Euclid's.
719 uint64_t lowBitOfOffset = offset & (~offset + 1);
720 if (lowBitOfOffset < fieldAlign)
721 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
722 }
723
724 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000725 }
Chris Lattner68061312009-01-24 21:53:27 +0000726 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000727
Ken Dyckcc56c542011-01-15 18:38:59 +0000728 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000729}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000730
John McCall87fe5d52010-05-20 01:18:31 +0000731std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000732ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000733 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000734 return std::make_pair(toCharUnitsFromBits(Info.first),
735 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000736}
737
738std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000739ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000740 return getTypeInfoInChars(T.getTypePtr());
741}
742
Chris Lattner983a8bb2007-07-13 22:13:22 +0000743/// getTypeSize - Return the size of the specified type, in bits. This method
744/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000745///
746/// FIXME: Pointers into different addr spaces could have different sizes and
747/// alignment requirements: getPointerInfo should take an AddrSpace, this
748/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000749std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000750ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000751 uint64_t Width=0;
752 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000753 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000754#define TYPE(Class, Base)
755#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000756#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000757#define DEPENDENT_TYPE(Class, Base) case Type::Class:
758#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000759 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000760 break;
761
Chris Lattner355332d2007-07-13 22:27:08 +0000762 case Type::FunctionNoProto:
763 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000764 // GCC extension: alignof(function) = 32 bits
765 Width = 0;
766 Align = 32;
767 break;
768
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000769 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000770 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000771 Width = 0;
772 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
773 break;
774
Steve Naroff5c131802007-08-30 01:06:46 +0000775 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000776 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000777
Chris Lattner37e05872008-03-05 18:54:05 +0000778 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000779 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000780 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000781 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000782 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000783 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000784 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000785 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000786 const VectorType *VT = cast<VectorType>(T);
787 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
788 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000789 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000790 // If the alignment is not a power of 2, round up to the next power of 2.
791 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000792 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000793 Align = llvm::NextPowerOf2(Align);
794 Width = llvm::RoundUpToAlignment(Width, Align);
795 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000796 break;
797 }
Chris Lattner647fb222007-07-18 18:26:58 +0000798
Chris Lattner7570e9c2008-03-08 08:52:55 +0000799 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000800 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner355332d2007-07-13 22:27:08 +0000801 default: assert(0 && "Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000802 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000803 // GCC extension: alignof(void) = 8 bits.
804 Width = 0;
805 Align = 8;
806 break;
807
Chris Lattner6a4f7452007-12-19 19:23:28 +0000808 case BuiltinType::Bool:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000809 Width = Target.getBoolWidth();
810 Align = Target.getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000811 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000812 case BuiltinType::Char_S:
813 case BuiltinType::Char_U:
814 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000815 case BuiltinType::SChar:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000816 Width = Target.getCharWidth();
817 Align = Target.getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000818 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000819 case BuiltinType::WChar_S:
820 case BuiltinType::WChar_U:
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000821 Width = Target.getWCharWidth();
822 Align = Target.getWCharAlign();
823 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000824 case BuiltinType::Char16:
825 Width = Target.getChar16Width();
826 Align = Target.getChar16Align();
827 break;
828 case BuiltinType::Char32:
829 Width = Target.getChar32Width();
830 Align = Target.getChar32Align();
831 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000832 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000833 case BuiltinType::Short:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000834 Width = Target.getShortWidth();
835 Align = Target.getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000836 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000837 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000838 case BuiltinType::Int:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000839 Width = Target.getIntWidth();
840 Align = Target.getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000841 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000842 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000843 case BuiltinType::Long:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000844 Width = Target.getLongWidth();
845 Align = Target.getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000846 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000847 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000848 case BuiltinType::LongLong:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000849 Width = Target.getLongLongWidth();
850 Align = Target.getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000851 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000852 case BuiltinType::Int128:
853 case BuiltinType::UInt128:
854 Width = 128;
855 Align = 128; // int128_t is 128-bit aligned on all targets.
856 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000857 case BuiltinType::Float:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000858 Width = Target.getFloatWidth();
859 Align = Target.getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000860 break;
861 case BuiltinType::Double:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000862 Width = Target.getDoubleWidth();
863 Align = Target.getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000864 break;
865 case BuiltinType::LongDouble:
Chris Lattner7570e9c2008-03-08 08:52:55 +0000866 Width = Target.getLongDoubleWidth();
867 Align = Target.getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000868 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000869 case BuiltinType::NullPtr:
870 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
871 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000872 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000873 case BuiltinType::ObjCId:
874 case BuiltinType::ObjCClass:
875 case BuiltinType::ObjCSel:
876 Width = Target.getPointerWidth(0);
877 Align = Target.getPointerAlign(0);
878 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000879 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000880 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000881 case Type::ObjCObjectPointer:
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000882 Width = Target.getPointerWidth(0);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000883 Align = Target.getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000884 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000885 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000886 unsigned AS = getTargetAddressSpace(
887 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff921a45c2008-09-24 15:05:44 +0000888 Width = Target.getPointerWidth(AS);
889 Align = Target.getPointerAlign(AS);
890 break;
891 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000892 case Type::LValueReference:
893 case Type::RValueReference: {
894 // alignof and sizeof should never enter this code path here, so we go
895 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000896 unsigned AS = getTargetAddressSpace(
897 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000898 Width = Target.getPointerWidth(AS);
899 Align = Target.getPointerAlign(AS);
900 break;
901 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000902 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000903 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner4ba0cef2008-04-07 07:01:58 +0000904 Width = Target.getPointerWidth(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000905 Align = Target.getPointerAlign(AS);
906 break;
907 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000908 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000909 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000910 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000911 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000912 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000913 Align = PtrDiffInfo.second;
914 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000915 }
Chris Lattner647fb222007-07-18 18:26:58 +0000916 case Type::Complex: {
917 // Complex types have the same alignment as their elements, but twice the
918 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000919 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +0000920 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +0000921 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +0000922 Align = EltInfo.second;
923 break;
924 }
John McCall8b07ec22010-05-15 11:32:37 +0000925 case Type::ObjCObject:
926 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +0000927 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000928 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +0000929 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000930 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000931 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +0000932 break;
933 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000934 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000935 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000936 const TagType *TT = cast<TagType>(T);
937
938 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +0000939 Width = 8;
940 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +0000941 break;
942 }
Mike Stump11289f42009-09-09 15:08:12 +0000943
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000944 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +0000945 return getTypeInfo(ET->getDecl()->getIntegerType());
946
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000947 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +0000948 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +0000949 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000950 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +0000951 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000952 }
Douglas Gregordc572a32009-03-30 22:58:21 +0000953
Chris Lattner63d2b362009-10-22 05:17:15 +0000954 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +0000955 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
956 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +0000957
Richard Smith30482bc2011-02-20 03:19:35 +0000958 case Type::Auto: {
959 const AutoType *A = cast<AutoType>(T);
960 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +0000961 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +0000962 }
963
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000964 case Type::Paren:
965 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
966
Douglas Gregoref462e62009-04-30 17:32:17 +0000967 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +0000968 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +0000969 std::pair<uint64_t, unsigned> Info
970 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +0000971 // If the typedef has an aligned attribute on it, it overrides any computed
972 // alignment we have. This violates the GCC documentation (which says that
973 // attribute(aligned) can only round up) but matches its implementation.
974 if (unsigned AttrAlign = Typedef->getMaxAlignment())
975 Align = AttrAlign;
976 else
977 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +0000978 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +0000979 break;
Chris Lattner8b23c252008-04-06 22:05:18 +0000980 }
Douglas Gregoref462e62009-04-30 17:32:17 +0000981
982 case Type::TypeOfExpr:
983 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
984 .getTypePtr());
985
986 case Type::TypeOf:
987 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
988
Anders Carlsson81df7b82009-06-24 19:06:50 +0000989 case Type::Decltype:
990 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
991 .getTypePtr());
992
Alexis Hunte852b102011-05-24 22:41:36 +0000993 case Type::UnaryTransform:
994 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
995
Abramo Bagnara6150c882010-05-11 21:36:43 +0000996 case Type::Elaborated:
997 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +0000998
John McCall81904512011-01-06 01:58:22 +0000999 case Type::Attributed:
1000 return getTypeInfo(
1001 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1002
Richard Smith3f1b5d02011-05-05 21:57:07 +00001003 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001004 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001005 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001006 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1007 // A type alias template specialization may refer to a typedef with the
1008 // aligned attribute on it.
1009 if (TST->isTypeAlias())
1010 return getTypeInfo(TST->getAliasedType().getTypePtr());
1011 else
1012 return getTypeInfo(getCanonicalType(T));
1013 }
1014
Douglas Gregoref462e62009-04-30 17:32:17 +00001015 }
Mike Stump11289f42009-09-09 15:08:12 +00001016
Chris Lattner53cfe802007-07-18 17:52:12 +00001017 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001018 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001019}
1020
Ken Dyckcc56c542011-01-15 18:38:59 +00001021/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1022CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1023 return CharUnits::fromQuantity(BitSize / getCharWidth());
1024}
1025
Ken Dyckb0fcc592011-02-11 01:54:29 +00001026/// toBits - Convert a size in characters to a size in characters.
1027int64_t ASTContext::toBits(CharUnits CharSize) const {
1028 return CharSize.getQuantity() * getCharWidth();
1029}
1030
Ken Dyck8c89d592009-12-22 14:23:30 +00001031/// getTypeSizeInChars - Return the size of the specified type, in characters.
1032/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001033CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001034 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001035}
Jay Foad39c79802011-01-12 09:06:06 +00001036CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001037 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001038}
1039
Ken Dycka6046ab2010-01-26 17:25:18 +00001040/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001041/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001042CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001043 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001044}
Jay Foad39c79802011-01-12 09:06:06 +00001045CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001046 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001047}
1048
Chris Lattnera3402cd2009-01-27 18:08:34 +00001049/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1050/// type for the current target in bits. This can be different than the ABI
1051/// alignment in cases where it is beneficial for performance to overalign
1052/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001053unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001054 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001055
1056 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001057 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001058 T = CT->getElementType().getTypePtr();
1059 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1060 T->isSpecificBuiltinType(BuiltinType::LongLong))
1061 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1062
Chris Lattnera3402cd2009-01-27 18:08:34 +00001063 return ABIAlign;
1064}
1065
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001066/// ShallowCollectObjCIvars -
1067/// Collect all ivars, including those synthesized, in the current class.
1068///
1069void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad39c79802011-01-12 09:06:06 +00001070 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001071 // FIXME. This need be removed but there are two many places which
1072 // assume const-ness of ObjCInterfaceDecl
1073 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1074 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1075 Iv= Iv->getNextIvar())
1076 Ivars.push_back(Iv);
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001077}
1078
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001079/// DeepCollectObjCIvars -
1080/// This routine first collects all declared, but not synthesized, ivars in
1081/// super class and then collects all ivars, including those synthesized for
1082/// current class. This routine is used for implementation of current class
1083/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001084///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001085void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1086 bool leafClass,
Jay Foad39c79802011-01-12 09:06:06 +00001087 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001088 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1089 DeepCollectObjCIvars(SuperClass, false, Ivars);
1090 if (!leafClass) {
1091 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1092 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001093 Ivars.push_back(*I);
1094 }
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001095 else {
1096 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1097 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1098 Iv= Iv->getNextIvar())
1099 Ivars.push_back(Iv);
1100 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001101}
1102
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001103/// CollectInheritedProtocols - Collect all protocols in current class and
1104/// those inherited by it.
1105void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001106 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001107 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001108 // We can use protocol_iterator here instead of
1109 // all_referenced_protocol_iterator since we are walking all categories.
1110 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1111 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001112 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001113 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001114 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001115 PE = Proto->protocol_end(); P != PE; ++P) {
1116 Protocols.insert(*P);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001117 CollectInheritedProtocols(*P, Protocols);
1118 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001119 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001120
1121 // Categories of this Interface.
1122 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1123 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1124 CollectInheritedProtocols(CDeclChain, Protocols);
1125 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1126 while (SD) {
1127 CollectInheritedProtocols(SD, Protocols);
1128 SD = SD->getSuperClass();
1129 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001130 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001131 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001132 PE = OC->protocol_end(); P != PE; ++P) {
1133 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001134 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001135 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1136 PE = Proto->protocol_end(); P != PE; ++P)
1137 CollectInheritedProtocols(*P, Protocols);
1138 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001139 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001140 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1141 PE = OP->protocol_end(); P != PE; ++P) {
1142 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001143 Protocols.insert(Proto);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001144 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1145 PE = Proto->protocol_end(); P != PE; ++P)
1146 CollectInheritedProtocols(*P, Protocols);
1147 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001148 }
1149}
1150
Jay Foad39c79802011-01-12 09:06:06 +00001151unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001152 unsigned count = 0;
1153 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001154 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1155 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001156 count += CDecl->ivar_size();
1157
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001158 // Count ivar defined in this class's implementation. This
1159 // includes synthesized ivars.
1160 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001161 count += ImplDecl->ivar_size();
1162
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001163 return count;
1164}
1165
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001166/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1167ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1168 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1169 I = ObjCImpls.find(D);
1170 if (I != ObjCImpls.end())
1171 return cast<ObjCImplementationDecl>(I->second);
1172 return 0;
1173}
1174/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1175ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1176 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1177 I = ObjCImpls.find(D);
1178 if (I != ObjCImpls.end())
1179 return cast<ObjCCategoryImplDecl>(I->second);
1180 return 0;
1181}
1182
1183/// \brief Set the implementation of ObjCInterfaceDecl.
1184void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1185 ObjCImplementationDecl *ImplD) {
1186 assert(IFaceD && ImplD && "Passed null params");
1187 ObjCImpls[IFaceD] = ImplD;
1188}
1189/// \brief Set the implementation of ObjCCategoryDecl.
1190void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1191 ObjCCategoryImplDecl *ImplD) {
1192 assert(CatD && ImplD && "Passed null params");
1193 ObjCImpls[CatD] = ImplD;
1194}
1195
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001196/// \brief Get the copy initialization expression of VarDecl,or NULL if
1197/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001198Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001199 assert(VD && "Passed null params");
1200 assert(VD->hasAttr<BlocksAttr>() &&
1201 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001202 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001203 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001204 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1205}
1206
1207/// \brief Set the copy inialization expression of a block var decl.
1208void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1209 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001210 assert(VD->hasAttr<BlocksAttr>() &&
1211 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001212 BlockVarCopyInits[VD] = Init;
1213}
1214
John McCallbcd03502009-12-07 02:54:59 +00001215/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001216///
John McCallbcd03502009-12-07 02:54:59 +00001217/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001218/// the TypeLoc wrappers.
1219///
1220/// \param T the type that will be the basis for type source info. This type
1221/// should refer to how the declarator was written in source code, not to
1222/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001223TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001224 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001225 if (!DataSize)
1226 DataSize = TypeLoc::getFullDataSizeForType(T);
1227 else
1228 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001229 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001230
John McCallbcd03502009-12-07 02:54:59 +00001231 TypeSourceInfo *TInfo =
1232 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1233 new (TInfo) TypeSourceInfo(T);
1234 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001235}
1236
John McCallbcd03502009-12-07 02:54:59 +00001237TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001238 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001239 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001240 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001241 return DI;
1242}
1243
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001244const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001245ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001246 return getObjCLayout(D, 0);
1247}
1248
1249const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001250ASTContext::getASTObjCImplementationLayout(
1251 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001252 return getObjCLayout(D->getClassInterface(), D);
1253}
1254
Chris Lattner983a8bb2007-07-13 22:13:22 +00001255//===----------------------------------------------------------------------===//
1256// Type creation/memoization methods
1257//===----------------------------------------------------------------------===//
1258
Jay Foad39c79802011-01-12 09:06:06 +00001259QualType
John McCall33ddac02011-01-19 10:06:00 +00001260ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1261 unsigned fastQuals = quals.getFastQualifiers();
1262 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001263
1264 // Check if we've already instantiated this type.
1265 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001266 ExtQuals::Profile(ID, baseType, quals);
1267 void *insertPos = 0;
1268 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1269 assert(eq->getQualifiers() == quals);
1270 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001271 }
1272
John McCall33ddac02011-01-19 10:06:00 +00001273 // If the base type is not canonical, make the appropriate canonical type.
1274 QualType canon;
1275 if (!baseType->isCanonicalUnqualified()) {
1276 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1277 canonSplit.second.addConsistentQualifiers(quals);
1278 canon = getExtQualType(canonSplit.first, canonSplit.second);
1279
1280 // Re-find the insert position.
1281 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1282 }
1283
1284 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1285 ExtQualNodes.InsertNode(eq, insertPos);
1286 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001287}
1288
Jay Foad39c79802011-01-12 09:06:06 +00001289QualType
1290ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001291 QualType CanT = getCanonicalType(T);
1292 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001293 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001294
John McCall8ccfcb52009-09-24 19:53:00 +00001295 // If we are composing extended qualifiers together, merge together
1296 // into one ExtQuals node.
1297 QualifierCollector Quals;
1298 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001299
John McCall8ccfcb52009-09-24 19:53:00 +00001300 // If this type already has an address space specified, it cannot get
1301 // another one.
1302 assert(!Quals.hasAddressSpace() &&
1303 "Type cannot be in multiple addr spaces!");
1304 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001305
John McCall8ccfcb52009-09-24 19:53:00 +00001306 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001307}
1308
Chris Lattnerd60183d2009-02-18 22:53:11 +00001309QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001310 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001311 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001312 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001313 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001314
John McCall53fa7142010-12-24 02:08:15 +00001315 if (const PointerType *ptr = T->getAs<PointerType>()) {
1316 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001317 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001318 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1319 return getPointerType(ResultType);
1320 }
1321 }
Mike Stump11289f42009-09-09 15:08:12 +00001322
John McCall8ccfcb52009-09-24 19:53:00 +00001323 // If we are composing extended qualifiers together, merge together
1324 // into one ExtQuals node.
1325 QualifierCollector Quals;
1326 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001327
John McCall8ccfcb52009-09-24 19:53:00 +00001328 // If this type already has an ObjCGC specified, it cannot get
1329 // another one.
1330 assert(!Quals.hasObjCGCAttr() &&
1331 "Type cannot have multiple ObjCGCs!");
1332 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001333
John McCall8ccfcb52009-09-24 19:53:00 +00001334 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001335}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001336
John McCall4f5019e2010-12-19 02:44:49 +00001337const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1338 FunctionType::ExtInfo Info) {
1339 if (T->getExtInfo() == Info)
1340 return T;
1341
1342 QualType Result;
1343 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1344 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1345 } else {
1346 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1347 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1348 EPI.ExtInfo = Info;
1349 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1350 FPT->getNumArgs(), EPI);
1351 }
1352
1353 return cast<FunctionType>(Result.getTypePtr());
1354}
1355
Chris Lattnerc6395932007-06-22 20:56:16 +00001356/// getComplexType - Return the uniqued reference to the type for a complex
1357/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001358QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001359 // Unique pointers, to guarantee there is only one pointer of a particular
1360 // structure.
1361 llvm::FoldingSetNodeID ID;
1362 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001363
Chris Lattnerc6395932007-06-22 20:56:16 +00001364 void *InsertPos = 0;
1365 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1366 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001367
Chris Lattnerc6395932007-06-22 20:56:16 +00001368 // If the pointee type isn't canonical, this won't be a canonical type either,
1369 // so fill in the canonical type field.
1370 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001371 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001372 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001373
Chris Lattnerc6395932007-06-22 20:56:16 +00001374 // Get the new insert position for the node we care about.
1375 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001376 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001377 }
John McCall90d1c2d2009-09-24 23:30:46 +00001378 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001379 Types.push_back(New);
1380 ComplexTypes.InsertNode(New, InsertPos);
1381 return QualType(New, 0);
1382}
1383
Chris Lattner970e54e2006-11-12 00:37:36 +00001384/// getPointerType - Return the uniqued reference to the type for a pointer to
1385/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001386QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001387 // Unique pointers, to guarantee there is only one pointer of a particular
1388 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001389 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001390 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001391
Chris Lattner67521df2007-01-27 01:29:36 +00001392 void *InsertPos = 0;
1393 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001394 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001395
Chris Lattner7ccecb92006-11-12 08:50:50 +00001396 // If the pointee type isn't canonical, this won't be a canonical type either,
1397 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001398 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001399 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001400 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001401
Chris Lattner67521df2007-01-27 01:29:36 +00001402 // Get the new insert position for the node we care about.
1403 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001404 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001405 }
John McCall90d1c2d2009-09-24 23:30:46 +00001406 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001407 Types.push_back(New);
1408 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001409 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001410}
1411
Mike Stump11289f42009-09-09 15:08:12 +00001412/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001413/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001414QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001415 assert(T->isFunctionType() && "block of function types only");
1416 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001417 // structure.
1418 llvm::FoldingSetNodeID ID;
1419 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001420
Steve Naroffec33ed92008-08-27 16:04:49 +00001421 void *InsertPos = 0;
1422 if (BlockPointerType *PT =
1423 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1424 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001425
1426 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001427 // type either so fill in the canonical type field.
1428 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001429 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001430 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001431
Steve Naroffec33ed92008-08-27 16:04:49 +00001432 // Get the new insert position for the node we care about.
1433 BlockPointerType *NewIP =
1434 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001435 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001436 }
John McCall90d1c2d2009-09-24 23:30:46 +00001437 BlockPointerType *New
1438 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001439 Types.push_back(New);
1440 BlockPointerTypes.InsertNode(New, InsertPos);
1441 return QualType(New, 0);
1442}
1443
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001444/// getLValueReferenceType - Return the uniqued reference to the type for an
1445/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001446QualType
1447ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001448 assert(getCanonicalType(T) != OverloadTy &&
1449 "Unresolved overloaded function type");
1450
Bill Wendling3708c182007-05-27 10:15:43 +00001451 // Unique pointers, to guarantee there is only one pointer of a particular
1452 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001453 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001454 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001455
1456 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001457 if (LValueReferenceType *RT =
1458 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001459 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001460
John McCallfc93cf92009-10-22 22:37:11 +00001461 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1462
Bill Wendling3708c182007-05-27 10:15:43 +00001463 // If the referencee type isn't canonical, this won't be a canonical type
1464 // either, so fill in the canonical type field.
1465 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001466 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1467 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1468 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001469
Bill Wendling3708c182007-05-27 10:15:43 +00001470 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001471 LValueReferenceType *NewIP =
1472 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001473 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001474 }
1475
John McCall90d1c2d2009-09-24 23:30:46 +00001476 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001477 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1478 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001479 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001480 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001481
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001482 return QualType(New, 0);
1483}
1484
1485/// getRValueReferenceType - Return the uniqued reference to the type for an
1486/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001487QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001488 // Unique pointers, to guarantee there is only one pointer of a particular
1489 // structure.
1490 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001491 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001492
1493 void *InsertPos = 0;
1494 if (RValueReferenceType *RT =
1495 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1496 return QualType(RT, 0);
1497
John McCallfc93cf92009-10-22 22:37:11 +00001498 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1499
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001500 // If the referencee type isn't canonical, this won't be a canonical type
1501 // either, so fill in the canonical type field.
1502 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001503 if (InnerRef || !T.isCanonical()) {
1504 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1505 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001506
1507 // Get the new insert position for the node we care about.
1508 RValueReferenceType *NewIP =
1509 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001510 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001511 }
1512
John McCall90d1c2d2009-09-24 23:30:46 +00001513 RValueReferenceType *New
1514 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001515 Types.push_back(New);
1516 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001517 return QualType(New, 0);
1518}
1519
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001520/// getMemberPointerType - Return the uniqued reference to the type for a
1521/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001522QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001523 // Unique pointers, to guarantee there is only one pointer of a particular
1524 // structure.
1525 llvm::FoldingSetNodeID ID;
1526 MemberPointerType::Profile(ID, T, Cls);
1527
1528 void *InsertPos = 0;
1529 if (MemberPointerType *PT =
1530 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1531 return QualType(PT, 0);
1532
1533 // If the pointee or class type isn't canonical, this won't be a canonical
1534 // type either, so fill in the canonical type field.
1535 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001536 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001537 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1538
1539 // Get the new insert position for the node we care about.
1540 MemberPointerType *NewIP =
1541 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001542 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001543 }
John McCall90d1c2d2009-09-24 23:30:46 +00001544 MemberPointerType *New
1545 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001546 Types.push_back(New);
1547 MemberPointerTypes.InsertNode(New, InsertPos);
1548 return QualType(New, 0);
1549}
1550
Mike Stump11289f42009-09-09 15:08:12 +00001551/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001552/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001553QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001554 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001555 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001556 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001557 assert((EltTy->isDependentType() ||
1558 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001559 "Constant array of VLAs is illegal!");
1560
Chris Lattnere2df3f92009-05-13 04:12:56 +00001561 // Convert the array size into a canonical width matching the pointer size for
1562 // the target.
1563 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001564 ArySize =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001565 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001566
Chris Lattner23b7eb62007-06-15 23:05:46 +00001567 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001568 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001569
Chris Lattner36f8e652007-01-27 08:31:04 +00001570 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001571 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001572 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001573 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001574
John McCall33ddac02011-01-19 10:06:00 +00001575 // If the element type isn't canonical or has qualifiers, this won't
1576 // be a canonical type either, so fill in the canonical type field.
1577 QualType Canon;
1578 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1579 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1580 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001581 ASM, IndexTypeQuals);
John McCall33ddac02011-01-19 10:06:00 +00001582 Canon = getQualifiedType(Canon, canonSplit.second);
1583
Chris Lattner36f8e652007-01-27 08:31:04 +00001584 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001585 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001586 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001587 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001588 }
Mike Stump11289f42009-09-09 15:08:12 +00001589
John McCall90d1c2d2009-09-24 23:30:46 +00001590 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001591 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001592 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001593 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001594 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001595}
1596
John McCall06549462011-01-18 08:40:38 +00001597/// getVariableArrayDecayedType - Turns the given type, which may be
1598/// variably-modified, into the corresponding type with all the known
1599/// sizes replaced with [*].
1600QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1601 // Vastly most common case.
1602 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001603
John McCall06549462011-01-18 08:40:38 +00001604 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001605
John McCall06549462011-01-18 08:40:38 +00001606 SplitQualType split = type.getSplitDesugaredType();
1607 const Type *ty = split.first;
1608 switch (ty->getTypeClass()) {
1609#define TYPE(Class, Base)
1610#define ABSTRACT_TYPE(Class, Base)
1611#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1612#include "clang/AST/TypeNodes.def"
1613 llvm_unreachable("didn't desugar past all non-canonical types?");
1614
1615 // These types should never be variably-modified.
1616 case Type::Builtin:
1617 case Type::Complex:
1618 case Type::Vector:
1619 case Type::ExtVector:
1620 case Type::DependentSizedExtVector:
1621 case Type::ObjCObject:
1622 case Type::ObjCInterface:
1623 case Type::ObjCObjectPointer:
1624 case Type::Record:
1625 case Type::Enum:
1626 case Type::UnresolvedUsing:
1627 case Type::TypeOfExpr:
1628 case Type::TypeOf:
1629 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001630 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001631 case Type::DependentName:
1632 case Type::InjectedClassName:
1633 case Type::TemplateSpecialization:
1634 case Type::DependentTemplateSpecialization:
1635 case Type::TemplateTypeParm:
1636 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001637 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001638 case Type::PackExpansion:
1639 llvm_unreachable("type should never be variably-modified");
1640
1641 // These types can be variably-modified but should never need to
1642 // further decay.
1643 case Type::FunctionNoProto:
1644 case Type::FunctionProto:
1645 case Type::BlockPointer:
1646 case Type::MemberPointer:
1647 return type;
1648
1649 // These types can be variably-modified. All these modifications
1650 // preserve structure except as noted by comments.
1651 // TODO: if we ever care about optimizing VLAs, there are no-op
1652 // optimizations available here.
1653 case Type::Pointer:
1654 result = getPointerType(getVariableArrayDecayedType(
1655 cast<PointerType>(ty)->getPointeeType()));
1656 break;
1657
1658 case Type::LValueReference: {
1659 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1660 result = getLValueReferenceType(
1661 getVariableArrayDecayedType(lv->getPointeeType()),
1662 lv->isSpelledAsLValue());
1663 break;
1664 }
1665
1666 case Type::RValueReference: {
1667 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1668 result = getRValueReferenceType(
1669 getVariableArrayDecayedType(lv->getPointeeType()));
1670 break;
1671 }
1672
1673 case Type::ConstantArray: {
1674 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1675 result = getConstantArrayType(
1676 getVariableArrayDecayedType(cat->getElementType()),
1677 cat->getSize(),
1678 cat->getSizeModifier(),
1679 cat->getIndexTypeCVRQualifiers());
1680 break;
1681 }
1682
1683 case Type::DependentSizedArray: {
1684 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1685 result = getDependentSizedArrayType(
1686 getVariableArrayDecayedType(dat->getElementType()),
1687 dat->getSizeExpr(),
1688 dat->getSizeModifier(),
1689 dat->getIndexTypeCVRQualifiers(),
1690 dat->getBracketsRange());
1691 break;
1692 }
1693
1694 // Turn incomplete types into [*] types.
1695 case Type::IncompleteArray: {
1696 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1697 result = getVariableArrayType(
1698 getVariableArrayDecayedType(iat->getElementType()),
1699 /*size*/ 0,
1700 ArrayType::Normal,
1701 iat->getIndexTypeCVRQualifiers(),
1702 SourceRange());
1703 break;
1704 }
1705
1706 // Turn VLA types into [*] types.
1707 case Type::VariableArray: {
1708 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1709 result = getVariableArrayType(
1710 getVariableArrayDecayedType(vat->getElementType()),
1711 /*size*/ 0,
1712 ArrayType::Star,
1713 vat->getIndexTypeCVRQualifiers(),
1714 vat->getBracketsRange());
1715 break;
1716 }
1717 }
1718
1719 // Apply the top-level qualifiers from the original.
1720 return getQualifiedType(result, split.second);
1721}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001722
Steve Naroffcadebd02007-08-30 18:14:25 +00001723/// getVariableArrayType - Returns a non-unique reference to the type for a
1724/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001725QualType ASTContext::getVariableArrayType(QualType EltTy,
1726 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001727 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001728 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001729 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001730 // Since we don't unique expressions, it isn't possible to unique VLA's
1731 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001732 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001733
John McCall33ddac02011-01-19 10:06:00 +00001734 // Be sure to pull qualifiers off the element type.
1735 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1736 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1737 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001738 IndexTypeQuals, Brackets);
John McCall33ddac02011-01-19 10:06:00 +00001739 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001740 }
1741
John McCall90d1c2d2009-09-24 23:30:46 +00001742 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001743 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001744
1745 VariableArrayTypes.push_back(New);
1746 Types.push_back(New);
1747 return QualType(New, 0);
1748}
1749
Douglas Gregor4619e432008-12-05 23:32:09 +00001750/// getDependentSizedArrayType - Returns a non-unique reference to
1751/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001752/// type.
John McCall33ddac02011-01-19 10:06:00 +00001753QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1754 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001755 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001756 unsigned elementTypeQuals,
1757 SourceRange brackets) const {
1758 assert((!numElements || numElements->isTypeDependent() ||
1759 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001760 "Size must be type- or value-dependent!");
1761
John McCall33ddac02011-01-19 10:06:00 +00001762 // Dependently-sized array types that do not have a specified number
1763 // of elements will have their sizes deduced from a dependent
1764 // initializer. We do no canonicalization here at all, which is okay
1765 // because they can't be used in most locations.
1766 if (!numElements) {
1767 DependentSizedArrayType *newType
1768 = new (*this, TypeAlignment)
1769 DependentSizedArrayType(*this, elementType, QualType(),
1770 numElements, ASM, elementTypeQuals,
1771 brackets);
1772 Types.push_back(newType);
1773 return QualType(newType, 0);
1774 }
1775
1776 // Otherwise, we actually build a new type every time, but we
1777 // also build a canonical type.
1778
1779 SplitQualType canonElementType = getCanonicalType(elementType).split();
1780
1781 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001782 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001783 DependentSizedArrayType::Profile(ID, *this,
1784 QualType(canonElementType.first, 0),
1785 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001786
John McCall33ddac02011-01-19 10:06:00 +00001787 // Look for an existing type with these properties.
1788 DependentSizedArrayType *canonTy =
1789 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001790
John McCall33ddac02011-01-19 10:06:00 +00001791 // If we don't have one, build one.
1792 if (!canonTy) {
1793 canonTy = new (*this, TypeAlignment)
1794 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1795 QualType(), numElements, ASM, elementTypeQuals,
1796 brackets);
1797 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1798 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001799 }
1800
John McCall33ddac02011-01-19 10:06:00 +00001801 // Apply qualifiers from the element type to the array.
1802 QualType canon = getQualifiedType(QualType(canonTy,0),
1803 canonElementType.second);
Mike Stump11289f42009-09-09 15:08:12 +00001804
John McCall33ddac02011-01-19 10:06:00 +00001805 // If we didn't need extra canonicalization for the element type,
1806 // then just use that as our result.
1807 if (QualType(canonElementType.first, 0) == elementType)
1808 return canon;
1809
1810 // Otherwise, we need to build a type which follows the spelling
1811 // of the element type.
1812 DependentSizedArrayType *sugaredType
1813 = new (*this, TypeAlignment)
1814 DependentSizedArrayType(*this, elementType, canon, numElements,
1815 ASM, elementTypeQuals, brackets);
1816 Types.push_back(sugaredType);
1817 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001818}
1819
John McCall33ddac02011-01-19 10:06:00 +00001820QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001821 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001822 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001823 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001824 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001825
John McCall33ddac02011-01-19 10:06:00 +00001826 void *insertPos = 0;
1827 if (IncompleteArrayType *iat =
1828 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1829 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001830
1831 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001832 // either, so fill in the canonical type field. We also have to pull
1833 // qualifiers off the element type.
1834 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001835
John McCall33ddac02011-01-19 10:06:00 +00001836 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1837 SplitQualType canonSplit = getCanonicalType(elementType).split();
1838 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1839 ASM, elementTypeQuals);
1840 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanbd258282008-02-15 18:16:39 +00001841
1842 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001843 IncompleteArrayType *existing =
1844 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1845 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001846 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001847
John McCall33ddac02011-01-19 10:06:00 +00001848 IncompleteArrayType *newType = new (*this, TypeAlignment)
1849 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001850
John McCall33ddac02011-01-19 10:06:00 +00001851 IncompleteArrayTypes.InsertNode(newType, insertPos);
1852 Types.push_back(newType);
1853 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001854}
1855
Steve Naroff91fcddb2007-07-18 18:00:27 +00001856/// getVectorType - Return the unique reference to a vector type of
1857/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001858QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001859 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001860 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001861
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001862 // Check if we've already instantiated a vector of this type.
1863 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001864 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001865
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001866 void *InsertPos = 0;
1867 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1868 return QualType(VTP, 0);
1869
1870 // If the element type isn't canonical, this won't be a canonical type either,
1871 // so fill in the canonical type field.
1872 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001873 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001874 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001875
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001876 // Get the new insert position for the node we care about.
1877 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001878 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001879 }
John McCall90d1c2d2009-09-24 23:30:46 +00001880 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001881 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001882 VectorTypes.InsertNode(New, InsertPos);
1883 Types.push_back(New);
1884 return QualType(New, 0);
1885}
1886
Nate Begemance4d7fc2008-04-18 23:10:10 +00001887/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00001888/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00001889QualType
1890ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00001891 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00001892
Steve Naroff91fcddb2007-07-18 18:00:27 +00001893 // Check if we've already instantiated a vector of this type.
1894 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00001895 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001896 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001897 void *InsertPos = 0;
1898 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1899 return QualType(VTP, 0);
1900
1901 // If the element type isn't canonical, this won't be a canonical type either,
1902 // so fill in the canonical type field.
1903 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001904 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00001905 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00001906
Steve Naroff91fcddb2007-07-18 18:00:27 +00001907 // Get the new insert position for the node we care about.
1908 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001909 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00001910 }
John McCall90d1c2d2009-09-24 23:30:46 +00001911 ExtVectorType *New = new (*this, TypeAlignment)
1912 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00001913 VectorTypes.InsertNode(New, InsertPos);
1914 Types.push_back(New);
1915 return QualType(New, 0);
1916}
1917
Jay Foad39c79802011-01-12 09:06:06 +00001918QualType
1919ASTContext::getDependentSizedExtVectorType(QualType vecType,
1920 Expr *SizeExpr,
1921 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00001922 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001923 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00001924 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001925
Douglas Gregor352169a2009-07-31 03:54:25 +00001926 void *InsertPos = 0;
1927 DependentSizedExtVectorType *Canon
1928 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1929 DependentSizedExtVectorType *New;
1930 if (Canon) {
1931 // We already have a canonical version of this array type; use it as
1932 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00001933 New = new (*this, TypeAlignment)
1934 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1935 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001936 } else {
1937 QualType CanonVecTy = getCanonicalType(vecType);
1938 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00001939 New = new (*this, TypeAlignment)
1940 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1941 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00001942
1943 DependentSizedExtVectorType *CanonCheck
1944 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1945 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1946 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00001947 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1948 } else {
1949 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1950 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00001951 New = new (*this, TypeAlignment)
1952 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00001953 }
1954 }
Mike Stump11289f42009-09-09 15:08:12 +00001955
Douglas Gregor758a8692009-06-17 21:51:59 +00001956 Types.push_back(New);
1957 return QualType(New, 0);
1958}
1959
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001960/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001961///
Jay Foad39c79802011-01-12 09:06:06 +00001962QualType
1963ASTContext::getFunctionNoProtoType(QualType ResultTy,
1964 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00001965 const CallingConv DefaultCC = Info.getCC();
1966 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1967 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001968 // Unique functions, to guarantee there is only one function of a particular
1969 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001970 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001971 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00001972
Chris Lattner47955de2007-01-27 08:37:20 +00001973 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001974 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001975 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001976 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001977
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001978 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00001979 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00001980 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001981 Canonical =
1982 getFunctionNoProtoType(getCanonicalType(ResultTy),
1983 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00001984
Chris Lattner47955de2007-01-27 08:37:20 +00001985 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001986 FunctionNoProtoType *NewIP =
1987 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001988 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00001989 }
Mike Stump11289f42009-09-09 15:08:12 +00001990
Roman Divacky65b88cd2011-03-01 17:40:53 +00001991 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00001992 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00001993 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00001994 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001995 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001996 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00001997}
1998
1999/// getFunctionType - Return a normal function type with a typed argument
2000/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002001QualType
2002ASTContext::getFunctionType(QualType ResultTy,
2003 const QualType *ArgArray, unsigned NumArgs,
2004 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002005 // Unique functions, to guarantee there is only one function of a particular
2006 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002007 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002008 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002009
2010 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002011 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002012 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002013 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002014
2015 // Determine whether the type being created is already canonical or not.
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002016 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002017 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002018 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002019 isCanonical = false;
2020
Roman Divacky65b88cd2011-03-01 17:40:53 +00002021 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2022 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2023 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002024
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002025 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002026 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002027 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002028 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002029 llvm::SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002030 CanonicalArgs.reserve(NumArgs);
2031 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002032 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002033
John McCalldb40c7f2010-12-14 08:05:40 +00002034 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002035 CanonicalEPI.ExceptionSpecType = EST_None;
2036 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002037 CanonicalEPI.ExtInfo
2038 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2039
Chris Lattner76a00cf2008-04-06 22:59:24 +00002040 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002041 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002042 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002043
Chris Lattnerfd4de792007-01-27 01:15:32 +00002044 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002045 FunctionProtoType *NewIP =
2046 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002047 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002048 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002049
John McCall31168b02011-06-15 23:02:42 +00002050 // FunctionProtoType objects are allocated with extra bytes after
2051 // them for three variable size arrays at the end:
2052 // - parameter types
2053 // - exception types
2054 // - consumed-arguments flags
2055 // Instead of the exception types, there could be a noexcept
2056 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002057 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002058 NumArgs * sizeof(QualType);
2059 if (EPI.ExceptionSpecType == EST_Dynamic)
2060 Size += EPI.NumExceptions * sizeof(QualType);
2061 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002062 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002063 }
John McCall31168b02011-06-15 23:02:42 +00002064 if (EPI.ConsumedArguments)
2065 Size += NumArgs * sizeof(bool);
2066
John McCalldb40c7f2010-12-14 08:05:40 +00002067 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002068 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2069 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002070 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002071 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002072 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002073 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002074}
Chris Lattneref51c202006-11-10 07:17:23 +00002075
John McCalle78aac42010-03-10 03:28:59 +00002076#ifndef NDEBUG
2077static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2078 if (!isa<CXXRecordDecl>(D)) return false;
2079 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2080 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2081 return true;
2082 if (RD->getDescribedClassTemplate() &&
2083 !isa<ClassTemplateSpecializationDecl>(RD))
2084 return true;
2085 return false;
2086}
2087#endif
2088
2089/// getInjectedClassNameType - Return the unique reference to the
2090/// injected class name type for the specified templated declaration.
2091QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002092 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002093 assert(NeedsInjectedClassNameType(Decl));
2094 if (Decl->TypeForDecl) {
2095 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00002096 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCalle78aac42010-03-10 03:28:59 +00002097 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2098 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2099 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2100 } else {
John McCall424cec92011-01-19 06:33:43 +00002101 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002102 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002103 Decl->TypeForDecl = newType;
2104 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002105 }
2106 return QualType(Decl->TypeForDecl, 0);
2107}
2108
Douglas Gregor83a586e2008-04-13 21:07:44 +00002109/// getTypeDeclType - Return the unique reference to the type for the
2110/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002111QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002112 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002113 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002114
Richard Smithdda56e42011-04-15 14:24:37 +00002115 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002116 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002117
John McCall96f0b5f2010-03-10 06:48:02 +00002118 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2119 "Template type parameter types are always available.");
2120
John McCall81e38502010-02-16 03:57:14 +00002121 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002122 assert(!Record->getPreviousDeclaration() &&
2123 "struct/union has previous declaration");
2124 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002125 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002126 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCall96f0b5f2010-03-10 06:48:02 +00002127 assert(!Enum->getPreviousDeclaration() &&
2128 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002129 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002130 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002131 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002132 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2133 Decl->TypeForDecl = newType;
2134 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002135 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002136 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002137
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002138 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002139}
2140
Chris Lattner32d920b2007-01-26 02:01:53 +00002141/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002142/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002143QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002144ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2145 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002146 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002147
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002148 if (Canonical.isNull())
2149 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002150 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002151 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002152 Decl->TypeForDecl = newType;
2153 Types.push_back(newType);
2154 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002155}
2156
Jay Foad39c79802011-01-12 09:06:06 +00002157QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002158 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2159
2160 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2161 if (PrevDecl->TypeForDecl)
2162 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2163
John McCall424cec92011-01-19 06:33:43 +00002164 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2165 Decl->TypeForDecl = newType;
2166 Types.push_back(newType);
2167 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002168}
2169
Jay Foad39c79802011-01-12 09:06:06 +00002170QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002171 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2172
2173 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2174 if (PrevDecl->TypeForDecl)
2175 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2176
John McCall424cec92011-01-19 06:33:43 +00002177 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2178 Decl->TypeForDecl = newType;
2179 Types.push_back(newType);
2180 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002181}
2182
John McCall81904512011-01-06 01:58:22 +00002183QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2184 QualType modifiedType,
2185 QualType equivalentType) {
2186 llvm::FoldingSetNodeID id;
2187 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2188
2189 void *insertPos = 0;
2190 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2191 if (type) return QualType(type, 0);
2192
2193 QualType canon = getCanonicalType(equivalentType);
2194 type = new (*this, TypeAlignment)
2195 AttributedType(canon, attrKind, modifiedType, equivalentType);
2196
2197 Types.push_back(type);
2198 AttributedTypes.InsertNode(type, insertPos);
2199
2200 return QualType(type, 0);
2201}
2202
2203
John McCallcebee162009-10-18 09:09:24 +00002204/// \brief Retrieve a substitution-result type.
2205QualType
2206ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002207 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002208 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002209 && "replacement types must always be canonical");
2210
2211 llvm::FoldingSetNodeID ID;
2212 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2213 void *InsertPos = 0;
2214 SubstTemplateTypeParmType *SubstParm
2215 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2216
2217 if (!SubstParm) {
2218 SubstParm = new (*this, TypeAlignment)
2219 SubstTemplateTypeParmType(Parm, Replacement);
2220 Types.push_back(SubstParm);
2221 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2222 }
2223
2224 return QualType(SubstParm, 0);
2225}
2226
Douglas Gregorada4b792011-01-14 02:55:32 +00002227/// \brief Retrieve a
2228QualType ASTContext::getSubstTemplateTypeParmPackType(
2229 const TemplateTypeParmType *Parm,
2230 const TemplateArgument &ArgPack) {
2231#ifndef NDEBUG
2232 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2233 PEnd = ArgPack.pack_end();
2234 P != PEnd; ++P) {
2235 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2236 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2237 }
2238#endif
2239
2240 llvm::FoldingSetNodeID ID;
2241 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2242 void *InsertPos = 0;
2243 if (SubstTemplateTypeParmPackType *SubstParm
2244 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2245 return QualType(SubstParm, 0);
2246
2247 QualType Canon;
2248 if (!Parm->isCanonicalUnqualified()) {
2249 Canon = getCanonicalType(QualType(Parm, 0));
2250 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2251 ArgPack);
2252 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2253 }
2254
2255 SubstTemplateTypeParmPackType *SubstParm
2256 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2257 ArgPack);
2258 Types.push_back(SubstParm);
2259 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2260 return QualType(SubstParm, 0);
2261}
2262
Douglas Gregoreff93e02009-02-05 23:33:38 +00002263/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002264/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002265/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002266QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002267 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002268 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002269 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002270 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002271 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002272 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002273 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2274
2275 if (TypeParm)
2276 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002277
Chandler Carruth08836322011-05-01 00:51:33 +00002278 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002279 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002280 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002281
2282 TemplateTypeParmType *TypeCheck
2283 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2284 assert(!TypeCheck && "Template type parameter canonical type broken");
2285 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002286 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002287 TypeParm = new (*this, TypeAlignment)
2288 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002289
2290 Types.push_back(TypeParm);
2291 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2292
2293 return QualType(TypeParm, 0);
2294}
2295
John McCalle78aac42010-03-10 03:28:59 +00002296TypeSourceInfo *
2297ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2298 SourceLocation NameLoc,
2299 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002300 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002301 assert(!Name.getAsDependentTemplateName() &&
2302 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002303 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002304
2305 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2306 TemplateSpecializationTypeLoc TL
2307 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2308 TL.setTemplateNameLoc(NameLoc);
2309 TL.setLAngleLoc(Args.getLAngleLoc());
2310 TL.setRAngleLoc(Args.getRAngleLoc());
2311 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2312 TL.setArgLocInfo(i, Args[i].getLocInfo());
2313 return DI;
2314}
2315
Mike Stump11289f42009-09-09 15:08:12 +00002316QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002317ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002318 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002319 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002320 assert(!Template.getAsDependentTemplateName() &&
2321 "No dependent template names here!");
2322
John McCall6b51f282009-11-23 01:53:49 +00002323 unsigned NumArgs = Args.size();
2324
John McCall0ad16662009-10-29 08:12:44 +00002325 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2326 ArgVec.reserve(NumArgs);
2327 for (unsigned i = 0; i != NumArgs; ++i)
2328 ArgVec.push_back(Args[i].getArgument());
2329
John McCall2408e322010-04-27 00:57:59 +00002330 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002331 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002332}
2333
2334QualType
2335ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002336 const TemplateArgument *Args,
2337 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002338 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002339 assert(!Template.getAsDependentTemplateName() &&
2340 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002341 // Look through qualified template names.
2342 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2343 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002344
Richard Smith3f1b5d02011-05-05 21:57:07 +00002345 bool isTypeAlias =
2346 Template.getAsTemplateDecl() &&
2347 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2348
2349 QualType CanonType;
2350 if (!Underlying.isNull())
2351 CanonType = getCanonicalType(Underlying);
2352 else {
2353 assert(!isTypeAlias &&
2354 "Underlying type for template alias must be computed by caller");
2355 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2356 NumArgs);
2357 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002358
Douglas Gregora8e02e72009-07-28 23:00:59 +00002359 // Allocate the (non-canonical) template specialization type, but don't
2360 // try to unique it: these types typically have location information that
2361 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002362 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2363 sizeof(TemplateArgument) * NumArgs +
2364 (isTypeAlias ? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002365 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002366 TemplateSpecializationType *Spec
John McCall773cc982010-06-11 11:07:21 +00002367 = new (Mem) TemplateSpecializationType(Template,
John McCall2408e322010-04-27 00:57:59 +00002368 Args, NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002369 CanonType,
2370 isTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002371
Douglas Gregor8bf42052009-02-09 18:46:07 +00002372 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002373 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002374}
2375
Mike Stump11289f42009-09-09 15:08:12 +00002376QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002377ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2378 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002379 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002380 assert(!Template.getAsDependentTemplateName() &&
2381 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002382 assert((!Template.getAsTemplateDecl() ||
2383 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2384 "Underlying type for template alias must be computed by caller");
2385
Douglas Gregore29139c2011-03-03 17:04:51 +00002386 // Look through qualified template names.
2387 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2388 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002389
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002390 // Build the canonical template specialization type.
2391 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2392 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2393 CanonArgs.reserve(NumArgs);
2394 for (unsigned I = 0; I != NumArgs; ++I)
2395 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2396
2397 // Determine whether this canonical template specialization type already
2398 // exists.
2399 llvm::FoldingSetNodeID ID;
2400 TemplateSpecializationType::Profile(ID, CanonTemplate,
2401 CanonArgs.data(), NumArgs, *this);
2402
2403 void *InsertPos = 0;
2404 TemplateSpecializationType *Spec
2405 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2406
2407 if (!Spec) {
2408 // Allocate a new canonical template specialization type.
2409 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2410 sizeof(TemplateArgument) * NumArgs),
2411 TypeAlignment);
2412 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2413 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002414 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002415 Types.push_back(Spec);
2416 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2417 }
2418
2419 assert(Spec->isDependentType() &&
2420 "Non-dependent template-id type must have a canonical type");
2421 return QualType(Spec, 0);
2422}
2423
2424QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002425ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2426 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002427 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002428 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002429 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002430
2431 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002432 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002433 if (T)
2434 return QualType(T, 0);
2435
Douglas Gregorc42075a2010-02-04 18:10:26 +00002436 QualType Canon = NamedType;
2437 if (!Canon.isCanonical()) {
2438 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002439 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2440 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002441 (void)CheckT;
2442 }
2443
Abramo Bagnara6150c882010-05-11 21:36:43 +00002444 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002445 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002446 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002447 return QualType(T, 0);
2448}
2449
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002450QualType
Jay Foad39c79802011-01-12 09:06:06 +00002451ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002452 llvm::FoldingSetNodeID ID;
2453 ParenType::Profile(ID, InnerType);
2454
2455 void *InsertPos = 0;
2456 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2457 if (T)
2458 return QualType(T, 0);
2459
2460 QualType Canon = InnerType;
2461 if (!Canon.isCanonical()) {
2462 Canon = getCanonicalType(InnerType);
2463 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2464 assert(!CheckT && "Paren canonical type broken");
2465 (void)CheckT;
2466 }
2467
2468 T = new (*this) ParenType(InnerType, Canon);
2469 Types.push_back(T);
2470 ParenTypes.InsertNode(T, InsertPos);
2471 return QualType(T, 0);
2472}
2473
Douglas Gregor02085352010-03-31 20:19:30 +00002474QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2475 NestedNameSpecifier *NNS,
2476 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002477 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002478 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2479
2480 if (Canon.isNull()) {
2481 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002482 ElaboratedTypeKeyword CanonKeyword = Keyword;
2483 if (Keyword == ETK_None)
2484 CanonKeyword = ETK_Typename;
2485
2486 if (CanonNNS != NNS || CanonKeyword != Keyword)
2487 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002488 }
2489
2490 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002491 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002492
2493 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002494 DependentNameType *T
2495 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002496 if (T)
2497 return QualType(T, 0);
2498
Douglas Gregor02085352010-03-31 20:19:30 +00002499 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002500 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002501 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002502 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002503}
2504
Mike Stump11289f42009-09-09 15:08:12 +00002505QualType
John McCallc392f372010-06-11 00:33:02 +00002506ASTContext::getDependentTemplateSpecializationType(
2507 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002508 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002509 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002510 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002511 // TODO: avoid this copy
2512 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2513 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2514 ArgCopy.push_back(Args[I].getArgument());
2515 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2516 ArgCopy.size(),
2517 ArgCopy.data());
2518}
2519
2520QualType
2521ASTContext::getDependentTemplateSpecializationType(
2522 ElaboratedTypeKeyword Keyword,
2523 NestedNameSpecifier *NNS,
2524 const IdentifierInfo *Name,
2525 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002526 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002527 assert((!NNS || NNS->isDependent()) &&
2528 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002529
Douglas Gregorc42075a2010-02-04 18:10:26 +00002530 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002531 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2532 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002533
2534 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002535 DependentTemplateSpecializationType *T
2536 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002537 if (T)
2538 return QualType(T, 0);
2539
John McCallc392f372010-06-11 00:33:02 +00002540 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002541
John McCallc392f372010-06-11 00:33:02 +00002542 ElaboratedTypeKeyword CanonKeyword = Keyword;
2543 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2544
2545 bool AnyNonCanonArgs = false;
2546 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2547 for (unsigned I = 0; I != NumArgs; ++I) {
2548 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2549 if (!CanonArgs[I].structurallyEquals(Args[I]))
2550 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002551 }
2552
John McCallc392f372010-06-11 00:33:02 +00002553 QualType Canon;
2554 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2555 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2556 Name, NumArgs,
2557 CanonArgs.data());
2558
2559 // Find the insert position again.
2560 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2561 }
2562
2563 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2564 sizeof(TemplateArgument) * NumArgs),
2565 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002566 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002567 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002568 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002569 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002570 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002571}
2572
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002573QualType ASTContext::getPackExpansionType(QualType Pattern,
2574 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002575 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002576 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002577
2578 assert(Pattern->containsUnexpandedParameterPack() &&
2579 "Pack expansions must expand one or more parameter packs");
2580 void *InsertPos = 0;
2581 PackExpansionType *T
2582 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2583 if (T)
2584 return QualType(T, 0);
2585
2586 QualType Canon;
2587 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002588 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002589
2590 // Find the insert position again.
2591 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2592 }
2593
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002594 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002595 Types.push_back(T);
2596 PackExpansionTypes.InsertNode(T, InsertPos);
2597 return QualType(T, 0);
2598}
2599
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002600/// CmpProtocolNames - Comparison predicate for sorting protocols
2601/// alphabetically.
2602static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2603 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002604 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002605}
2606
John McCall8b07ec22010-05-15 11:32:37 +00002607static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002608 unsigned NumProtocols) {
2609 if (NumProtocols == 0) return true;
2610
2611 for (unsigned i = 1; i != NumProtocols; ++i)
2612 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2613 return false;
2614 return true;
2615}
2616
2617static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002618 unsigned &NumProtocols) {
2619 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002620
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002621 // Sort protocols, keyed by name.
2622 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2623
2624 // Remove duplicates.
2625 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2626 NumProtocols = ProtocolsEnd-Protocols;
2627}
2628
John McCall8b07ec22010-05-15 11:32:37 +00002629QualType ASTContext::getObjCObjectType(QualType BaseType,
2630 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002631 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002632 // If the base type is an interface and there aren't any protocols
2633 // to add, then the interface type will do just fine.
2634 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2635 return BaseType;
2636
2637 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002638 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002639 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002640 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002641 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2642 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002643
John McCall8b07ec22010-05-15 11:32:37 +00002644 // Build the canonical type, which has the canonical base type and
2645 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002646 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002647 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2648 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2649 if (!ProtocolsSorted) {
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002650 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2651 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002652 unsigned UniqueCount = NumProtocols;
2653
John McCallfc93cf92009-10-22 22:37:11 +00002654 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002655 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2656 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002657 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002658 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2659 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002660 }
2661
2662 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002663 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2664 }
2665
2666 unsigned Size = sizeof(ObjCObjectTypeImpl);
2667 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2668 void *Mem = Allocate(Size, TypeAlignment);
2669 ObjCObjectTypeImpl *T =
2670 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2671
2672 Types.push_back(T);
2673 ObjCObjectTypes.InsertNode(T, InsertPos);
2674 return QualType(T, 0);
2675}
2676
2677/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2678/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002679QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002680 llvm::FoldingSetNodeID ID;
2681 ObjCObjectPointerType::Profile(ID, ObjectT);
2682
2683 void *InsertPos = 0;
2684 if (ObjCObjectPointerType *QT =
2685 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2686 return QualType(QT, 0);
2687
2688 // Find the canonical object type.
2689 QualType Canonical;
2690 if (!ObjectT.isCanonical()) {
2691 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2692
2693 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002694 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2695 }
2696
Douglas Gregorf85bee62010-02-08 22:59:26 +00002697 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002698 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2699 ObjCObjectPointerType *QType =
2700 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002701
Steve Narofffb4330f2009-06-17 22:40:22 +00002702 Types.push_back(QType);
2703 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002704 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002705}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002706
Douglas Gregor1c283312010-08-11 12:19:30 +00002707/// getObjCInterfaceType - Return the unique reference to the type for the
2708/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad39c79802011-01-12 09:06:06 +00002709QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002710 if (Decl->TypeForDecl)
2711 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002712
Douglas Gregor1c283312010-08-11 12:19:30 +00002713 // FIXME: redeclarations?
2714 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2715 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2716 Decl->TypeForDecl = T;
2717 Types.push_back(T);
2718 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002719}
2720
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002721/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2722/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002723/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002724/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002725/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002726QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002727 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002728 if (tofExpr->isTypeDependent()) {
2729 llvm::FoldingSetNodeID ID;
2730 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002731
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002732 void *InsertPos = 0;
2733 DependentTypeOfExprType *Canon
2734 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2735 if (Canon) {
2736 // We already have a "canonical" version of an identical, dependent
2737 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002738 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002739 QualType((TypeOfExprType*)Canon, 0));
2740 }
2741 else {
2742 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002743 Canon
2744 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002745 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2746 toe = Canon;
2747 }
2748 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002749 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002750 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002751 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002752 Types.push_back(toe);
2753 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002754}
2755
Steve Naroffa773cd52007-08-01 18:02:17 +00002756/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2757/// TypeOfType AST's. The only motivation to unique these nodes would be
2758/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002759/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002760/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002761QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002762 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002763 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002764 Types.push_back(tot);
2765 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002766}
2767
Anders Carlssonad6bd352009-06-24 21:24:56 +00002768/// getDecltypeForExpr - Given an expr, will return the decltype for that
2769/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad39c79802011-01-12 09:06:06 +00002770static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlsson7d209572009-06-25 15:00:34 +00002771 if (e->isTypeDependent())
2772 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002773
Anders Carlssonad6bd352009-06-24 21:24:56 +00002774 // If e is an id expression or a class member access, decltype(e) is defined
2775 // as the type of the entity named by e.
2776 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2777 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2778 return VD->getType();
2779 }
2780 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2781 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2782 return FD->getType();
2783 }
2784 // If e is a function call or an invocation of an overloaded operator,
2785 // (parentheses around e are ignored), decltype(e) is defined as the
2786 // return type of that function.
2787 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2788 return CE->getCallReturnType();
Mike Stump11289f42009-09-09 15:08:12 +00002789
Anders Carlssonad6bd352009-06-24 21:24:56 +00002790 QualType T = e->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002791
2792 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlssonad6bd352009-06-24 21:24:56 +00002793 // defined as T&, otherwise decltype(e) is defined as T.
John McCall086a4642010-11-24 05:12:34 +00002794 if (e->isLValue())
Anders Carlssonad6bd352009-06-24 21:24:56 +00002795 T = Context.getLValueReferenceType(T);
Mike Stump11289f42009-09-09 15:08:12 +00002796
Anders Carlssonad6bd352009-06-24 21:24:56 +00002797 return T;
2798}
2799
Anders Carlsson81df7b82009-06-24 19:06:50 +00002800/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2801/// DecltypeType AST's. The only motivation to unique these nodes would be
2802/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002803/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson81df7b82009-06-24 19:06:50 +00002804/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002805QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002806 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002807
2808 // C++0x [temp.type]p2:
2809 // If an expression e involves a template parameter, decltype(e) denotes a
2810 // unique dependent type. Two such decltype-specifiers refer to the same
2811 // type only if their expressions are equivalent (14.5.6.1).
2812 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002813 llvm::FoldingSetNodeID ID;
2814 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002815
Douglas Gregora21f6c32009-07-30 23:36:40 +00002816 void *InsertPos = 0;
2817 DependentDecltypeType *Canon
2818 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2819 if (Canon) {
2820 // We already have a "canonical" version of an equivalent, dependent
2821 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002822 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002823 QualType((DecltypeType*)Canon, 0));
2824 }
2825 else {
2826 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002827 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002828 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2829 dt = Canon;
2830 }
2831 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002832 QualType T = getDecltypeForExpr(e, *this);
John McCall90d1c2d2009-09-24 23:30:46 +00002833 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregorabd68132009-07-08 00:03:05 +00002834 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002835 Types.push_back(dt);
2836 return QualType(dt, 0);
2837}
2838
Alexis Hunte852b102011-05-24 22:41:36 +00002839/// getUnaryTransformationType - We don't unique these, since the memory
2840/// savings are minimal and these are rare.
2841QualType ASTContext::getUnaryTransformType(QualType BaseType,
2842 QualType UnderlyingType,
2843 UnaryTransformType::UTTKind Kind)
2844 const {
2845 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002846 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2847 Kind,
2848 UnderlyingType->isDependentType() ?
2849 QualType() : UnderlyingType);
Alexis Hunte852b102011-05-24 22:41:36 +00002850 Types.push_back(Ty);
2851 return QualType(Ty, 0);
2852}
2853
Richard Smithb2bc2e62011-02-21 20:05:19 +00002854/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002855QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002856 void *InsertPos = 0;
2857 if (!DeducedType.isNull()) {
2858 // Look in the folding set for an existing type.
2859 llvm::FoldingSetNodeID ID;
2860 AutoType::Profile(ID, DeducedType);
2861 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2862 return QualType(AT, 0);
2863 }
2864
2865 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2866 Types.push_back(AT);
2867 if (InsertPos)
2868 AutoTypes.InsertNode(AT, InsertPos);
2869 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002870}
2871
Richard Smith02e85f32011-04-14 22:09:26 +00002872/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2873QualType ASTContext::getAutoDeductType() const {
2874 if (AutoDeductTy.isNull())
2875 AutoDeductTy = getAutoType(QualType());
2876 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2877 return AutoDeductTy;
2878}
2879
2880/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2881QualType ASTContext::getAutoRRefDeductType() const {
2882 if (AutoRRefDeductTy.isNull())
2883 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2884 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2885 return AutoRRefDeductTy;
2886}
2887
Chris Lattnerfb072462007-01-23 05:45:31 +00002888/// getTagDeclType - Return the unique reference to the type for the
2889/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00002890QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00002891 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00002892 // FIXME: What is the design on getTagDeclType when it requires casting
2893 // away const? mutable?
2894 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00002895}
2896
Mike Stump11289f42009-09-09 15:08:12 +00002897/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2898/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2899/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00002900CanQualType ASTContext::getSizeType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002901 return getFromTargetType(Target.getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00002902}
Chris Lattnerfb072462007-01-23 05:45:31 +00002903
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00002904/// getSignedWCharType - Return the type of "signed wchar_t".
2905/// Used when in C++, as a GCC extension.
2906QualType ASTContext::getSignedWCharType() const {
2907 // FIXME: derive from "Target" ?
2908 return WCharTy;
2909}
2910
2911/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2912/// Used when in C++, as a GCC extension.
2913QualType ASTContext::getUnsignedWCharType() const {
2914 // FIXME: derive from "Target" ?
2915 return UnsignedIntTy;
2916}
2917
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002918/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2919/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2920QualType ASTContext::getPointerDiffType() const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00002921 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00002922}
2923
Chris Lattnera21ad802008-04-02 05:18:44 +00002924//===----------------------------------------------------------------------===//
2925// Type Operators
2926//===----------------------------------------------------------------------===//
2927
Jay Foad39c79802011-01-12 09:06:06 +00002928CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00002929 // Push qualifiers into arrays, and then discard any remaining
2930 // qualifiers.
2931 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002932 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00002933 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00002934 QualType Result;
2935 if (isa<ArrayType>(Ty)) {
2936 Result = getArrayDecayedType(QualType(Ty,0));
2937 } else if (isa<FunctionType>(Ty)) {
2938 Result = getPointerType(QualType(Ty, 0));
2939 } else {
2940 Result = QualType(Ty, 0);
2941 }
2942
2943 return CanQualType::CreateUnsafe(Result);
2944}
2945
John McCall6c9dd522011-01-18 07:41:22 +00002946QualType ASTContext::getUnqualifiedArrayType(QualType type,
2947 Qualifiers &quals) {
2948 SplitQualType splitType = type.getSplitUnqualifiedType();
2949
2950 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2951 // the unqualified desugared type and then drops it on the floor.
2952 // We then have to strip that sugar back off with
2953 // getUnqualifiedDesugaredType(), which is silly.
2954 const ArrayType *AT =
2955 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2956
2957 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002958 if (!AT) {
John McCall6c9dd522011-01-18 07:41:22 +00002959 quals = splitType.second;
2960 return QualType(splitType.first, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002961 }
2962
John McCall6c9dd522011-01-18 07:41:22 +00002963 // Otherwise, recurse on the array's element type.
2964 QualType elementType = AT->getElementType();
2965 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2966
2967 // If that didn't change the element type, AT has no qualifiers, so we
2968 // can just use the results in splitType.
2969 if (elementType == unqualElementType) {
2970 assert(quals.empty()); // from the recursive call
2971 quals = splitType.second;
2972 return QualType(splitType.first, 0);
2973 }
2974
2975 // Otherwise, add in the qualifiers from the outermost type, then
2976 // build the type back up.
2977 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002978
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002979 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002980 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002981 CAT->getSizeModifier(), 0);
2982 }
2983
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002984 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002985 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002986 }
2987
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002988 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00002989 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00002990 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00002991 VAT->getSizeModifier(),
2992 VAT->getIndexTypeCVRQualifiers(),
2993 VAT->getBracketsRange());
2994 }
2995
2996 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00002997 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00002998 DSAT->getSizeModifier(), 0,
2999 SourceRange());
3000}
3001
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003002/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3003/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3004/// they point to and return true. If T1 and T2 aren't pointer types
3005/// or pointer-to-member types, or if they are not similar at this
3006/// level, returns false and leaves T1 and T2 unchanged. Top-level
3007/// qualifiers on T1 and T2 are ignored. This function will typically
3008/// be called in a loop that successively "unwraps" pointer and
3009/// pointer-to-member types to compare them at each level.
3010bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3011 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3012 *T2PtrType = T2->getAs<PointerType>();
3013 if (T1PtrType && T2PtrType) {
3014 T1 = T1PtrType->getPointeeType();
3015 T2 = T2PtrType->getPointeeType();
3016 return true;
3017 }
3018
3019 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3020 *T2MPType = T2->getAs<MemberPointerType>();
3021 if (T1MPType && T2MPType &&
3022 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3023 QualType(T2MPType->getClass(), 0))) {
3024 T1 = T1MPType->getPointeeType();
3025 T2 = T2MPType->getPointeeType();
3026 return true;
3027 }
3028
3029 if (getLangOptions().ObjC1) {
3030 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3031 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3032 if (T1OPType && T2OPType) {
3033 T1 = T1OPType->getPointeeType();
3034 T2 = T2OPType->getPointeeType();
3035 return true;
3036 }
3037 }
3038
3039 // FIXME: Block pointers, too?
3040
3041 return false;
3042}
3043
Jay Foad39c79802011-01-12 09:06:06 +00003044DeclarationNameInfo
3045ASTContext::getNameForTemplate(TemplateName Name,
3046 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003047 switch (Name.getKind()) {
3048 case TemplateName::QualifiedTemplate:
3049 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003050 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003051 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3052 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003053
John McCalld9dfe3a2011-06-30 08:33:18 +00003054 case TemplateName::OverloadedTemplate: {
3055 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3056 // DNInfo work in progress: CHECKME: what about DNLoc?
3057 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3058 }
3059
3060 case TemplateName::DependentTemplate: {
3061 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003062 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003063 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003064 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3065 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003066 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003067 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3068 // DNInfo work in progress: FIXME: source locations?
3069 DeclarationNameLoc DNLoc;
3070 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3071 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3072 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003073 }
3074 }
3075
John McCalld9dfe3a2011-06-30 08:33:18 +00003076 case TemplateName::SubstTemplateTemplateParm: {
3077 SubstTemplateTemplateParmStorage *subst
3078 = Name.getAsSubstTemplateTemplateParm();
3079 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3080 NameLoc);
3081 }
3082
3083 case TemplateName::SubstTemplateTemplateParmPack: {
3084 SubstTemplateTemplateParmPackStorage *subst
3085 = Name.getAsSubstTemplateTemplateParmPack();
3086 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3087 NameLoc);
3088 }
3089 }
3090
3091 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003092}
3093
Jay Foad39c79802011-01-12 09:06:06 +00003094TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003095 switch (Name.getKind()) {
3096 case TemplateName::QualifiedTemplate:
3097 case TemplateName::Template: {
3098 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003099 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003100 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003101 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3102
3103 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003104 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003105 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003106
John McCalld9dfe3a2011-06-30 08:33:18 +00003107 case TemplateName::OverloadedTemplate:
3108 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003109
John McCalld9dfe3a2011-06-30 08:33:18 +00003110 case TemplateName::DependentTemplate: {
3111 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3112 assert(DTN && "Non-dependent template names must refer to template decls.");
3113 return DTN->CanonicalTemplateName;
3114 }
3115
3116 case TemplateName::SubstTemplateTemplateParm: {
3117 SubstTemplateTemplateParmStorage *subst
3118 = Name.getAsSubstTemplateTemplateParm();
3119 return getCanonicalTemplateName(subst->getReplacement());
3120 }
3121
3122 case TemplateName::SubstTemplateTemplateParmPack: {
3123 SubstTemplateTemplateParmPackStorage *subst
3124 = Name.getAsSubstTemplateTemplateParmPack();
3125 TemplateTemplateParmDecl *canonParameter
3126 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3127 TemplateArgument canonArgPack
3128 = getCanonicalTemplateArgument(subst->getArgumentPack());
3129 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3130 }
3131 }
3132
3133 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003134}
3135
Douglas Gregoradee3e32009-11-11 23:06:43 +00003136bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3137 X = getCanonicalTemplateName(X);
3138 Y = getCanonicalTemplateName(Y);
3139 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3140}
3141
Mike Stump11289f42009-09-09 15:08:12 +00003142TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003143ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003144 switch (Arg.getKind()) {
3145 case TemplateArgument::Null:
3146 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003147
Douglas Gregora8e02e72009-07-28 23:00:59 +00003148 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003149 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003150
Douglas Gregora8e02e72009-07-28 23:00:59 +00003151 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003152 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003153
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003154 case TemplateArgument::Template:
3155 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003156
3157 case TemplateArgument::TemplateExpansion:
3158 return TemplateArgument(getCanonicalTemplateName(
3159 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003160 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003161
Douglas Gregora8e02e72009-07-28 23:00:59 +00003162 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003163 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003164 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003165
Douglas Gregora8e02e72009-07-28 23:00:59 +00003166 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003167 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003168
Douglas Gregora8e02e72009-07-28 23:00:59 +00003169 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003170 if (Arg.pack_size() == 0)
3171 return Arg;
3172
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003173 TemplateArgument *CanonArgs
3174 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003175 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003176 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003177 AEnd = Arg.pack_end();
3178 A != AEnd; (void)++A, ++Idx)
3179 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003180
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003181 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003182 }
3183 }
3184
3185 // Silence GCC warning
3186 assert(false && "Unhandled template argument kind");
3187 return TemplateArgument();
3188}
3189
Douglas Gregor333489b2009-03-27 23:10:48 +00003190NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003191ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003192 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003193 return 0;
3194
3195 switch (NNS->getKind()) {
3196 case NestedNameSpecifier::Identifier:
3197 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003198 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003199 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3200 NNS->getAsIdentifier());
3201
3202 case NestedNameSpecifier::Namespace:
3203 // A namespace is canonical; build a nested-name-specifier with
3204 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003205 return NestedNameSpecifier::Create(*this, 0,
3206 NNS->getAsNamespace()->getOriginalNamespace());
3207
3208 case NestedNameSpecifier::NamespaceAlias:
3209 // A namespace is canonical; build a nested-name-specifier with
3210 // this namespace and no prefix.
3211 return NestedNameSpecifier::Create(*this, 0,
3212 NNS->getAsNamespaceAlias()->getNamespace()
3213 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003214
3215 case NestedNameSpecifier::TypeSpec:
3216 case NestedNameSpecifier::TypeSpecWithTemplate: {
3217 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003218
3219 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3220 // break it apart into its prefix and identifier, then reconsititute those
3221 // as the canonical nested-name-specifier. This is required to canonicalize
3222 // a dependent nested-name-specifier involving typedefs of dependent-name
3223 // types, e.g.,
3224 // typedef typename T::type T1;
3225 // typedef typename T1::type T2;
3226 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3227 NestedNameSpecifier *Prefix
3228 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3229 return NestedNameSpecifier::Create(*this, Prefix,
3230 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3231 }
3232
Douglas Gregorcc10cbf2010-11-04 00:14:23 +00003233 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor3ade5702010-11-04 00:09:33 +00003234 if (const DependentTemplateSpecializationType *DTST
3235 = T->getAs<DependentTemplateSpecializationType>()) {
3236 NestedNameSpecifier *Prefix
3237 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregor6e068012011-02-28 00:04:36 +00003238
3239 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3240 Prefix, DTST->getIdentifier(),
3241 DTST->getNumArgs(),
3242 DTST->getArgs());
Douglas Gregor3ade5702010-11-04 00:09:33 +00003243 T = getCanonicalType(T);
3244 }
3245
John McCall33ddac02011-01-19 10:06:00 +00003246 return NestedNameSpecifier::Create(*this, 0, false,
3247 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003248 }
3249
3250 case NestedNameSpecifier::Global:
3251 // The global specifier is canonical and unique.
3252 return NNS;
3253 }
3254
3255 // Required to silence a GCC warning
3256 return 0;
3257}
3258
Chris Lattner7adf0762008-08-04 07:31:14 +00003259
Jay Foad39c79802011-01-12 09:06:06 +00003260const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003261 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003262 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003263 // Handle the common positive case fast.
3264 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3265 return AT;
3266 }
Mike Stump11289f42009-09-09 15:08:12 +00003267
John McCall8ccfcb52009-09-24 19:53:00 +00003268 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003269 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003270 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003271
John McCall8ccfcb52009-09-24 19:53:00 +00003272 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003273 // implements C99 6.7.3p8: "If the specification of an array type includes
3274 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003275
Chris Lattner7adf0762008-08-04 07:31:14 +00003276 // If we get here, we either have type qualifiers on the type, or we have
3277 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003278 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003279
John McCall33ddac02011-01-19 10:06:00 +00003280 SplitQualType split = T.getSplitDesugaredType();
3281 Qualifiers qs = split.second;
Mike Stump11289f42009-09-09 15:08:12 +00003282
Chris Lattner7adf0762008-08-04 07:31:14 +00003283 // If we have a simple case, just return now.
John McCall33ddac02011-01-19 10:06:00 +00003284 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3285 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003286 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003287
Chris Lattner7adf0762008-08-04 07:31:14 +00003288 // Otherwise, we have an array and we have qualifiers on it. Push the
3289 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003290 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003291
Chris Lattner7adf0762008-08-04 07:31:14 +00003292 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3293 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3294 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003295 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003296 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3297 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3298 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003299 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003300
Mike Stump11289f42009-09-09 15:08:12 +00003301 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003302 = dyn_cast<DependentSizedArrayType>(ATy))
3303 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003304 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003305 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003306 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003307 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003308 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003309
Chris Lattner7adf0762008-08-04 07:31:14 +00003310 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003311 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003312 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003313 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003314 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003315 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003316}
3317
Douglas Gregor84280642011-07-12 04:42:08 +00003318QualType ASTContext::getAdjustedParameterType(QualType T) {
3319 // C99 6.7.5.3p7:
3320 // A declaration of a parameter as "array of type" shall be
3321 // adjusted to "qualified pointer to type", where the type
3322 // qualifiers (if any) are those specified within the [ and ] of
3323 // the array type derivation.
3324 if (T->isArrayType())
3325 return getArrayDecayedType(T);
3326
3327 // C99 6.7.5.3p8:
3328 // A declaration of a parameter as "function returning type"
3329 // shall be adjusted to "pointer to function returning type", as
3330 // in 6.3.2.1.
3331 if (T->isFunctionType())
3332 return getPointerType(T);
3333
3334 return T;
3335}
3336
3337QualType ASTContext::getSignatureParameterType(QualType T) {
3338 T = getVariableArrayDecayedType(T);
3339 T = getAdjustedParameterType(T);
3340 return T.getUnqualifiedType();
3341}
3342
Chris Lattnera21ad802008-04-02 05:18:44 +00003343/// getArrayDecayedType - Return the properly qualified result of decaying the
3344/// specified array type to a pointer. This operation is non-trivial when
3345/// handling typedefs etc. The canonical type of "T" must be an array type,
3346/// this returns a pointer to a properly qualified element of the array.
3347///
3348/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003349QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003350 // Get the element type with 'getAsArrayType' so that we don't lose any
3351 // typedefs in the element type of the array. This also handles propagation
3352 // of type qualifiers from the array type into the element type if present
3353 // (C99 6.7.3p8).
3354 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3355 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003356
Chris Lattner7adf0762008-08-04 07:31:14 +00003357 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003358
3359 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003360 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003361}
3362
John McCall33ddac02011-01-19 10:06:00 +00003363QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3364 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003365}
3366
John McCall33ddac02011-01-19 10:06:00 +00003367QualType ASTContext::getBaseElementType(QualType type) const {
3368 Qualifiers qs;
3369 while (true) {
3370 SplitQualType split = type.getSplitDesugaredType();
3371 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3372 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003373
John McCall33ddac02011-01-19 10:06:00 +00003374 type = array->getElementType();
3375 qs.addConsistentQualifiers(split.second);
3376 }
Mike Stump11289f42009-09-09 15:08:12 +00003377
John McCall33ddac02011-01-19 10:06:00 +00003378 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003379}
3380
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003381/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003382uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003383ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3384 uint64_t ElementCount = 1;
3385 do {
3386 ElementCount *= CA->getSize().getZExtValue();
3387 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3388 } while (CA);
3389 return ElementCount;
3390}
3391
Steve Naroff0af91202007-04-27 21:51:21 +00003392/// getFloatingRank - Return a relative rank for floating point types.
3393/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003394static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003395 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003396 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003397
John McCall9dd450b2009-09-21 23:43:11 +00003398 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3399 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003400 default: assert(0 && "getFloatingRank(): not a floating type");
Chris Lattnerc6395932007-06-22 20:56:16 +00003401 case BuiltinType::Float: return FloatRank;
3402 case BuiltinType::Double: return DoubleRank;
3403 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003404 }
3405}
3406
Mike Stump11289f42009-09-09 15:08:12 +00003407/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3408/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003409/// 'typeDomain' is a real floating point or complex type.
3410/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003411QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3412 QualType Domain) const {
3413 FloatingRank EltRank = getFloatingRank(Size);
3414 if (Domain->isComplexType()) {
3415 switch (EltRank) {
Steve Narofffc6ffa22007-08-27 01:41:48 +00003416 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Naroff9091ef72007-08-27 01:27:54 +00003417 case FloatRank: return FloatComplexTy;
3418 case DoubleRank: return DoubleComplexTy;
3419 case LongDoubleRank: return LongDoubleComplexTy;
3420 }
Steve Naroff0af91202007-04-27 21:51:21 +00003421 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003422
3423 assert(Domain->isRealFloatingType() && "Unknown domain!");
3424 switch (EltRank) {
3425 default: assert(0 && "getFloatingRank(): illegal value for rank");
3426 case FloatRank: return FloatTy;
3427 case DoubleRank: return DoubleTy;
3428 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003429 }
Steve Naroffe4718892007-04-27 18:30:00 +00003430}
3431
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003432/// getFloatingTypeOrder - Compare the rank of the two specified floating
3433/// point types, ignoring the domain of the type (i.e. 'double' ==
3434/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003435/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003436int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003437 FloatingRank LHSR = getFloatingRank(LHS);
3438 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003439
Chris Lattnerb90739d2008-04-06 23:38:49 +00003440 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003441 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003442 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003443 return 1;
3444 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003445}
3446
Chris Lattner76a00cf2008-04-06 22:59:24 +00003447/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3448/// routine will assert if passed a built-in type that isn't an integer or enum,
3449/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003450unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003451 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCall424cec92011-01-19 06:33:43 +00003452 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall56774992009-12-09 09:09:27 +00003453 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedman1efaaea2009-02-13 02:31:07 +00003454
Chris Lattnerad3467e2010-12-25 23:25:43 +00003455 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3456 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmanc131d3b2009-07-05 23:44:27 +00003457 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3458
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003459 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3460 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3461
3462 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3463 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3464
Chris Lattner76a00cf2008-04-06 22:59:24 +00003465 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003466 default: assert(0 && "getIntegerRank(): not a built-in integer");
3467 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003468 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003469 case BuiltinType::Char_S:
3470 case BuiltinType::Char_U:
3471 case BuiltinType::SChar:
3472 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003473 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003474 case BuiltinType::Short:
3475 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003476 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003477 case BuiltinType::Int:
3478 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003479 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003480 case BuiltinType::Long:
3481 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003482 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003483 case BuiltinType::LongLong:
3484 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003485 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003486 case BuiltinType::Int128:
3487 case BuiltinType::UInt128:
3488 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003489 }
3490}
3491
Eli Friedman629ffb92009-08-20 04:21:42 +00003492/// \brief Whether this is a promotable bitfield reference according
3493/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3494///
3495/// \returns the type this bit-field will promote to, or NULL if no
3496/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003497QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003498 if (E->isTypeDependent() || E->isValueDependent())
3499 return QualType();
3500
Eli Friedman629ffb92009-08-20 04:21:42 +00003501 FieldDecl *Field = E->getBitField();
3502 if (!Field)
3503 return QualType();
3504
3505 QualType FT = Field->getType();
3506
3507 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3508 uint64_t BitWidth = BitWidthAP.getZExtValue();
3509 uint64_t IntSize = getTypeSize(IntTy);
3510 // GCC extension compatibility: if the bit-field size is less than or equal
3511 // to the size of int, it gets promoted no matter what its type is.
3512 // For instance, unsigned long bf : 4 gets promoted to signed int.
3513 if (BitWidth < IntSize)
3514 return IntTy;
3515
3516 if (BitWidth == IntSize)
3517 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3518
3519 // Types bigger than int are not subject to promotions, and therefore act
3520 // like the base type.
3521 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3522 // is ridiculous.
3523 return QualType();
3524}
3525
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003526/// getPromotedIntegerType - Returns the type that Promotable will
3527/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3528/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003529QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003530 assert(!Promotable.isNull());
3531 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003532 if (const EnumType *ET = Promotable->getAs<EnumType>())
3533 return ET->getDecl()->getPromotionType();
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003534 if (Promotable->isSignedIntegerType())
3535 return IntTy;
3536 uint64_t PromotableSize = getTypeSize(Promotable);
3537 uint64_t IntSize = getTypeSize(IntTy);
3538 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3539 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3540}
3541
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003542/// \brief Recurses in pointer/array types until it finds an objc retainable
3543/// type and returns its ownership.
3544Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3545 while (!T.isNull()) {
3546 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3547 return T.getObjCLifetime();
3548 if (T->isArrayType())
3549 T = getBaseElementType(T);
3550 else if (const PointerType *PT = T->getAs<PointerType>())
3551 T = PT->getPointeeType();
3552 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003553 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003554 else
3555 break;
3556 }
3557
3558 return Qualifiers::OCL_None;
3559}
3560
Mike Stump11289f42009-09-09 15:08:12 +00003561/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003562/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003563/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003564int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003565 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3566 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003567 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003568
Chris Lattner76a00cf2008-04-06 22:59:24 +00003569 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3570 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003571
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003572 unsigned LHSRank = getIntegerRank(LHSC);
3573 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003574
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003575 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3576 if (LHSRank == RHSRank) return 0;
3577 return LHSRank > RHSRank ? 1 : -1;
3578 }
Mike Stump11289f42009-09-09 15:08:12 +00003579
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003580 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3581 if (LHSUnsigned) {
3582 // If the unsigned [LHS] type is larger, return it.
3583 if (LHSRank >= RHSRank)
3584 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003585
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003586 // If the signed type can represent all values of the unsigned type, it
3587 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003588 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003589 return -1;
3590 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003591
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003592 // If the unsigned [RHS] type is larger, return it.
3593 if (RHSRank >= LHSRank)
3594 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003595
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003596 // If the signed type can represent all values of the unsigned type, it
3597 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003598 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003599 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003600}
Anders Carlsson98f07902007-08-17 05:31:46 +00003601
Anders Carlsson6d417272009-11-14 21:45:58 +00003602static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003603CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3604 DeclContext *DC, IdentifierInfo *Id) {
3605 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003606 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003607 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003608 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003609 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003610}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003611
Mike Stump11289f42009-09-09 15:08:12 +00003612// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003613QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003614 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003615 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003616 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003617 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003618 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003619
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003620 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003621
Anders Carlsson98f07902007-08-17 05:31:46 +00003622 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003623 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003624 // int flags;
3625 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003626 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003627 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003628 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003629 FieldTypes[3] = LongTy;
3630
Anders Carlsson98f07902007-08-17 05:31:46 +00003631 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003632 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003633 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003634 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003635 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003636 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003637 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003638 /*Mutable=*/false,
3639 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003640 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003641 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003642 }
3643
Douglas Gregord5058122010-02-11 01:19:42 +00003644 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003645 }
Mike Stump11289f42009-09-09 15:08:12 +00003646
Anders Carlsson98f07902007-08-17 05:31:46 +00003647 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003648}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003649
Douglas Gregor512b0772009-04-23 22:29:11 +00003650void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003651 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003652 assert(Rec && "Invalid CFConstantStringType");
3653 CFConstantStringTypeDecl = Rec->getDecl();
3654}
3655
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003656// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003657QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003658 if (!NSConstantStringTypeDecl) {
3659 NSConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003660 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003661 &Idents.get("__builtin_NSString"));
3662 NSConstantStringTypeDecl->startDefinition();
3663
3664 QualType FieldTypes[3];
3665
3666 // const int *isa;
3667 FieldTypes[0] = getPointerType(IntTy.withConst());
3668 // const char *str;
3669 FieldTypes[1] = getPointerType(CharTy.withConst());
3670 // unsigned int length;
3671 FieldTypes[2] = UnsignedIntTy;
3672
3673 // Create fields
3674 for (unsigned i = 0; i < 3; ++i) {
3675 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003676 SourceLocation(),
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003677 SourceLocation(), 0,
3678 FieldTypes[i], /*TInfo=*/0,
3679 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003680 /*Mutable=*/false,
3681 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003682 Field->setAccess(AS_public);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00003683 NSConstantStringTypeDecl->addDecl(Field);
3684 }
3685
3686 NSConstantStringTypeDecl->completeDefinition();
3687 }
3688
3689 return getTagDeclType(NSConstantStringTypeDecl);
3690}
3691
3692void ASTContext::setNSConstantStringType(QualType T) {
3693 const RecordType *Rec = T->getAs<RecordType>();
3694 assert(Rec && "Invalid NSConstantStringType");
3695 NSConstantStringTypeDecl = Rec->getDecl();
3696}
3697
Jay Foad39c79802011-01-12 09:06:06 +00003698QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003699 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003700 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003701 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003702 &Idents.get("__objcFastEnumerationState"));
John McCallae580fe2010-02-05 01:33:36 +00003703 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003704
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003705 QualType FieldTypes[] = {
3706 UnsignedLongTy,
Steve Naroff1329fa02009-07-15 18:40:39 +00003707 getPointerType(ObjCIdTypedefType),
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003708 getPointerType(UnsignedLongTy),
3709 getConstantArrayType(UnsignedLongTy,
3710 llvm::APInt(32, 5), ArrayType::Normal, 0)
3711 };
Mike Stump11289f42009-09-09 15:08:12 +00003712
Douglas Gregor91f84212008-12-11 16:49:14 +00003713 for (size_t i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003714 FieldDecl *Field = FieldDecl::Create(*this,
3715 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003716 SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00003717 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003718 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003719 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003720 /*Mutable=*/false,
3721 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003722 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003723 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003724 }
Mike Stump11289f42009-09-09 15:08:12 +00003725
Douglas Gregord5058122010-02-11 01:19:42 +00003726 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003727 }
Mike Stump11289f42009-09-09 15:08:12 +00003728
Anders Carlssond89ba7d2008-08-30 19:34:46 +00003729 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3730}
3731
Jay Foad39c79802011-01-12 09:06:06 +00003732QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003733 if (BlockDescriptorType)
3734 return getTagDeclType(BlockDescriptorType);
3735
3736 RecordDecl *T;
3737 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003738 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003739 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003740 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003741
3742 QualType FieldTypes[] = {
3743 UnsignedLongTy,
3744 UnsignedLongTy,
3745 };
3746
3747 const char *FieldNames[] = {
3748 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003749 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003750 };
3751
3752 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003753 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003754 SourceLocation(),
3755 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003756 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003757 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003758 /*Mutable=*/false,
3759 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003760 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003761 T->addDecl(Field);
3762 }
3763
Douglas Gregord5058122010-02-11 01:19:42 +00003764 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003765
3766 BlockDescriptorType = T;
3767
3768 return getTagDeclType(BlockDescriptorType);
3769}
3770
3771void ASTContext::setBlockDescriptorType(QualType T) {
3772 const RecordType *Rec = T->getAs<RecordType>();
3773 assert(Rec && "Invalid BlockDescriptorType");
3774 BlockDescriptorType = Rec->getDecl();
3775}
3776
Jay Foad39c79802011-01-12 09:06:06 +00003777QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003778 if (BlockDescriptorExtendedType)
3779 return getTagDeclType(BlockDescriptorExtendedType);
3780
3781 RecordDecl *T;
3782 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003783 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003784 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003785 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003786
3787 QualType FieldTypes[] = {
3788 UnsignedLongTy,
3789 UnsignedLongTy,
3790 getPointerType(VoidPtrTy),
3791 getPointerType(VoidPtrTy)
3792 };
3793
3794 const char *FieldNames[] = {
3795 "reserved",
3796 "Size",
3797 "CopyFuncPtr",
3798 "DestroyFuncPtr"
3799 };
3800
3801 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003802 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003803 SourceLocation(),
3804 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003805 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003806 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003807 /*Mutable=*/false,
3808 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003809 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003810 T->addDecl(Field);
3811 }
3812
Douglas Gregord5058122010-02-11 01:19:42 +00003813 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003814
3815 BlockDescriptorExtendedType = T;
3816
3817 return getTagDeclType(BlockDescriptorExtendedType);
3818}
3819
3820void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3821 const RecordType *Rec = T->getAs<RecordType>();
3822 assert(Rec && "Invalid BlockDescriptorType");
3823 BlockDescriptorExtendedType = Rec->getDecl();
3824}
3825
Jay Foad39c79802011-01-12 09:06:06 +00003826bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003827 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003828 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003829 if (getLangOptions().CPlusPlus) {
3830 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3831 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003832 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003833
3834 }
3835 }
Mike Stump94967902009-10-21 18:16:27 +00003836 return false;
3837}
3838
Jay Foad39c79802011-01-12 09:06:06 +00003839QualType
3840ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003841 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003842 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003843 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003844 // unsigned int __flags;
3845 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003846 // void *__copy_helper; // as needed
3847 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003848 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003849 // } *
3850
Mike Stump94967902009-10-21 18:16:27 +00003851 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3852
3853 // FIXME: Move up
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003854 llvm::SmallString<36> Name;
3855 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3856 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003857 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003858 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003859 T->startDefinition();
3860 QualType Int32Ty = IntTy;
3861 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3862 QualType FieldTypes[] = {
3863 getPointerType(VoidPtrTy),
3864 getPointerType(getTagDeclType(T)),
3865 Int32Ty,
3866 Int32Ty,
3867 getPointerType(VoidPtrTy),
3868 getPointerType(VoidPtrTy),
3869 Ty
3870 };
3871
Daniel Dunbar56df9772010-08-17 22:39:59 +00003872 llvm::StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003873 "__isa",
3874 "__forwarding",
3875 "__flags",
3876 "__size",
3877 "__copy_helper",
3878 "__destroy_helper",
3879 DeclName,
3880 };
3881
3882 for (size_t i = 0; i < 7; ++i) {
3883 if (!HasCopyAndDispose && i >=4 && i <= 5)
3884 continue;
3885 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003886 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003887 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003888 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003889 /*BitWidth=*/0, /*Mutable=*/false,
3890 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003891 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003892 T->addDecl(Field);
3893 }
3894
Douglas Gregord5058122010-02-11 01:19:42 +00003895 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003896
3897 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003898}
3899
Douglas Gregor512b0772009-04-23 22:29:11 +00003900void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003901 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003902 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3903 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3904}
3905
Anders Carlsson18acd442007-10-29 06:33:42 +00003906// This returns true if a type has been typedefed to BOOL:
3907// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003908static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003909 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003910 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3911 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003912
Anders Carlssond8499822007-10-29 05:01:08 +00003913 return false;
3914}
3915
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003916/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003917/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003918CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00003919 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3920 return CharUnits::Zero();
3921
Ken Dyck40775002010-01-11 17:06:35 +00003922 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003923
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003924 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003925 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003926 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003927 // Treat arrays as pointers, since that's how they're passed in.
3928 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00003929 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00003930 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00003931}
3932
3933static inline
3934std::string charUnitsToString(const CharUnits &CU) {
3935 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003936}
3937
John McCall351762c2011-02-07 10:33:21 +00003938/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00003939/// declaration.
John McCall351762c2011-02-07 10:33:21 +00003940std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3941 std::string S;
3942
David Chisnall950a9512009-11-17 19:33:30 +00003943 const BlockDecl *Decl = Expr->getBlockDecl();
3944 QualType BlockTy =
3945 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3946 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00003947 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00003948 // Compute size of all parameters.
3949 // Start with computing size of a pointer in number of bytes.
3950 // FIXME: There might(should) be a better way of doing this computation!
3951 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00003952 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3953 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00003954 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00003955 E = Decl->param_end(); PI != E; ++PI) {
3956 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00003957 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00003958 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00003959 ParmOffset += sz;
3960 }
3961 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00003962 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00003963 // Block pointer and offset.
3964 S += "@?0";
3965 ParmOffset = PtrSize;
3966
3967 // Argument types.
3968 ParmOffset = PtrSize;
3969 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3970 Decl->param_end(); PI != E; ++PI) {
3971 ParmVarDecl *PVDecl = *PI;
3972 QualType PType = PVDecl->getOriginalType();
3973 if (const ArrayType *AT =
3974 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3975 // Use array's original type only if it has known number of
3976 // elements.
3977 if (!isa<ConstantArrayType>(AT))
3978 PType = PVDecl->getType();
3979 } else if (PType->isFunctionType())
3980 PType = PVDecl->getType();
3981 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00003982 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00003983 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00003984 }
John McCall351762c2011-02-07 10:33:21 +00003985
3986 return S;
David Chisnall950a9512009-11-17 19:33:30 +00003987}
3988
Douglas Gregora9d84932011-05-27 01:19:52 +00003989bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00003990 std::string& S) {
3991 // Encode result type.
3992 getObjCEncodingForType(Decl->getResultType(), S);
3993 CharUnits ParmOffset;
3994 // Compute size of all parameters.
3995 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3996 E = Decl->param_end(); PI != E; ++PI) {
3997 QualType PType = (*PI)->getType();
3998 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00003999 if (sz.isZero())
4000 return true;
4001
David Chisnall50e4eba2010-12-30 14:05:53 +00004002 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004003 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004004 ParmOffset += sz;
4005 }
4006 S += charUnitsToString(ParmOffset);
4007 ParmOffset = CharUnits::Zero();
4008
4009 // Argument types.
4010 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4011 E = Decl->param_end(); PI != E; ++PI) {
4012 ParmVarDecl *PVDecl = *PI;
4013 QualType PType = PVDecl->getOriginalType();
4014 if (const ArrayType *AT =
4015 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4016 // Use array's original type only if it has known number of
4017 // elements.
4018 if (!isa<ConstantArrayType>(AT))
4019 PType = PVDecl->getType();
4020 } else if (PType->isFunctionType())
4021 PType = PVDecl->getType();
4022 getObjCEncodingForType(PType, S);
4023 S += charUnitsToString(ParmOffset);
4024 ParmOffset += getObjCEncodingTypeSize(PType);
4025 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004026
4027 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004028}
4029
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004030/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004031/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004032bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00004033 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004034 // FIXME: This is not very efficient.
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004035 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004036 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004037 // Encode result type.
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004038 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004039 // Compute size of all parameters.
4040 // Start with computing size of a pointer in number of bytes.
4041 // FIXME: There might(should) be a better way of doing this computation!
4042 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004043 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004044 // The first two arguments (self and _cmd) are pointers; account for
4045 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004046 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00004047 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004048 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004049 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004050 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004051 if (sz.isZero())
4052 return true;
4053
Ken Dyck40775002010-01-11 17:06:35 +00004054 assert (sz.isPositive() &&
4055 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004056 ParmOffset += sz;
4057 }
Ken Dyck40775002010-01-11 17:06:35 +00004058 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004059 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004060 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004061
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004062 // Argument types.
4063 ParmOffset = 2 * PtrSize;
Chris Lattnera4997152009-02-20 18:43:26 +00004064 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004065 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004066 ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004067 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004068 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004069 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4070 // Use array's original type only if it has known number of
4071 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004072 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004073 PType = PVDecl->getType();
4074 } else if (PType->isFunctionType())
4075 PType = PVDecl->getType();
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004076 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004077 // 'in', 'inout', etc.
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004078 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004079 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004080 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004081 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004082 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004083
4084 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004085}
4086
Daniel Dunbar4932b362008-08-28 04:38:10 +00004087/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004088/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004089/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4090/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004091/// Property attributes are stored as a comma-delimited C string. The simple
4092/// attributes readonly and bycopy are encoded as single characters. The
4093/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4094/// encoded as single characters, followed by an identifier. Property types
4095/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004096/// these attributes are defined by the following enumeration:
4097/// @code
4098/// enum PropertyAttributes {
4099/// kPropertyReadOnly = 'R', // property is read-only.
4100/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4101/// kPropertyByref = '&', // property is a reference to the value last assigned
4102/// kPropertyDynamic = 'D', // property is dynamic
4103/// kPropertyGetter = 'G', // followed by getter selector name
4104/// kPropertySetter = 'S', // followed by setter selector name
4105/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4106/// kPropertyType = 't' // followed by old-style type encoding.
4107/// kPropertyWeak = 'W' // 'weak' property
4108/// kPropertyStrong = 'P' // property GC'able
4109/// kPropertyNonAtomic = 'N' // property non-atomic
4110/// };
4111/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004112void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004113 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004114 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004115 // Collect information from the property implementation decl(s).
4116 bool Dynamic = false;
4117 ObjCPropertyImplDecl *SynthesizePID = 0;
4118
4119 // FIXME: Duplicated code due to poor abstraction.
4120 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004121 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004122 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4123 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004124 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004125 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004126 ObjCPropertyImplDecl *PID = *i;
4127 if (PID->getPropertyDecl() == PD) {
4128 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4129 Dynamic = true;
4130 } else {
4131 SynthesizePID = PID;
4132 }
4133 }
4134 }
4135 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004136 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004137 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004138 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004139 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004140 ObjCPropertyImplDecl *PID = *i;
4141 if (PID->getPropertyDecl() == PD) {
4142 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4143 Dynamic = true;
4144 } else {
4145 SynthesizePID = PID;
4146 }
4147 }
Mike Stump11289f42009-09-09 15:08:12 +00004148 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004149 }
4150 }
4151
4152 // FIXME: This is not very efficient.
4153 S = "T";
4154
4155 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004156 // GCC has some special rules regarding encoding of properties which
4157 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004158 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004159 true /* outermost type */,
4160 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004161
4162 if (PD->isReadOnly()) {
4163 S += ",R";
4164 } else {
4165 switch (PD->getSetterKind()) {
4166 case ObjCPropertyDecl::Assign: break;
4167 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004168 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004169 }
4170 }
4171
4172 // It really isn't clear at all what this means, since properties
4173 // are "dynamic by default".
4174 if (Dynamic)
4175 S += ",D";
4176
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004177 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4178 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004179
Daniel Dunbar4932b362008-08-28 04:38:10 +00004180 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4181 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004182 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004183 }
4184
4185 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4186 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004187 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004188 }
4189
4190 if (SynthesizePID) {
4191 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4192 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004193 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004194 }
4195
4196 // FIXME: OBJCGC: weak & strong
4197}
4198
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004199/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004200/// Another legacy compatibility encoding: 32-bit longs are encoded as
4201/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004202/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4203///
4204void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004205 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004206 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004207 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004208 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004209 else
Jay Foad39c79802011-01-12 09:06:06 +00004210 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004211 PointeeTy = IntTy;
4212 }
4213 }
4214}
4215
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004216void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004217 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004218 // We follow the behavior of gcc, expanding structures which are
4219 // directly pointed to, and expanding embedded structures. Note that
4220 // these rules are sufficient to prevent recursive encoding of the
4221 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004222 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004223 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004224}
4225
David Chisnallb190a2c2010-06-04 01:10:52 +00004226static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4227 switch (T->getAs<BuiltinType>()->getKind()) {
4228 default: assert(0 && "Unhandled builtin type kind");
4229 case BuiltinType::Void: return 'v';
4230 case BuiltinType::Bool: return 'B';
4231 case BuiltinType::Char_U:
4232 case BuiltinType::UChar: return 'C';
4233 case BuiltinType::UShort: return 'S';
4234 case BuiltinType::UInt: return 'I';
4235 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004236 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004237 case BuiltinType::UInt128: return 'T';
4238 case BuiltinType::ULongLong: return 'Q';
4239 case BuiltinType::Char_S:
4240 case BuiltinType::SChar: return 'c';
4241 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004242 case BuiltinType::WChar_S:
4243 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004244 case BuiltinType::Int: return 'i';
4245 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004246 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004247 case BuiltinType::LongLong: return 'q';
4248 case BuiltinType::Int128: return 't';
4249 case BuiltinType::Float: return 'f';
4250 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004251 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004252 }
4253}
4254
Jay Foad39c79802011-01-12 09:06:06 +00004255static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004256 QualType T, const FieldDecl *FD) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004257 const Expr *E = FD->getBitWidth();
4258 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004259 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004260 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4261 // The GNU runtime requires more information; bitfields are encoded as b,
4262 // then the offset (in bits) of the first element, then the type of the
4263 // bitfield, then the size in bits. For example, in this structure:
4264 //
4265 // struct
4266 // {
4267 // int integer;
4268 // int flags:2;
4269 // };
4270 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4271 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4272 // information is not especially sensible, but we're stuck with it for
4273 // compatibility with GCC, although providing it breaks anything that
4274 // actually uses runtime introspection and wants to work on both runtimes...
4275 if (!Ctx->getLangOptions().NeXTRuntime) {
4276 const RecordDecl *RD = FD->getParent();
4277 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004278 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
David Chisnall6f0a7d22010-12-26 20:12:30 +00004279 if (T->isEnumeralType())
4280 S += 'i';
4281 else
Jay Foad39c79802011-01-12 09:06:06 +00004282 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004283 }
4284 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004285 S += llvm::utostr(N);
4286}
4287
Daniel Dunbar07d07852009-10-18 21:17:35 +00004288// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004289void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4290 bool ExpandPointedToStructures,
4291 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004292 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004293 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004294 bool EncodingProperty,
4295 bool StructField) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004296 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004297 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004298 return EncodeBitField(this, S, T, FD);
4299 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004300 return;
4301 }
Mike Stump11289f42009-09-09 15:08:12 +00004302
John McCall9dd450b2009-09-21 23:43:11 +00004303 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004304 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004305 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004306 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004307 return;
4308 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004309
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004310 // encoding for pointer or r3eference types.
4311 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004312 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004313 if (PT->isObjCSelType()) {
4314 S += ':';
4315 return;
4316 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004317 PointeeTy = PT->getPointeeType();
4318 }
4319 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4320 PointeeTy = RT->getPointeeType();
4321 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004322 bool isReadOnly = false;
4323 // For historical/compatibility reasons, the read-only qualifier of the
4324 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4325 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004326 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004327 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004328 if (OutermostType && T.isConstQualified()) {
4329 isReadOnly = true;
4330 S += 'r';
4331 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004332 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004333 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004334 while (P->getAs<PointerType>())
4335 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004336 if (P.isConstQualified()) {
4337 isReadOnly = true;
4338 S += 'r';
4339 }
4340 }
4341 if (isReadOnly) {
4342 // Another legacy compatibility encoding. Some ObjC qualifier and type
4343 // combinations need to be rearranged.
4344 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004345 if (llvm::StringRef(S).endswith("nr"))
4346 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004347 }
Mike Stump11289f42009-09-09 15:08:12 +00004348
Anders Carlssond8499822007-10-29 05:01:08 +00004349 if (PointeeTy->isCharType()) {
4350 // char pointer types should be encoded as '*' unless it is a
4351 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004352 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004353 S += '*';
4354 return;
4355 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004356 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004357 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4358 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4359 S += '#';
4360 return;
4361 }
4362 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4363 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4364 S += '@';
4365 return;
4366 }
4367 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004368 }
Anders Carlssond8499822007-10-29 05:01:08 +00004369 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004370 getLegacyIntegralTypeEncoding(PointeeTy);
4371
Mike Stump11289f42009-09-09 15:08:12 +00004372 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004373 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004374 return;
4375 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004376
Chris Lattnere7cabb92009-07-13 00:10:46 +00004377 if (const ArrayType *AT =
4378 // Ignore type qualifiers etc.
4379 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004380 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004381 // Incomplete arrays are encoded as a pointer to the array element.
4382 S += '^';
4383
Mike Stump11289f42009-09-09 15:08:12 +00004384 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004385 false, ExpandStructures, FD);
4386 } else {
4387 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004388
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004389 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4390 if (getTypeSize(CAT->getElementType()) == 0)
4391 S += '0';
4392 else
4393 S += llvm::utostr(CAT->getSize().getZExtValue());
4394 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004395 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004396 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4397 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004398 S += '0';
4399 }
Mike Stump11289f42009-09-09 15:08:12 +00004400
4401 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004402 false, ExpandStructures, FD);
4403 S += ']';
4404 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004405 return;
4406 }
Mike Stump11289f42009-09-09 15:08:12 +00004407
John McCall9dd450b2009-09-21 23:43:11 +00004408 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004409 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004410 return;
4411 }
Mike Stump11289f42009-09-09 15:08:12 +00004412
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004413 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004414 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004415 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004416 // Anonymous structures print as '?'
4417 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4418 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004419 if (ClassTemplateSpecializationDecl *Spec
4420 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4421 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4422 std::string TemplateArgsStr
4423 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004424 TemplateArgs.data(),
4425 TemplateArgs.size(),
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004426 (*this).PrintingPolicy);
4427
4428 S += TemplateArgsStr;
4429 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004430 } else {
4431 S += '?';
4432 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004433 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004434 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004435 if (!RDecl->isUnion()) {
4436 getObjCEncodingForStructureImpl(RDecl, S, FD);
4437 } else {
4438 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4439 FieldEnd = RDecl->field_end();
4440 Field != FieldEnd; ++Field) {
4441 if (FD) {
4442 S += '"';
4443 S += Field->getNameAsString();
4444 S += '"';
4445 }
Mike Stump11289f42009-09-09 15:08:12 +00004446
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004447 // Special case bit-fields.
4448 if (Field->isBitField()) {
4449 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4450 (*Field));
4451 } else {
4452 QualType qt = Field->getType();
4453 getLegacyIntegralTypeEncoding(qt);
4454 getObjCEncodingForTypeImpl(qt, S, false, true,
4455 FD, /*OutermostType*/false,
4456 /*EncodingProperty*/false,
4457 /*StructField*/true);
4458 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004459 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004460 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004461 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004462 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004463 return;
4464 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004465
Chris Lattnere7cabb92009-07-13 00:10:46 +00004466 if (T->isEnumeralType()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004467 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004468 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004469 else
4470 S += 'i';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004471 return;
4472 }
Mike Stump11289f42009-09-09 15:08:12 +00004473
Chris Lattnere7cabb92009-07-13 00:10:46 +00004474 if (T->isBlockPointerType()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004475 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnere7cabb92009-07-13 00:10:46 +00004476 return;
4477 }
Mike Stump11289f42009-09-09 15:08:12 +00004478
John McCall8b07ec22010-05-15 11:32:37 +00004479 // Ignore protocol qualifiers when mangling at this level.
4480 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4481 T = OT->getBaseType();
4482
John McCall8ccfcb52009-09-24 19:53:00 +00004483 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004484 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004485 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004486 S += '{';
4487 const IdentifierInfo *II = OI->getIdentifier();
4488 S += II->getName();
4489 S += '=';
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004490 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4491 DeepCollectObjCIvars(OI, true, Ivars);
4492 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4493 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4494 if (Field->isBitField())
4495 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004496 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004497 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004498 }
4499 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004500 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004501 }
Mike Stump11289f42009-09-09 15:08:12 +00004502
John McCall9dd450b2009-09-21 23:43:11 +00004503 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004504 if (OPT->isObjCIdType()) {
4505 S += '@';
4506 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004507 }
Mike Stump11289f42009-09-09 15:08:12 +00004508
Steve Narofff0c86112009-10-28 22:03:49 +00004509 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4510 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4511 // Since this is a binary compatibility issue, need to consult with runtime
4512 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004513 S += '#';
4514 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004515 }
Mike Stump11289f42009-09-09 15:08:12 +00004516
Chris Lattnere7cabb92009-07-13 00:10:46 +00004517 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004518 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004519 ExpandPointedToStructures,
4520 ExpandStructures, FD);
4521 if (FD || EncodingProperty) {
4522 // Note that we do extended encoding of protocol qualifer list
4523 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004524 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004525 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4526 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004527 S += '<';
4528 S += (*I)->getNameAsString();
4529 S += '>';
4530 }
4531 S += '"';
4532 }
4533 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004534 }
Mike Stump11289f42009-09-09 15:08:12 +00004535
Chris Lattnere7cabb92009-07-13 00:10:46 +00004536 QualType PointeeTy = OPT->getPointeeType();
4537 if (!EncodingProperty &&
4538 isa<TypedefType>(PointeeTy.getTypePtr())) {
4539 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004540 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004541 // {...};
4542 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004543 getObjCEncodingForTypeImpl(PointeeTy, S,
4544 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004545 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004546 return;
4547 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004548
4549 S += '@';
Steve Narofff0c86112009-10-28 22:03:49 +00004550 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004551 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004552 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004553 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4554 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004555 S += '<';
4556 S += (*I)->getNameAsString();
4557 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004558 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004559 S += '"';
4560 }
4561 return;
4562 }
Mike Stump11289f42009-09-09 15:08:12 +00004563
John McCalla9e6e8d2010-05-17 23:56:34 +00004564 // gcc just blithely ignores member pointers.
4565 // TODO: maybe there should be a mangling for these
4566 if (T->getAs<MemberPointerType>())
4567 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004568
4569 if (T->isVectorType()) {
4570 // This matches gcc's encoding, even though technically it is
4571 // insufficient.
4572 // FIXME. We should do a better job than gcc.
4573 return;
4574 }
4575
Chris Lattnere7cabb92009-07-13 00:10:46 +00004576 assert(0 && "@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004577}
4578
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004579void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4580 std::string &S,
4581 const FieldDecl *FD,
4582 bool includeVBases) const {
4583 assert(RDecl && "Expected non-null RecordDecl");
4584 assert(!RDecl->isUnion() && "Should not be called for unions");
4585 if (!RDecl->getDefinition())
4586 return;
4587
4588 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4589 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4590 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4591
4592 if (CXXRec) {
4593 for (CXXRecordDecl::base_class_iterator
4594 BI = CXXRec->bases_begin(),
4595 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4596 if (!BI->isVirtual()) {
4597 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004598 if (base->isEmpty())
4599 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004600 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4601 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4602 std::make_pair(offs, base));
4603 }
4604 }
4605 }
4606
4607 unsigned i = 0;
4608 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4609 FieldEnd = RDecl->field_end();
4610 Field != FieldEnd; ++Field, ++i) {
4611 uint64_t offs = layout.getFieldOffset(i);
4612 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4613 std::make_pair(offs, *Field));
4614 }
4615
4616 if (CXXRec && includeVBases) {
4617 for (CXXRecordDecl::base_class_iterator
4618 BI = CXXRec->vbases_begin(),
4619 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4620 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004621 if (base->isEmpty())
4622 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004623 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4624 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4625 std::make_pair(offs, base));
4626 }
4627 }
4628
4629 CharUnits size;
4630 if (CXXRec) {
4631 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4632 } else {
4633 size = layout.getSize();
4634 }
4635
4636 uint64_t CurOffs = 0;
4637 std::multimap<uint64_t, NamedDecl *>::iterator
4638 CurLayObj = FieldOrBaseOffsets.begin();
4639
4640 if (CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) {
4641 assert(CXXRec && CXXRec->isDynamicClass() &&
4642 "Offset 0 was empty but no VTable ?");
4643 if (FD) {
4644 S += "\"_vptr$";
4645 std::string recname = CXXRec->getNameAsString();
4646 if (recname.empty()) recname = "?";
4647 S += recname;
4648 S += '"';
4649 }
4650 S += "^^?";
4651 CurOffs += getTypeSize(VoidPtrTy);
4652 }
4653
4654 if (!RDecl->hasFlexibleArrayMember()) {
4655 // Mark the end of the structure.
4656 uint64_t offs = toBits(size);
4657 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4658 std::make_pair(offs, (NamedDecl*)0));
4659 }
4660
4661 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4662 assert(CurOffs <= CurLayObj->first);
4663
4664 if (CurOffs < CurLayObj->first) {
4665 uint64_t padding = CurLayObj->first - CurOffs;
4666 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4667 // packing/alignment of members is different that normal, in which case
4668 // the encoding will be out-of-sync with the real layout.
4669 // If the runtime switches to just consider the size of types without
4670 // taking into account alignment, we could make padding explicit in the
4671 // encoding (e.g. using arrays of chars). The encoding strings would be
4672 // longer then though.
4673 CurOffs += padding;
4674 }
4675
4676 NamedDecl *dcl = CurLayObj->second;
4677 if (dcl == 0)
4678 break; // reached end of structure.
4679
4680 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4681 // We expand the bases without their virtual bases since those are going
4682 // in the initial structure. Note that this differs from gcc which
4683 // expands virtual bases each time one is encountered in the hierarchy,
4684 // making the encoding type bigger than it really is.
4685 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004686 assert(!base->isEmpty());
4687 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004688 } else {
4689 FieldDecl *field = cast<FieldDecl>(dcl);
4690 if (FD) {
4691 S += '"';
4692 S += field->getNameAsString();
4693 S += '"';
4694 }
4695
4696 if (field->isBitField()) {
4697 EncodeBitField(this, S, field->getType(), field);
4698 CurOffs += field->getBitWidth()->EvaluateAsInt(*this).getZExtValue();
4699 } else {
4700 QualType qt = field->getType();
4701 getLegacyIntegralTypeEncoding(qt);
4702 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4703 /*OutermostType*/false,
4704 /*EncodingProperty*/false,
4705 /*StructField*/true);
4706 CurOffs += getTypeSize(field->getType());
4707 }
4708 }
4709 }
4710}
4711
Mike Stump11289f42009-09-09 15:08:12 +00004712void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004713 std::string& S) const {
4714 if (QT & Decl::OBJC_TQ_In)
4715 S += 'n';
4716 if (QT & Decl::OBJC_TQ_Inout)
4717 S += 'N';
4718 if (QT & Decl::OBJC_TQ_Out)
4719 S += 'o';
4720 if (QT & Decl::OBJC_TQ_Bycopy)
4721 S += 'O';
4722 if (QT & Decl::OBJC_TQ_Byref)
4723 S += 'R';
4724 if (QT & Decl::OBJC_TQ_Oneway)
4725 S += 'V';
4726}
4727
Chris Lattnere7cabb92009-07-13 00:10:46 +00004728void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004729 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004730
Anders Carlsson87c149b2007-10-11 01:00:40 +00004731 BuiltinVaListType = T;
4732}
4733
Chris Lattnere7cabb92009-07-13 00:10:46 +00004734void ASTContext::setObjCIdType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004735 ObjCIdTypedefType = T;
Steve Naroff66e9f332007-10-15 14:41:52 +00004736}
4737
Chris Lattnere7cabb92009-07-13 00:10:46 +00004738void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00004739 ObjCSelTypedefType = T;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004740}
4741
Chris Lattnere7cabb92009-07-13 00:10:46 +00004742void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004743 ObjCProtoType = QT;
Fariborz Jahaniana32aaef2007-10-17 16:58:11 +00004744}
4745
Chris Lattnere7cabb92009-07-13 00:10:46 +00004746void ASTContext::setObjCClassType(QualType T) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004747 ObjCClassTypedefType = T;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004748}
4749
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004750void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004751 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004752 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004753
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004754 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004755}
4756
John McCalld28ae272009-12-02 08:04:21 +00004757/// \brief Retrieve the template name that corresponds to a non-empty
4758/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004759TemplateName
4760ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4761 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004762 unsigned size = End - Begin;
4763 assert(size > 1 && "set is not overloaded!");
4764
4765 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4766 size * sizeof(FunctionTemplateDecl*));
4767 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4768
4769 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004770 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004771 NamedDecl *D = *I;
4772 assert(isa<FunctionTemplateDecl>(D) ||
4773 (isa<UsingShadowDecl>(D) &&
4774 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4775 *Storage++ = D;
4776 }
4777
4778 return TemplateName(OT);
4779}
4780
Douglas Gregordc572a32009-03-30 22:58:21 +00004781/// \brief Retrieve the template name that represents a qualified
4782/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004783TemplateName
4784ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4785 bool TemplateKeyword,
4786 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004787 assert(NNS && "Missing nested-name-specifier in qualified template name");
4788
Douglas Gregorc42075a2010-02-04 18:10:26 +00004789 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004790 llvm::FoldingSetNodeID ID;
4791 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4792
4793 void *InsertPos = 0;
4794 QualifiedTemplateName *QTN =
4795 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4796 if (!QTN) {
4797 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4798 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4799 }
4800
4801 return TemplateName(QTN);
4802}
4803
4804/// \brief Retrieve the template name that represents a dependent
4805/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004806TemplateName
4807ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4808 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004809 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004810 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004811
4812 llvm::FoldingSetNodeID ID;
4813 DependentTemplateName::Profile(ID, NNS, Name);
4814
4815 void *InsertPos = 0;
4816 DependentTemplateName *QTN =
4817 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4818
4819 if (QTN)
4820 return TemplateName(QTN);
4821
4822 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4823 if (CanonNNS == NNS) {
4824 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4825 } else {
4826 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4827 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004828 DependentTemplateName *CheckQTN =
4829 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4830 assert(!CheckQTN && "Dependent type name canonicalization broken");
4831 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00004832 }
4833
4834 DependentTemplateNames.InsertNode(QTN, InsertPos);
4835 return TemplateName(QTN);
4836}
4837
Douglas Gregor71395fa2009-11-04 00:56:37 +00004838/// \brief Retrieve the template name that represents a dependent
4839/// template name such as \c MetaFun::template operator+.
4840TemplateName
4841ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00004842 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00004843 assert((!NNS || NNS->isDependent()) &&
4844 "Nested name specifier must be dependent");
4845
4846 llvm::FoldingSetNodeID ID;
4847 DependentTemplateName::Profile(ID, NNS, Operator);
4848
4849 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00004850 DependentTemplateName *QTN
4851 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00004852
4853 if (QTN)
4854 return TemplateName(QTN);
4855
4856 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4857 if (CanonNNS == NNS) {
4858 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4859 } else {
4860 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4861 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004862
4863 DependentTemplateName *CheckQTN
4864 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4865 assert(!CheckQTN && "Dependent template name canonicalization broken");
4866 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00004867 }
4868
4869 DependentTemplateNames.InsertNode(QTN, InsertPos);
4870 return TemplateName(QTN);
4871}
4872
Douglas Gregor5590be02011-01-15 06:45:20 +00004873TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00004874ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4875 TemplateName replacement) const {
4876 llvm::FoldingSetNodeID ID;
4877 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4878
4879 void *insertPos = 0;
4880 SubstTemplateTemplateParmStorage *subst
4881 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4882
4883 if (!subst) {
4884 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4885 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4886 }
4887
4888 return TemplateName(subst);
4889}
4890
4891TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00004892ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4893 const TemplateArgument &ArgPack) const {
4894 ASTContext &Self = const_cast<ASTContext &>(*this);
4895 llvm::FoldingSetNodeID ID;
4896 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4897
4898 void *InsertPos = 0;
4899 SubstTemplateTemplateParmPackStorage *Subst
4900 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4901
4902 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00004903 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00004904 ArgPack.pack_size(),
4905 ArgPack.pack_begin());
4906 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4907 }
4908
4909 return TemplateName(Subst);
4910}
4911
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004912/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00004913/// TargetInfo, produce the corresponding type. The unsigned @p Type
4914/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00004915CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004916 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00004917 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004918 case TargetInfo::SignedShort: return ShortTy;
4919 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4920 case TargetInfo::SignedInt: return IntTy;
4921 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4922 case TargetInfo::SignedLong: return LongTy;
4923 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4924 case TargetInfo::SignedLongLong: return LongLongTy;
4925 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4926 }
4927
4928 assert(false && "Unhandled TargetInfo::IntType value");
John McCall48f2d582009-10-23 23:03:21 +00004929 return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00004930}
Ted Kremenek77c51b22008-07-24 23:58:27 +00004931
4932//===----------------------------------------------------------------------===//
4933// Type Predicates.
4934//===----------------------------------------------------------------------===//
4935
Fariborz Jahanian96207692009-02-18 21:49:28 +00004936/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4937/// garbage collection attribute.
4938///
John McCall553d45a2011-01-12 00:34:59 +00004939Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4940 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4941 return Qualifiers::GCNone;
4942
4943 assert(getLangOptions().ObjC1);
4944 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4945
4946 // Default behaviour under objective-C's gc is for ObjC pointers
4947 // (or pointers to them) be treated as though they were declared
4948 // as __strong.
4949 if (GCAttrs == Qualifiers::GCNone) {
4950 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4951 return Qualifiers::Strong;
4952 else if (Ty->isPointerType())
4953 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4954 } else {
4955 // It's not valid to set GC attributes on anything that isn't a
4956 // pointer.
4957#ifndef NDEBUG
4958 QualType CT = Ty->getCanonicalTypeInternal();
4959 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4960 CT = AT->getElementType();
4961 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4962#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00004963 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00004964 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00004965}
4966
Chris Lattner49af6a42008-04-07 06:51:04 +00004967//===----------------------------------------------------------------------===//
4968// Type Compatibility Testing
4969//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00004970
Mike Stump11289f42009-09-09 15:08:12 +00004971/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00004972/// compatible.
4973static bool areCompatVectorTypes(const VectorType *LHS,
4974 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00004975 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00004976 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00004977 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00004978}
4979
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004980bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4981 QualType SecondVec) {
4982 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4983 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4984
4985 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4986 return true;
4987
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004988 // Treat Neon vector types and most AltiVec vector types as if they are the
4989 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004990 const VectorType *First = FirstVec->getAs<VectorType>();
4991 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004992 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004993 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00004994 First->getVectorKind() != VectorType::AltiVecPixel &&
4995 First->getVectorKind() != VectorType::AltiVecBool &&
4996 Second->getVectorKind() != VectorType::AltiVecPixel &&
4997 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00004998 return true;
4999
5000 return false;
5001}
5002
Steve Naroff8e6aee52009-07-23 01:01:38 +00005003//===----------------------------------------------------------------------===//
5004// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5005//===----------------------------------------------------------------------===//
5006
5007/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5008/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005009bool
5010ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5011 ObjCProtocolDecl *rProto) const {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005012 if (lProto == rProto)
5013 return true;
5014 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5015 E = rProto->protocol_end(); PI != E; ++PI)
5016 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5017 return true;
5018 return false;
5019}
5020
Steve Naroff8e6aee52009-07-23 01:01:38 +00005021/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5022/// return true if lhs's protocols conform to rhs's protocol; false
5023/// otherwise.
5024bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5025 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5026 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5027 return false;
5028}
5029
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005030/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5031/// Class<p1, ...>.
5032bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5033 QualType rhs) {
5034 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5035 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5036 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5037
5038 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5039 E = lhsQID->qual_end(); I != E; ++I) {
5040 bool match = false;
5041 ObjCProtocolDecl *lhsProto = *I;
5042 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5043 E = rhsOPT->qual_end(); J != E; ++J) {
5044 ObjCProtocolDecl *rhsProto = *J;
5045 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5046 match = true;
5047 break;
5048 }
5049 }
5050 if (!match)
5051 return false;
5052 }
5053 return true;
5054}
5055
Steve Naroff8e6aee52009-07-23 01:01:38 +00005056/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5057/// ObjCQualifiedIDType.
5058bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5059 bool compare) {
5060 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005061 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005062 lhs->isObjCIdType() || lhs->isObjCClassType())
5063 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005064 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005065 rhs->isObjCIdType() || rhs->isObjCClassType())
5066 return true;
5067
5068 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005069 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005070
Steve Naroff8e6aee52009-07-23 01:01:38 +00005071 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005072
Steve Naroff8e6aee52009-07-23 01:01:38 +00005073 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005074 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005075 // make sure we check the class hierarchy.
5076 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5077 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5078 E = lhsQID->qual_end(); I != E; ++I) {
5079 // when comparing an id<P> on lhs with a static type on rhs,
5080 // see if static class implements all of id's protocols, directly or
5081 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005082 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005083 return false;
5084 }
5085 }
5086 // If there are no qualifiers and no interface, we have an 'id'.
5087 return true;
5088 }
Mike Stump11289f42009-09-09 15:08:12 +00005089 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005090 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5091 E = lhsQID->qual_end(); I != E; ++I) {
5092 ObjCProtocolDecl *lhsProto = *I;
5093 bool match = false;
5094
5095 // when comparing an id<P> on lhs with a static type on rhs,
5096 // see if static class implements all of id's protocols, directly or
5097 // through its super class and categories.
5098 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5099 E = rhsOPT->qual_end(); J != E; ++J) {
5100 ObjCProtocolDecl *rhsProto = *J;
5101 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5102 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5103 match = true;
5104 break;
5105 }
5106 }
Mike Stump11289f42009-09-09 15:08:12 +00005107 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005108 // make sure we check the class hierarchy.
5109 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5110 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5111 E = lhsQID->qual_end(); I != E; ++I) {
5112 // when comparing an id<P> on lhs with a static type on rhs,
5113 // see if static class implements all of id's protocols, directly or
5114 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005115 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005116 match = true;
5117 break;
5118 }
5119 }
5120 }
5121 if (!match)
5122 return false;
5123 }
Mike Stump11289f42009-09-09 15:08:12 +00005124
Steve Naroff8e6aee52009-07-23 01:01:38 +00005125 return true;
5126 }
Mike Stump11289f42009-09-09 15:08:12 +00005127
Steve Naroff8e6aee52009-07-23 01:01:38 +00005128 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5129 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5130
Mike Stump11289f42009-09-09 15:08:12 +00005131 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005132 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005133 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005134 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5135 E = lhsOPT->qual_end(); I != E; ++I) {
5136 ObjCProtocolDecl *lhsProto = *I;
5137 bool match = false;
5138
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005139 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005140 // see if static class implements all of id's protocols, directly or
5141 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005142 // First, lhs protocols in the qualifier list must be found, direct
5143 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005144 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5145 E = rhsQID->qual_end(); J != E; ++J) {
5146 ObjCProtocolDecl *rhsProto = *J;
5147 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5148 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5149 match = true;
5150 break;
5151 }
5152 }
5153 if (!match)
5154 return false;
5155 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005156
5157 // Static class's protocols, or its super class or category protocols
5158 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5159 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5160 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5161 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5162 // This is rather dubious but matches gcc's behavior. If lhs has
5163 // no type qualifier and its class has no static protocol(s)
5164 // assume that it is mismatch.
5165 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5166 return false;
5167 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5168 LHSInheritedProtocols.begin(),
5169 E = LHSInheritedProtocols.end(); I != E; ++I) {
5170 bool match = false;
5171 ObjCProtocolDecl *lhsProto = (*I);
5172 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5173 E = rhsQID->qual_end(); J != E; ++J) {
5174 ObjCProtocolDecl *rhsProto = *J;
5175 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5176 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5177 match = true;
5178 break;
5179 }
5180 }
5181 if (!match)
5182 return false;
5183 }
5184 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005185 return true;
5186 }
5187 return false;
5188}
5189
Eli Friedman47f77112008-08-22 00:56:42 +00005190/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005191/// compatible for assignment from RHS to LHS. This handles validation of any
5192/// protocol qualifiers on the LHS or RHS.
5193///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005194bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5195 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005196 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5197 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5198
Steve Naroff1329fa02009-07-15 18:40:39 +00005199 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005200 if (LHS->isObjCUnqualifiedIdOrClass() ||
5201 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005202 return true;
5203
John McCall8b07ec22010-05-15 11:32:37 +00005204 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005205 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5206 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005207 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005208
5209 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5210 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5211 QualType(RHSOPT,0));
5212
John McCall8b07ec22010-05-15 11:32:37 +00005213 // If we have 2 user-defined types, fall into that path.
5214 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005215 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005216
Steve Naroff8e6aee52009-07-23 01:01:38 +00005217 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005218}
5219
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005220/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005221/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005222/// arguments in block literals. When passed as arguments, passing 'A*' where
5223/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5224/// not OK. For the return type, the opposite is not OK.
5225bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5226 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005227 const ObjCObjectPointerType *RHSOPT,
5228 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005229 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005230 return true;
5231
5232 if (LHSOPT->isObjCBuiltinType()) {
5233 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5234 }
5235
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005236 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005237 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5238 QualType(RHSOPT,0),
5239 false);
5240
5241 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5242 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5243 if (LHS && RHS) { // We have 2 user-defined types.
5244 if (LHS != RHS) {
5245 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005246 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005247 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005248 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005249 }
5250 else
5251 return true;
5252 }
5253 return false;
5254}
5255
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005256/// getIntersectionOfProtocols - This routine finds the intersection of set
5257/// of protocols inherited from two distinct objective-c pointer objects.
5258/// It is used to build composite qualifier list of the composite type of
5259/// the conditional expression involving two objective-c pointer objects.
5260static
5261void getIntersectionOfProtocols(ASTContext &Context,
5262 const ObjCObjectPointerType *LHSOPT,
5263 const ObjCObjectPointerType *RHSOPT,
5264 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
5265
John McCall8b07ec22010-05-15 11:32:37 +00005266 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5267 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5268 assert(LHS->getInterface() && "LHS must have an interface base");
5269 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005270
5271 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5272 unsigned LHSNumProtocols = LHS->getNumProtocols();
5273 if (LHSNumProtocols > 0)
5274 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5275 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005276 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005277 Context.CollectInheritedProtocols(LHS->getInterface(),
5278 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005279 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5280 LHSInheritedProtocols.end());
5281 }
5282
5283 unsigned RHSNumProtocols = RHS->getNumProtocols();
5284 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005285 ObjCProtocolDecl **RHSProtocols =
5286 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005287 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5288 if (InheritedProtocolSet.count(RHSProtocols[i]))
5289 IntersectionOfProtocols.push_back(RHSProtocols[i]);
5290 }
5291 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005292 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005293 Context.CollectInheritedProtocols(RHS->getInterface(),
5294 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005295 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5296 RHSInheritedProtocols.begin(),
5297 E = RHSInheritedProtocols.end(); I != E; ++I)
5298 if (InheritedProtocolSet.count((*I)))
5299 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005300 }
5301}
5302
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005303/// areCommonBaseCompatible - Returns common base class of the two classes if
5304/// one found. Note that this is O'2 algorithm. But it will be called as the
5305/// last type comparison in a ?-exp of ObjC pointer types before a
5306/// warning is issued. So, its invokation is extremely rare.
5307QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005308 const ObjCObjectPointerType *Lptr,
5309 const ObjCObjectPointerType *Rptr) {
5310 const ObjCObjectType *LHS = Lptr->getObjectType();
5311 const ObjCObjectType *RHS = Rptr->getObjectType();
5312 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5313 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005314 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005315 return QualType();
5316
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005317 do {
John McCall8b07ec22010-05-15 11:32:37 +00005318 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005319 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCall8b07ec22010-05-15 11:32:37 +00005320 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
5321 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5322
5323 QualType Result = QualType(LHS, 0);
5324 if (!Protocols.empty())
5325 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5326 Result = getObjCObjectPointerType(Result);
5327 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005328 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005329 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005330
5331 return QualType();
5332}
5333
John McCall8b07ec22010-05-15 11:32:37 +00005334bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5335 const ObjCObjectType *RHS) {
5336 assert(LHS->getInterface() && "LHS is not an interface type");
5337 assert(RHS->getInterface() && "RHS is not an interface type");
5338
Chris Lattner49af6a42008-04-07 06:51:04 +00005339 // Verify that the base decls are compatible: the RHS must be a subclass of
5340 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005341 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005342 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005343
Chris Lattner49af6a42008-04-07 06:51:04 +00005344 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5345 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005346 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005347 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005348
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005349 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5350 // more detailed analysis is required.
5351 if (RHS->getNumProtocols() == 0) {
5352 // OK, if LHS is a superclass of RHS *and*
5353 // this superclass is assignment compatible with LHS.
5354 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005355 bool IsSuperClass =
5356 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5357 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005358 // OK if conversion of LHS to SuperClass results in narrowing of types
5359 // ; i.e., SuperClass may implement at least one of the protocols
5360 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5361 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5362 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005363 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005364 // If super class has no protocols, it is not a match.
5365 if (SuperClassInheritedProtocols.empty())
5366 return false;
5367
5368 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5369 LHSPE = LHS->qual_end();
5370 LHSPI != LHSPE; LHSPI++) {
5371 bool SuperImplementsProtocol = false;
5372 ObjCProtocolDecl *LHSProto = (*LHSPI);
5373
5374 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5375 SuperClassInheritedProtocols.begin(),
5376 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5377 ObjCProtocolDecl *SuperClassProto = (*I);
5378 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5379 SuperImplementsProtocol = true;
5380 break;
5381 }
5382 }
5383 if (!SuperImplementsProtocol)
5384 return false;
5385 }
5386 return true;
5387 }
5388 return false;
5389 }
Mike Stump11289f42009-09-09 15:08:12 +00005390
John McCall8b07ec22010-05-15 11:32:37 +00005391 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5392 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005393 LHSPI != LHSPE; LHSPI++) {
5394 bool RHSImplementsProtocol = false;
5395
5396 // If the RHS doesn't implement the protocol on the left, the types
5397 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005398 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5399 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005400 RHSPI != RHSPE; RHSPI++) {
5401 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005402 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005403 break;
5404 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005405 }
5406 // FIXME: For better diagnostics, consider passing back the protocol name.
5407 if (!RHSImplementsProtocol)
5408 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005409 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005410 // The RHS implements all protocols listed on the LHS.
5411 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005412}
5413
Steve Naroffb7605152009-02-12 17:52:19 +00005414bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5415 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005416 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5417 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005418
Steve Naroff7cae42b2009-07-10 23:34:53 +00005419 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005420 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005421
5422 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5423 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005424}
5425
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005426bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5427 return canAssignObjCInterfaces(
5428 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5429 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5430}
5431
Mike Stump11289f42009-09-09 15:08:12 +00005432/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005433/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005434/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005435/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005436bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5437 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005438 if (getLangOptions().CPlusPlus)
5439 return hasSameType(LHS, RHS);
5440
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005441 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005442}
5443
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005444bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5445 return !mergeTypes(LHS, RHS, true).isNull();
5446}
5447
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005448/// mergeTransparentUnionType - if T is a transparent union type and a member
5449/// of T is compatible with SubType, return the merged type, else return
5450/// QualType()
5451QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5452 bool OfBlockPointer,
5453 bool Unqualified) {
5454 if (const RecordType *UT = T->getAsUnionType()) {
5455 RecordDecl *UD = UT->getDecl();
5456 if (UD->hasAttr<TransparentUnionAttr>()) {
5457 for (RecordDecl::field_iterator it = UD->field_begin(),
5458 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005459 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005460 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5461 if (!MT.isNull())
5462 return MT;
5463 }
5464 }
5465 }
5466
5467 return QualType();
5468}
5469
5470/// mergeFunctionArgumentTypes - merge two types which appear as function
5471/// argument types
5472QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5473 bool OfBlockPointer,
5474 bool Unqualified) {
5475 // GNU extension: two types are compatible if they appear as a function
5476 // argument, one of the types is a transparent union type and the other
5477 // type is compatible with a union member
5478 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5479 Unqualified);
5480 if (!lmerge.isNull())
5481 return lmerge;
5482
5483 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5484 Unqualified);
5485 if (!rmerge.isNull())
5486 return rmerge;
5487
5488 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5489}
5490
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005491QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005492 bool OfBlockPointer,
5493 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005494 const FunctionType *lbase = lhs->getAs<FunctionType>();
5495 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005496 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5497 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005498 bool allLTypes = true;
5499 bool allRTypes = true;
5500
5501 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005502 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005503 if (OfBlockPointer) {
5504 QualType RHS = rbase->getResultType();
5505 QualType LHS = lbase->getResultType();
5506 bool UnqualifiedResult = Unqualified;
5507 if (!UnqualifiedResult)
5508 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005509 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005510 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005511 else
John McCall8c6b56f2010-12-15 01:06:38 +00005512 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5513 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005514 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005515
5516 if (Unqualified)
5517 retType = retType.getUnqualifiedType();
5518
5519 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5520 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5521 if (Unqualified) {
5522 LRetType = LRetType.getUnqualifiedType();
5523 RRetType = RRetType.getUnqualifiedType();
5524 }
5525
5526 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005527 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005528 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005529 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005530
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005531 // FIXME: double check this
5532 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5533 // rbase->getRegParmAttr() != 0 &&
5534 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005535 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5536 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005537
Douglas Gregor8c940862010-01-18 17:14:39 +00005538 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005539 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005540 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005541
John McCall8c6b56f2010-12-15 01:06:38 +00005542 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005543 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5544 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005545 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5546 return QualType();
5547
John McCall31168b02011-06-15 23:02:42 +00005548 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5549 return QualType();
5550
John McCall8c6b56f2010-12-15 01:06:38 +00005551 // It's noreturn if either type is.
5552 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5553 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5554 if (NoReturn != lbaseInfo.getNoReturn())
5555 allLTypes = false;
5556 if (NoReturn != rbaseInfo.getNoReturn())
5557 allRTypes = false;
5558
John McCall31168b02011-06-15 23:02:42 +00005559 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005560
Eli Friedman47f77112008-08-22 00:56:42 +00005561 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005562 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5563 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005564 unsigned lproto_nargs = lproto->getNumArgs();
5565 unsigned rproto_nargs = rproto->getNumArgs();
5566
5567 // Compatible functions must have the same number of arguments
5568 if (lproto_nargs != rproto_nargs)
5569 return QualType();
5570
5571 // Variadic and non-variadic functions aren't compatible
5572 if (lproto->isVariadic() != rproto->isVariadic())
5573 return QualType();
5574
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005575 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5576 return QualType();
5577
Eli Friedman47f77112008-08-22 00:56:42 +00005578 // Check argument compatibility
5579 llvm::SmallVector<QualType, 10> types;
5580 for (unsigned i = 0; i < lproto_nargs; i++) {
5581 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5582 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005583 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5584 OfBlockPointer,
5585 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005586 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005587
5588 if (Unqualified)
5589 argtype = argtype.getUnqualifiedType();
5590
Eli Friedman47f77112008-08-22 00:56:42 +00005591 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005592 if (Unqualified) {
5593 largtype = largtype.getUnqualifiedType();
5594 rargtype = rargtype.getUnqualifiedType();
5595 }
5596
Chris Lattner465fa322008-10-05 17:34:18 +00005597 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5598 allLTypes = false;
5599 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5600 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005601 }
5602 if (allLTypes) return lhs;
5603 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005604
5605 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5606 EPI.ExtInfo = einfo;
5607 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005608 }
5609
5610 if (lproto) allRTypes = false;
5611 if (rproto) allLTypes = false;
5612
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005613 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005614 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005615 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005616 if (proto->isVariadic()) return QualType();
5617 // Check that the types are compatible with the types that
5618 // would result from default argument promotions (C99 6.7.5.3p15).
5619 // The only types actually affected are promotable integer
5620 // types and floats, which would be passed as a different
5621 // type depending on whether the prototype is visible.
5622 unsigned proto_nargs = proto->getNumArgs();
5623 for (unsigned i = 0; i < proto_nargs; ++i) {
5624 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005625
5626 // Look at the promotion type of enum types, since that is the type used
5627 // to pass enum values.
5628 if (const EnumType *Enum = argTy->getAs<EnumType>())
5629 argTy = Enum->getDecl()->getPromotionType();
5630
Eli Friedman47f77112008-08-22 00:56:42 +00005631 if (argTy->isPromotableIntegerType() ||
5632 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5633 return QualType();
5634 }
5635
5636 if (allLTypes) return lhs;
5637 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005638
5639 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5640 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005641 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005642 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005643 }
5644
5645 if (allLTypes) return lhs;
5646 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005647 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005648}
5649
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005650QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005651 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005652 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005653 // C++ [expr]: If an expression initially has the type "reference to T", the
5654 // type is adjusted to "T" prior to any further analysis, the expression
5655 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005656 // expression is an lvalue unless the reference is an rvalue reference and
5657 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005658 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5659 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005660
5661 if (Unqualified) {
5662 LHS = LHS.getUnqualifiedType();
5663 RHS = RHS.getUnqualifiedType();
5664 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005665
Eli Friedman47f77112008-08-22 00:56:42 +00005666 QualType LHSCan = getCanonicalType(LHS),
5667 RHSCan = getCanonicalType(RHS);
5668
5669 // If two types are identical, they are compatible.
5670 if (LHSCan == RHSCan)
5671 return LHS;
5672
John McCall8ccfcb52009-09-24 19:53:00 +00005673 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005674 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5675 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005676 if (LQuals != RQuals) {
5677 // If any of these qualifiers are different, we have a type
5678 // mismatch.
5679 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005680 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5681 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005682 return QualType();
5683
5684 // Exactly one GC qualifier difference is allowed: __strong is
5685 // okay if the other type has no GC qualifier but is an Objective
5686 // C object pointer (i.e. implicitly strong by default). We fix
5687 // this by pretending that the unqualified type was actually
5688 // qualified __strong.
5689 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5690 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5691 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5692
5693 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5694 return QualType();
5695
5696 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5697 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5698 }
5699 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5700 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5701 }
Eli Friedman47f77112008-08-22 00:56:42 +00005702 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005703 }
5704
5705 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005706
Eli Friedmandcca6332009-06-01 01:22:52 +00005707 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5708 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005709
Chris Lattnerfd652912008-01-14 05:45:46 +00005710 // We want to consider the two function types to be the same for these
5711 // comparisons, just force one to the other.
5712 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5713 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005714
5715 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005716 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5717 LHSClass = Type::ConstantArray;
5718 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5719 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005720
John McCall8b07ec22010-05-15 11:32:37 +00005721 // ObjCInterfaces are just specialized ObjCObjects.
5722 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5723 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5724
Nate Begemance4d7fc2008-04-18 23:10:10 +00005725 // Canonicalize ExtVector -> Vector.
5726 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5727 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005728
Chris Lattner95554662008-04-07 05:43:21 +00005729 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005730 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005731 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005732 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005733 // Compatibility is based on the underlying type, not the promotion
5734 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005735 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005736 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5737 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005738 }
John McCall9dd450b2009-09-21 23:43:11 +00005739 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman47f77112008-08-22 00:56:42 +00005740 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5741 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005742 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005743
Eli Friedman47f77112008-08-22 00:56:42 +00005744 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005745 }
Eli Friedman47f77112008-08-22 00:56:42 +00005746
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005747 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005748 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005749#define TYPE(Class, Base)
5750#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005751#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005752#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5753#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5754#include "clang/AST/TypeNodes.def"
5755 assert(false && "Non-canonical and dependent types shouldn't get here");
5756 return QualType();
5757
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005758 case Type::LValueReference:
5759 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005760 case Type::MemberPointer:
5761 assert(false && "C++ should never be in mergeTypes");
5762 return QualType();
5763
John McCall8b07ec22010-05-15 11:32:37 +00005764 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005765 case Type::IncompleteArray:
5766 case Type::VariableArray:
5767 case Type::FunctionProto:
5768 case Type::ExtVector:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005769 assert(false && "Types are eliminated above");
5770 return QualType();
5771
Chris Lattnerfd652912008-01-14 05:45:46 +00005772 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005773 {
5774 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005775 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5776 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005777 if (Unqualified) {
5778 LHSPointee = LHSPointee.getUnqualifiedType();
5779 RHSPointee = RHSPointee.getUnqualifiedType();
5780 }
5781 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5782 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005783 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005784 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005785 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005786 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005787 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005788 return getPointerType(ResultType);
5789 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005790 case Type::BlockPointer:
5791 {
5792 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005793 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5794 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005795 if (Unqualified) {
5796 LHSPointee = LHSPointee.getUnqualifiedType();
5797 RHSPointee = RHSPointee.getUnqualifiedType();
5798 }
5799 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5800 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005801 if (ResultType.isNull()) return QualType();
5802 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5803 return LHS;
5804 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5805 return RHS;
5806 return getBlockPointerType(ResultType);
5807 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005808 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00005809 {
5810 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5811 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5812 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5813 return QualType();
5814
5815 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5816 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005817 if (Unqualified) {
5818 LHSElem = LHSElem.getUnqualifiedType();
5819 RHSElem = RHSElem.getUnqualifiedType();
5820 }
5821
5822 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005823 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00005824 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5825 return LHS;
5826 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5827 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00005828 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5829 ArrayType::ArraySizeModifier(), 0);
5830 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5831 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005832 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5833 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00005834 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5835 return LHS;
5836 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5837 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005838 if (LVAT) {
5839 // FIXME: This isn't correct! But tricky to implement because
5840 // the array's size has to be the size of LHS, but the type
5841 // has to be different.
5842 return LHS;
5843 }
5844 if (RVAT) {
5845 // FIXME: This isn't correct! But tricky to implement because
5846 // the array's size has to be the size of RHS, but the type
5847 // has to be different.
5848 return RHS;
5849 }
Eli Friedman3e62c212008-08-22 01:48:21 +00005850 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5851 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00005852 return getIncompleteArrayType(ResultType,
5853 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00005854 }
Chris Lattnerfd652912008-01-14 05:45:46 +00005855 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005856 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005857 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005858 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00005859 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00005860 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005861 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00005862 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00005863 case Type::Complex:
5864 // Distinct complex types are incompatible.
5865 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00005866 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00005867 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00005868 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5869 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00005870 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00005871 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00005872 case Type::ObjCObject: {
5873 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00005874 // FIXME: This should be type compatibility, e.g. whether
5875 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00005876 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5877 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5878 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00005879 return LHS;
5880
Eli Friedman47f77112008-08-22 00:56:42 +00005881 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00005882 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005883 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005884 if (OfBlockPointer) {
5885 if (canAssignObjCInterfacesInBlockPointer(
5886 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005887 RHS->getAs<ObjCObjectPointerType>(),
5888 BlockReturnType))
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005889 return LHS;
5890 return QualType();
5891 }
John McCall9dd450b2009-09-21 23:43:11 +00005892 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5893 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005894 return LHS;
5895
Steve Naroffc68cfcf2008-12-10 22:14:21 +00005896 return QualType();
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005897 }
Steve Naroff32e44c02007-10-15 20:41:53 +00005898 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005899
5900 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005901}
Ted Kremenekfc581a92007-10-31 17:10:13 +00005902
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005903/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5904/// 'RHS' attributes and returns the merged version; including for function
5905/// return types.
5906QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5907 QualType LHSCan = getCanonicalType(LHS),
5908 RHSCan = getCanonicalType(RHS);
5909 // If two types are identical, they are compatible.
5910 if (LHSCan == RHSCan)
5911 return LHS;
5912 if (RHSCan->isFunctionType()) {
5913 if (!LHSCan->isFunctionType())
5914 return QualType();
5915 QualType OldReturnType =
5916 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5917 QualType NewReturnType =
5918 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5919 QualType ResReturnType =
5920 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5921 if (ResReturnType.isNull())
5922 return QualType();
5923 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5924 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5925 // In either case, use OldReturnType to build the new function type.
5926 const FunctionType *F = LHS->getAs<FunctionType>();
5927 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00005928 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5929 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005930 QualType ResultType
5931 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005932 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00005933 return ResultType;
5934 }
5935 }
5936 return QualType();
5937 }
5938
5939 // If the qualifiers are different, the types can still be merged.
5940 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5941 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5942 if (LQuals != RQuals) {
5943 // If any of these qualifiers are different, we have a type mismatch.
5944 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5945 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5946 return QualType();
5947
5948 // Exactly one GC qualifier difference is allowed: __strong is
5949 // okay if the other type has no GC qualifier but is an Objective
5950 // C object pointer (i.e. implicitly strong by default). We fix
5951 // this by pretending that the unqualified type was actually
5952 // qualified __strong.
5953 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5954 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5955 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5956
5957 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5958 return QualType();
5959
5960 if (GC_L == Qualifiers::Strong)
5961 return LHS;
5962 if (GC_R == Qualifiers::Strong)
5963 return RHS;
5964 return QualType();
5965 }
5966
5967 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5968 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5969 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5970 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5971 if (ResQT == LHSBaseQT)
5972 return LHS;
5973 if (ResQT == RHSBaseQT)
5974 return RHS;
5975 }
5976 return QualType();
5977}
5978
Chris Lattner4ba0cef2008-04-07 07:01:58 +00005979//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005980// Integer Predicates
5981//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00005982
Jay Foad39c79802011-01-12 09:06:06 +00005983unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00005984 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00005985 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00005986 if (T->isBooleanType())
5987 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00005988 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00005989 return (unsigned)getTypeSize(T);
5990}
5991
5992QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005993 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00005994
5995 // Turn <4 x signed int> -> <4 x unsigned int>
5996 if (const VectorType *VTy = T->getAs<VectorType>())
5997 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00005998 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00005999
6000 // For enums, we return the unsigned version of the base type.
6001 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006002 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006003
6004 const BuiltinType *BTy = T->getAs<BuiltinType>();
6005 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006006 switch (BTy->getKind()) {
6007 case BuiltinType::Char_S:
6008 case BuiltinType::SChar:
6009 return UnsignedCharTy;
6010 case BuiltinType::Short:
6011 return UnsignedShortTy;
6012 case BuiltinType::Int:
6013 return UnsignedIntTy;
6014 case BuiltinType::Long:
6015 return UnsignedLongTy;
6016 case BuiltinType::LongLong:
6017 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006018 case BuiltinType::Int128:
6019 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006020 default:
6021 assert(0 && "Unexpected signed integer type");
6022 return QualType();
6023 }
6024}
6025
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006026ASTMutationListener::~ASTMutationListener() { }
6027
Chris Lattnerecd79c62009-06-14 00:45:47 +00006028
6029//===----------------------------------------------------------------------===//
6030// Builtin Type Computation
6031//===----------------------------------------------------------------------===//
6032
6033/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006034/// pointer over the consumed characters. This returns the resultant type. If
6035/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6036/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6037/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006038///
6039/// RequiresICE is filled in on return to indicate whether the value is required
6040/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006041static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006042 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006043 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006044 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006045 // Modifiers.
6046 int HowLong = 0;
6047 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006048 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006049
Chris Lattnerdc226c22010-10-01 22:42:38 +00006050 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006051 bool Done = false;
6052 while (!Done) {
6053 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006054 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006055 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006056 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006057 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006058 case 'S':
6059 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6060 assert(!Signed && "Can't use 'S' modifier multiple times!");
6061 Signed = true;
6062 break;
6063 case 'U':
6064 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6065 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6066 Unsigned = true;
6067 break;
6068 case 'L':
6069 assert(HowLong <= 2 && "Can't have LLLL modifier");
6070 ++HowLong;
6071 break;
6072 }
6073 }
6074
6075 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006076
Chris Lattnerecd79c62009-06-14 00:45:47 +00006077 // Read the base type.
6078 switch (*Str++) {
6079 default: assert(0 && "Unknown builtin type letter!");
6080 case 'v':
6081 assert(HowLong == 0 && !Signed && !Unsigned &&
6082 "Bad modifiers used with 'v'!");
6083 Type = Context.VoidTy;
6084 break;
6085 case 'f':
6086 assert(HowLong == 0 && !Signed && !Unsigned &&
6087 "Bad modifiers used with 'f'!");
6088 Type = Context.FloatTy;
6089 break;
6090 case 'd':
6091 assert(HowLong < 2 && !Signed && !Unsigned &&
6092 "Bad modifiers used with 'd'!");
6093 if (HowLong)
6094 Type = Context.LongDoubleTy;
6095 else
6096 Type = Context.DoubleTy;
6097 break;
6098 case 's':
6099 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6100 if (Unsigned)
6101 Type = Context.UnsignedShortTy;
6102 else
6103 Type = Context.ShortTy;
6104 break;
6105 case 'i':
6106 if (HowLong == 3)
6107 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6108 else if (HowLong == 2)
6109 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6110 else if (HowLong == 1)
6111 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6112 else
6113 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6114 break;
6115 case 'c':
6116 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6117 if (Signed)
6118 Type = Context.SignedCharTy;
6119 else if (Unsigned)
6120 Type = Context.UnsignedCharTy;
6121 else
6122 Type = Context.CharTy;
6123 break;
6124 case 'b': // boolean
6125 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6126 Type = Context.BoolTy;
6127 break;
6128 case 'z': // size_t.
6129 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6130 Type = Context.getSizeType();
6131 break;
6132 case 'F':
6133 Type = Context.getCFConstantStringType();
6134 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006135 case 'G':
6136 Type = Context.getObjCIdType();
6137 break;
6138 case 'H':
6139 Type = Context.getObjCSelType();
6140 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006141 case 'a':
6142 Type = Context.getBuiltinVaListType();
6143 assert(!Type.isNull() && "builtin va list type not initialized!");
6144 break;
6145 case 'A':
6146 // This is a "reference" to a va_list; however, what exactly
6147 // this means depends on how va_list is defined. There are two
6148 // different kinds of va_list: ones passed by value, and ones
6149 // passed by reference. An example of a by-value va_list is
6150 // x86, where va_list is a char*. An example of by-ref va_list
6151 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6152 // we want this argument to be a char*&; for x86-64, we want
6153 // it to be a __va_list_tag*.
6154 Type = Context.getBuiltinVaListType();
6155 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006156 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006157 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006158 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006159 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006160 break;
6161 case 'V': {
6162 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006163 unsigned NumElements = strtoul(Str, &End, 10);
6164 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006165 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006166
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006167 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6168 RequiresICE, false);
6169 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006170
6171 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006172 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006173 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006174 break;
6175 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006176 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006177 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6178 false);
6179 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006180 Type = Context.getComplexType(ElementType);
6181 break;
6182 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006183 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006184 Type = Context.getFILEType();
6185 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006186 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006187 return QualType();
6188 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006189 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006190 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006191 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006192 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006193 else
6194 Type = Context.getjmp_bufType();
6195
Mike Stump2adb4da2009-07-28 23:47:15 +00006196 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006197 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006198 return QualType();
6199 }
6200 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006201 }
Mike Stump11289f42009-09-09 15:08:12 +00006202
Chris Lattnerdc226c22010-10-01 22:42:38 +00006203 // If there are modifiers and if we're allowed to parse them, go for it.
6204 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006205 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006206 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006207 default: Done = true; --Str; break;
6208 case '*':
6209 case '&': {
6210 // Both pointers and references can have their pointee types
6211 // qualified with an address space.
6212 char *End;
6213 unsigned AddrSpace = strtoul(Str, &End, 10);
6214 if (End != Str && AddrSpace != 0) {
6215 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6216 Str = End;
6217 }
6218 if (c == '*')
6219 Type = Context.getPointerType(Type);
6220 else
6221 Type = Context.getLValueReferenceType(Type);
6222 break;
6223 }
6224 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6225 case 'C':
6226 Type = Type.withConst();
6227 break;
6228 case 'D':
6229 Type = Context.getVolatileType(Type);
6230 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006231 }
6232 }
Chris Lattner84733392010-10-01 07:13:18 +00006233
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006234 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006235 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006236
Chris Lattnerecd79c62009-06-14 00:45:47 +00006237 return Type;
6238}
6239
6240/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006241QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006242 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006243 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006244 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006245
Chris Lattnerecd79c62009-06-14 00:45:47 +00006246 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006247
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006248 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006249 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006250 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6251 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006252 if (Error != GE_None)
6253 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006254
6255 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6256
Chris Lattnerecd79c62009-06-14 00:45:47 +00006257 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006258 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006259 if (Error != GE_None)
6260 return QualType();
6261
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006262 // If this argument is required to be an IntegerConstantExpression and the
6263 // caller cares, fill in the bitmask we return.
6264 if (RequiresICE && IntegerConstantArgs)
6265 *IntegerConstantArgs |= 1 << ArgTypes.size();
6266
Chris Lattnerecd79c62009-06-14 00:45:47 +00006267 // Do array -> pointer decay. The builtin should use the decayed type.
6268 if (Ty->isArrayType())
6269 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006270
Chris Lattnerecd79c62009-06-14 00:45:47 +00006271 ArgTypes.push_back(Ty);
6272 }
6273
6274 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6275 "'.' should only occur at end of builtin type list!");
6276
John McCall991eb4b2010-12-21 00:44:39 +00006277 FunctionType::ExtInfo EI;
6278 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6279
6280 bool Variadic = (TypeStr[0] == '.');
6281
6282 // We really shouldn't be making a no-proto type here, especially in C++.
6283 if (ArgTypes.empty() && Variadic)
6284 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006285
John McCalldb40c7f2010-12-14 08:05:40 +00006286 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006287 EPI.ExtInfo = EI;
6288 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006289
6290 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006291}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006292
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006293GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6294 GVALinkage External = GVA_StrongExternal;
6295
6296 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006297 switch (L) {
6298 case NoLinkage:
6299 case InternalLinkage:
6300 case UniqueExternalLinkage:
6301 return GVA_Internal;
6302
6303 case ExternalLinkage:
6304 switch (FD->getTemplateSpecializationKind()) {
6305 case TSK_Undeclared:
6306 case TSK_ExplicitSpecialization:
6307 External = GVA_StrongExternal;
6308 break;
6309
6310 case TSK_ExplicitInstantiationDefinition:
6311 return GVA_ExplicitTemplateInstantiation;
6312
6313 case TSK_ExplicitInstantiationDeclaration:
6314 case TSK_ImplicitInstantiation:
6315 External = GVA_TemplateInstantiation;
6316 break;
6317 }
6318 }
6319
6320 if (!FD->isInlined())
6321 return External;
6322
6323 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6324 // GNU or C99 inline semantics. Determine whether this symbol should be
6325 // externally visible.
6326 if (FD->isInlineDefinitionExternallyVisible())
6327 return External;
6328
6329 // C99 inline semantics, where the symbol is not externally visible.
6330 return GVA_C99Inline;
6331 }
6332
6333 // C++0x [temp.explicit]p9:
6334 // [ Note: The intent is that an inline function that is the subject of
6335 // an explicit instantiation declaration will still be implicitly
6336 // instantiated when used so that the body can be considered for
6337 // inlining, but that no out-of-line copy of the inline function would be
6338 // generated in the translation unit. -- end note ]
6339 if (FD->getTemplateSpecializationKind()
6340 == TSK_ExplicitInstantiationDeclaration)
6341 return GVA_C99Inline;
6342
6343 return GVA_CXXInline;
6344}
6345
6346GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6347 // If this is a static data member, compute the kind of template
6348 // specialization. Otherwise, this variable is not part of a
6349 // template.
6350 TemplateSpecializationKind TSK = TSK_Undeclared;
6351 if (VD->isStaticDataMember())
6352 TSK = VD->getTemplateSpecializationKind();
6353
6354 Linkage L = VD->getLinkage();
6355 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6356 VD->getType()->getLinkage() == UniqueExternalLinkage)
6357 L = UniqueExternalLinkage;
6358
6359 switch (L) {
6360 case NoLinkage:
6361 case InternalLinkage:
6362 case UniqueExternalLinkage:
6363 return GVA_Internal;
6364
6365 case ExternalLinkage:
6366 switch (TSK) {
6367 case TSK_Undeclared:
6368 case TSK_ExplicitSpecialization:
6369 return GVA_StrongExternal;
6370
6371 case TSK_ExplicitInstantiationDeclaration:
6372 llvm_unreachable("Variable should not be instantiated");
6373 // Fall through to treat this like any other instantiation.
6374
6375 case TSK_ExplicitInstantiationDefinition:
6376 return GVA_ExplicitTemplateInstantiation;
6377
6378 case TSK_ImplicitInstantiation:
6379 return GVA_TemplateInstantiation;
6380 }
6381 }
6382
6383 return GVA_StrongExternal;
6384}
6385
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006386bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006387 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6388 if (!VD->isFileVarDecl())
6389 return false;
6390 } else if (!isa<FunctionDecl>(D))
6391 return false;
6392
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006393 // Weak references don't produce any output by themselves.
6394 if (D->hasAttr<WeakRefAttr>())
6395 return false;
6396
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006397 // Aliases and used decls are required.
6398 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6399 return true;
6400
6401 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6402 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006403 if (!FD->doesThisDeclarationHaveABody())
Cameron Zwarichbe652e62011-07-07 21:03:28 +00006404 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006405
6406 // Constructors and destructors are required.
6407 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6408 return true;
6409
6410 // The key function for a class is required.
6411 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6412 const CXXRecordDecl *RD = MD->getParent();
6413 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6414 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6415 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6416 return true;
6417 }
6418 }
6419
6420 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6421
6422 // static, static inline, always_inline, and extern inline functions can
6423 // always be deferred. Normal inline functions can be deferred in C99/C++.
6424 // Implicit template instantiations can also be deferred in C++.
6425 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6426 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6427 return false;
6428 return true;
6429 }
6430
6431 const VarDecl *VD = cast<VarDecl>(D);
6432 assert(VD->isFileVarDecl() && "Expected file scoped var");
6433
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006434 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6435 return false;
6436
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006437 // Structs that have non-trivial constructors or destructors are required.
6438
6439 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006440 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006441 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6442 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006443 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6444 RD->hasTrivialCopyConstructor() &&
6445 RD->hasTrivialMoveConstructor() &&
6446 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006447 return true;
6448 }
6449 }
6450
6451 GVALinkage L = GetGVALinkageForVariable(VD);
6452 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6453 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6454 return false;
6455 }
6456
6457 return true;
6458}
Charles Davis53c59df2010-08-16 03:33:14 +00006459
Charles Davis99202b32010-11-09 18:04:24 +00006460CallingConv ASTContext::getDefaultMethodCallConv() {
6461 // Pass through to the C++ ABI object
6462 return ABI->getDefaultMethodCallConv();
6463}
6464
Jay Foad39c79802011-01-12 09:06:06 +00006465bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006466 // Pass through to the C++ ABI object
6467 return ABI->isNearlyEmpty(RD);
6468}
6469
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006470MangleContext *ASTContext::createMangleContext() {
6471 switch (Target.getCXXABI()) {
6472 case CXXABI_ARM:
6473 case CXXABI_Itanium:
6474 return createItaniumMangleContext(*this, getDiagnostics());
6475 case CXXABI_Microsoft:
6476 return createMicrosoftMangleContext(*this, getDiagnostics());
6477 }
6478 assert(0 && "Unsupported ABI");
6479 return 0;
6480}
6481
Charles Davis53c59df2010-08-16 03:33:14 +00006482CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006483
6484size_t ASTContext::getSideTableAllocatedMemory() const {
6485 size_t bytes = 0;
6486 bytes += ASTRecordLayouts.getMemorySize();
6487 bytes += ObjCLayouts.getMemorySize();
6488 bytes += KeyFunctions.getMemorySize();
6489 bytes += ObjCImpls.getMemorySize();
6490 bytes += BlockVarCopyInits.getMemorySize();
6491 bytes += DeclAttrs.getMemorySize();
6492 bytes += InstantiatedFromStaticDataMember.getMemorySize();
6493 bytes += InstantiatedFromUsingDecl.getMemorySize();
6494 bytes += InstantiatedFromUsingShadowDecl.getMemorySize();
6495 bytes += InstantiatedFromUnnamedFieldDecl.getMemorySize();
6496 return bytes;
6497}