blob: e208bfdf1df5174d1e6a30229e0431c8a9713ed4 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000033#include "CXXABI.h"
Anders Carlsson29445a02009-07-18 21:19:52 +000034
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
36
Douglas Gregor18274032010-07-03 00:47:00 +000037unsigned ASTContext::NumImplicitDefaultConstructors;
38unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000039unsigned ASTContext::NumImplicitCopyConstructors;
40unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000041unsigned ASTContext::NumImplicitCopyAssignmentOperators;
42unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000043unsigned ASTContext::NumImplicitDestructors;
44unsigned ASTContext::NumImplicitDestructorsDeclared;
45
Reid Spencer5f016e22007-07-11 17:01:13 +000046enum FloatingRank {
47 FloatRank, DoubleRank, LongDoubleRank
48};
49
Douglas Gregor3e1274f2010-06-16 21:09:37 +000050void
51ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
52 TemplateTemplateParmDecl *Parm) {
53 ID.AddInteger(Parm->getDepth());
54 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +000055 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000056
57 TemplateParameterList *Params = Parm->getTemplateParameters();
58 ID.AddInteger(Params->size());
59 for (TemplateParameterList::const_iterator P = Params->begin(),
60 PEnd = Params->end();
61 P != PEnd; ++P) {
62 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
63 ID.AddInteger(0);
64 ID.AddBoolean(TTP->isParameterPack());
65 continue;
66 }
67
68 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
69 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +000070 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000071 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +000072 if (NTTP->isExpandedParameterPack()) {
73 ID.AddBoolean(true);
74 ID.AddInteger(NTTP->getNumExpansionTypes());
75 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
76 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
77 } else
78 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +000079 continue;
80 }
81
82 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
83 ID.AddInteger(2);
84 Profile(ID, TTP);
85 }
86}
87
88TemplateTemplateParmDecl *
89ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000090 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000091 // Check if we already have a canonical template template parameter.
92 llvm::FoldingSetNodeID ID;
93 CanonicalTemplateTemplateParm::Profile(ID, TTP);
94 void *InsertPos = 0;
95 CanonicalTemplateTemplateParm *Canonical
96 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
97 if (Canonical)
98 return Canonical->getParam();
99
100 // Build a canonical template parameter list.
101 TemplateParameterList *Params = TTP->getTemplateParameters();
102 llvm::SmallVector<NamedDecl *, 4> CanonParams;
103 CanonParams.reserve(Params->size());
104 for (TemplateParameterList::const_iterator P = Params->begin(),
105 PEnd = Params->end();
106 P != PEnd; ++P) {
107 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
108 CanonParams.push_back(
109 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000110 SourceLocation(),
111 SourceLocation(),
112 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000113 TTP->getIndex(), 0, false,
114 TTP->isParameterPack()));
115 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000116 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
117 QualType T = getCanonicalType(NTTP->getType());
118 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
119 NonTypeTemplateParmDecl *Param;
120 if (NTTP->isExpandedParameterPack()) {
121 llvm::SmallVector<QualType, 2> ExpandedTypes;
122 llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
123 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
124 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
125 ExpandedTInfos.push_back(
126 getTrivialTypeSourceInfo(ExpandedTypes.back()));
127 }
128
129 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000130 SourceLocation(),
131 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000132 NTTP->getDepth(),
133 NTTP->getPosition(), 0,
134 T,
135 TInfo,
136 ExpandedTypes.data(),
137 ExpandedTypes.size(),
138 ExpandedTInfos.data());
139 } else {
140 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000141 SourceLocation(),
142 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000143 NTTP->getDepth(),
144 NTTP->getPosition(), 0,
145 T,
146 NTTP->isParameterPack(),
147 TInfo);
148 }
149 CanonParams.push_back(Param);
150
151 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000152 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
153 cast<TemplateTemplateParmDecl>(*P)));
154 }
155
156 TemplateTemplateParmDecl *CanonTTP
157 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
158 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000159 TTP->getPosition(),
160 TTP->isParameterPack(),
161 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000162 TemplateParameterList::Create(*this, SourceLocation(),
163 SourceLocation(),
164 CanonParams.data(),
165 CanonParams.size(),
166 SourceLocation()));
167
168 // Get the new insert position for the node we care about.
169 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
170 assert(Canonical == 0 && "Shouldn't be in the map!");
171 (void)Canonical;
172
173 // Create the canonical template template parameter entry.
174 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
175 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
176 return CanonTTP;
177}
178
Charles Davis071cc7d2010-08-16 03:33:14 +0000179CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000180 if (!LangOpts.CPlusPlus) return 0;
181
Charles Davis20cf7172010-08-19 02:18:14 +0000182 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000183 case CXXABI_ARM:
184 return CreateARMCXXABI(*this);
185 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000186 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000187 case CXXABI_Microsoft:
188 return CreateMicrosoftCXXABI(*this);
189 }
John McCallee79a4c2010-08-21 22:46:04 +0000190 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000191}
192
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000193static const LangAS::Map &getAddressSpaceMap(const TargetInfo &T,
194 const LangOptions &LOpts) {
195 if (LOpts.FakeAddressSpaceMap) {
196 // The fake address space map must have a distinct entry for each
197 // language-specific address space.
198 static const unsigned FakeAddrSpaceMap[] = {
199 1, // opencl_global
200 2, // opencl_local
201 3 // opencl_constant
202 };
203 return FakeAddrSpaceMap;
204 } else {
205 return T.getAddressSpaceMap();
206 }
207}
208
Chris Lattner61710852008-10-05 17:34:18 +0000209ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000210 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000211 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000212 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000213 unsigned size_reserve) :
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000214 FunctionProtoTypes(this_()),
John McCallef990012010-06-11 11:07:21 +0000215 TemplateSpecializationTypes(this_()),
216 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000217 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
218 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000219 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000220 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Peter Collingbourne14b6ba72011-02-09 21:04:32 +0000221 cudaConfigureCallDecl(0),
John McCallbf1a0282010-06-04 23:28:52 +0000222 NullTypeSourceInfo(QualType()),
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000223 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
224 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000225 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000226 BuiltinInfo(builtins),
227 DeclarationNames(*this),
Argyrios Kyrtzidis9a44b5f2010-10-28 09:29:35 +0000228 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000229 LastSDM(0, 0),
John McCall8178df32011-02-22 22:38:33 +0000230 UniqueBlockByRefTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000231 ObjCIdRedefinitionType = QualType();
232 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000233 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000234 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000235 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000236 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000237}
238
Reid Spencer5f016e22007-07-11 17:01:13 +0000239ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000240 // Release the DenseMaps associated with DeclContext objects.
241 // FIXME: Is this the ideal solution?
242 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000243
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000244 // Call all of the deallocation functions.
245 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
246 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000247
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000248 // Release all of the memory associated with overridden C++ methods.
249 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
250 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
251 OM != OMEnd; ++OM)
252 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000253
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000254 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000255 // because they can contain DenseMaps.
256 for (llvm::DenseMap<const ObjCContainerDecl*,
257 const ASTRecordLayout*>::iterator
258 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
259 // Increment in loop to prevent using deallocated memory.
260 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
261 R->Destroy(*this);
262
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000263 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
264 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
265 // Increment in loop to prevent using deallocated memory.
266 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
267 R->Destroy(*this);
268 }
Douglas Gregor63200642010-08-30 16:49:28 +0000269
270 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
271 AEnd = DeclAttrs.end();
272 A != AEnd; ++A)
273 A->second->~AttrVec();
274}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000275
Douglas Gregor00545312010-05-23 18:26:36 +0000276void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
277 Deallocations.push_back(std::make_pair(Callback, Data));
278}
279
Mike Stump1eb44332009-09-09 15:08:12 +0000280void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000281ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
282 ExternalSource.reset(Source.take());
283}
284
Reid Spencer5f016e22007-07-11 17:01:13 +0000285void ASTContext::PrintStats() const {
286 fprintf(stderr, "*** AST Context Stats:\n");
287 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000288
Douglas Gregordbe833d2009-05-26 14:40:08 +0000289 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000290#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000291#define ABSTRACT_TYPE(Name, Parent)
292#include "clang/AST/TypeNodes.def"
293 0 // Extra
294 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000295
Reid Spencer5f016e22007-07-11 17:01:13 +0000296 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
297 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000298 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000299 }
300
Douglas Gregordbe833d2009-05-26 14:40:08 +0000301 unsigned Idx = 0;
302 unsigned TotalBytes = 0;
303#define TYPE(Name, Parent) \
304 if (counts[Idx]) \
305 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
306 TotalBytes += counts[Idx] * sizeof(Name##Type); \
307 ++Idx;
308#define ABSTRACT_TYPE(Name, Parent)
309#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Douglas Gregordbe833d2009-05-26 14:40:08 +0000311 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregored8abf12010-07-08 06:14:04 +0000312
Douglas Gregor4923aa22010-07-02 20:37:36 +0000313 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000314 fprintf(stderr, " %u/%u implicit default constructors created\n",
315 NumImplicitDefaultConstructorsDeclared,
316 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000317 fprintf(stderr, " %u/%u implicit copy constructors created\n",
318 NumImplicitCopyConstructorsDeclared,
319 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000320 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
321 NumImplicitCopyAssignmentOperatorsDeclared,
322 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000323 fprintf(stderr, " %u/%u implicit destructors created\n",
324 NumImplicitDestructorsDeclared, NumImplicitDestructors);
325
Douglas Gregor2cf26342009-04-09 22:27:44 +0000326 if (ExternalSource.get()) {
327 fprintf(stderr, "\n");
328 ExternalSource->PrintStats();
329 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000330
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000331 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000332}
333
334
John McCalle27ec8a2009-10-23 23:03:21 +0000335void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000336 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000337 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000338 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000339}
340
Reid Spencer5f016e22007-07-11 17:01:13 +0000341void ASTContext::InitBuiltinTypes() {
342 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Reid Spencer5f016e22007-07-11 17:01:13 +0000344 // C99 6.2.5p19.
345 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 // C99 6.2.5p2.
348 InitBuiltinType(BoolTy, BuiltinType::Bool);
349 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000350 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000351 InitBuiltinType(CharTy, BuiltinType::Char_S);
352 else
353 InitBuiltinType(CharTy, BuiltinType::Char_U);
354 // C99 6.2.5p4.
355 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
356 InitBuiltinType(ShortTy, BuiltinType::Short);
357 InitBuiltinType(IntTy, BuiltinType::Int);
358 InitBuiltinType(LongTy, BuiltinType::Long);
359 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 // C99 6.2.5p6.
362 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
363 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
364 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
365 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
366 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 // C99 6.2.5p10.
369 InitBuiltinType(FloatTy, BuiltinType::Float);
370 InitBuiltinType(DoubleTy, BuiltinType::Double);
371 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000372
Chris Lattner2df9ced2009-04-30 02:43:43 +0000373 // GNU extension, 128-bit integers.
374 InitBuiltinType(Int128Ty, BuiltinType::Int128);
375 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
376
Chris Lattner3f59c972010-12-25 23:25:43 +0000377 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
378 if (!LangOpts.ShortWChar)
379 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
380 else // -fshort-wchar makes wchar_t be unsigned.
381 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
382 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000383 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000384
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000385 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
386 InitBuiltinType(Char16Ty, BuiltinType::Char16);
387 else // C99
388 Char16Ty = getFromTargetType(Target.getChar16Type());
389
390 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
391 InitBuiltinType(Char32Ty, BuiltinType::Char32);
392 else // C99
393 Char32Ty = getFromTargetType(Target.getChar32Type());
394
Douglas Gregor898574e2008-12-05 23:32:09 +0000395 // Placeholder type for type-dependent expressions whose type is
396 // completely unknown. No code should ever check a type against
397 // DependentTy and users should never see it; however, it is here to
398 // help diagnose failures to properly check for type-dependent
399 // expressions.
400 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000401
John McCall2a984ca2010-10-12 00:20:44 +0000402 // Placeholder type for functions.
403 InitBuiltinType(OverloadTy, BuiltinType::Overload);
404
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 // C99 6.2.5p11.
406 FloatComplexTy = getComplexType(FloatTy);
407 DoubleComplexTy = getComplexType(DoubleTy);
408 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000409
Steve Naroff7e219e42007-10-15 14:41:52 +0000410 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Steve Naroffde2e22d2009-07-15 18:40:39 +0000412 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
413 ObjCIdTypedefType = QualType();
414 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000415 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000417 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000418 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
419 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000420 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000421
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000422 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000424 // void * type
425 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000426
427 // nullptr type (C++0x 2.14.7)
428 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000429}
430
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000431Diagnostic &ASTContext::getDiagnostics() const {
432 return SourceMgr.getDiagnostics();
433}
434
Douglas Gregor63200642010-08-30 16:49:28 +0000435AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
436 AttrVec *&Result = DeclAttrs[D];
437 if (!Result) {
438 void *Mem = Allocate(sizeof(AttrVec));
439 Result = new (Mem) AttrVec;
440 }
441
442 return *Result;
443}
444
445/// \brief Erase the attributes corresponding to the given declaration.
446void ASTContext::eraseDeclAttrs(const Decl *D) {
447 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
448 if (Pos != DeclAttrs.end()) {
449 Pos->second->~AttrVec();
450 DeclAttrs.erase(Pos);
451 }
452}
453
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000454MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000455ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000456 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000457 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000458 = InstantiatedFromStaticDataMember.find(Var);
459 if (Pos == InstantiatedFromStaticDataMember.end())
460 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Douglas Gregor7caa6822009-07-24 20:34:43 +0000462 return Pos->second;
463}
464
Mike Stump1eb44332009-09-09 15:08:12 +0000465void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000466ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000467 TemplateSpecializationKind TSK,
468 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000469 assert(Inst->isStaticDataMember() && "Not a static data member");
470 assert(Tmpl->isStaticDataMember() && "Not a static data member");
471 assert(!InstantiatedFromStaticDataMember[Inst] &&
472 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000473 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000474 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000475}
476
John McCall7ba107a2009-11-18 02:36:19 +0000477NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000478ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000479 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000480 = InstantiatedFromUsingDecl.find(UUD);
481 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000482 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Anders Carlsson0d8df782009-08-29 19:37:28 +0000484 return Pos->second;
485}
486
487void
John McCalled976492009-12-04 22:46:56 +0000488ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
489 assert((isa<UsingDecl>(Pattern) ||
490 isa<UnresolvedUsingValueDecl>(Pattern) ||
491 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
492 "pattern decl is not a using decl");
493 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
494 InstantiatedFromUsingDecl[Inst] = Pattern;
495}
496
497UsingShadowDecl *
498ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
499 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
500 = InstantiatedFromUsingShadowDecl.find(Inst);
501 if (Pos == InstantiatedFromUsingShadowDecl.end())
502 return 0;
503
504 return Pos->second;
505}
506
507void
508ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
509 UsingShadowDecl *Pattern) {
510 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
511 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000512}
513
Anders Carlssond8b285f2009-09-01 04:26:58 +0000514FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
515 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
516 = InstantiatedFromUnnamedFieldDecl.find(Field);
517 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
518 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Anders Carlssond8b285f2009-09-01 04:26:58 +0000520 return Pos->second;
521}
522
523void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
524 FieldDecl *Tmpl) {
525 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
526 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
527 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
528 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Anders Carlssond8b285f2009-09-01 04:26:58 +0000530 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
531}
532
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000533ASTContext::overridden_cxx_method_iterator
534ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
535 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
536 = OverriddenMethods.find(Method);
537 if (Pos == OverriddenMethods.end())
538 return 0;
539
540 return Pos->second.begin();
541}
542
543ASTContext::overridden_cxx_method_iterator
544ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
545 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
546 = OverriddenMethods.find(Method);
547 if (Pos == OverriddenMethods.end())
548 return 0;
549
550 return Pos->second.end();
551}
552
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000553unsigned
554ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
555 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
556 = OverriddenMethods.find(Method);
557 if (Pos == OverriddenMethods.end())
558 return 0;
559
560 return Pos->second.size();
561}
562
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000563void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
564 const CXXMethodDecl *Overridden) {
565 OverriddenMethods[Method].push_back(Overridden);
566}
567
Chris Lattner464175b2007-07-18 17:52:12 +0000568//===----------------------------------------------------------------------===//
569// Type Sizing and Analysis
570//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000571
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000572/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
573/// scalar floating point type.
574const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000575 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000576 assert(BT && "Not a floating point type!");
577 switch (BT->getKind()) {
578 default: assert(0 && "Not a floating point type!");
579 case BuiltinType::Float: return Target.getFloatFormat();
580 case BuiltinType::Double: return Target.getDoubleFormat();
581 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
582 }
583}
584
Ken Dyck8b752f12010-01-27 17:10:57 +0000585/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000586/// specified decl. Note that bitfields do not have a valid alignment, so
587/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000588/// If @p RefAsPointee, references are treated like their underlying type
589/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000590CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000591 unsigned Align = Target.getCharWidth();
592
John McCall4081a5c2010-10-08 18:24:19 +0000593 bool UseAlignAttrOnly = false;
594 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
595 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000596
John McCall4081a5c2010-10-08 18:24:19 +0000597 // __attribute__((aligned)) can increase or decrease alignment
598 // *except* on a struct or struct member, where it only increases
599 // alignment unless 'packed' is also specified.
600 //
601 // It is an error for [[align]] to decrease alignment, so we can
602 // ignore that possibility; Sema should diagnose it.
603 if (isa<FieldDecl>(D)) {
604 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
605 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
606 } else {
607 UseAlignAttrOnly = true;
608 }
609 }
610
John McCallba4f5d52011-01-20 07:57:12 +0000611 // If we're using the align attribute only, just ignore everything
612 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000613 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000614 // do nothing
615
John McCall4081a5c2010-10-08 18:24:19 +0000616 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000617 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000618 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000619 if (RefAsPointee)
620 T = RT->getPointeeType();
621 else
622 T = getPointerType(RT->getPointeeType());
623 }
624 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000625 // Adjust alignments of declarations with array type by the
626 // large-array alignment on the target.
Rafael Espindola6deecb02010-06-04 23:15:27 +0000627 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000628 const ArrayType *arrayType;
629 if (MinWidth && (arrayType = getAsArrayType(T))) {
630 if (isa<VariableArrayType>(arrayType))
631 Align = std::max(Align, Target.getLargeArrayAlign());
632 else if (isa<ConstantArrayType>(arrayType) &&
633 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
634 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000635
John McCall3b657512011-01-19 10:06:00 +0000636 // Walk through any array types while we're at it.
637 T = getBaseElementType(arrayType);
638 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000639 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
640 }
John McCallba4f5d52011-01-20 07:57:12 +0000641
642 // Fields can be subject to extra alignment constraints, like if
643 // the field is packed, the struct is packed, or the struct has a
644 // a max-field-alignment constraint (#pragma pack). So calculate
645 // the actual alignment of the field within the struct, and then
646 // (as we're expected to) constrain that by the alignment of the type.
647 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
648 // So calculate the alignment of the field.
649 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
650
651 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000652 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000653
654 // Use the GCD of that and the offset within the record.
655 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
656 if (offset > 0) {
657 // Alignment is always a power of 2, so the GCD will be a power of 2,
658 // which means we get to do this crazy thing instead of Euclid's.
659 uint64_t lowBitOfOffset = offset & (~offset + 1);
660 if (lowBitOfOffset < fieldAlign)
661 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
662 }
663
664 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000665 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000666 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000667
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000668 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000669}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000670
John McCallea1471e2010-05-20 01:18:31 +0000671std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000672ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000673 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000674 return std::make_pair(toCharUnitsFromBits(Info.first),
675 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000676}
677
678std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000679ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000680 return getTypeInfoInChars(T.getTypePtr());
681}
682
Chris Lattnera7674d82007-07-13 22:13:22 +0000683/// getTypeSize - Return the size of the specified type, in bits. This method
684/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000685///
686/// FIXME: Pointers into different addr spaces could have different sizes and
687/// alignment requirements: getPointerInfo should take an AddrSpace, this
688/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000689std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000690ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000691 uint64_t Width=0;
692 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000693 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000694#define TYPE(Class, Base)
695#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000696#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000697#define DEPENDENT_TYPE(Class, Base) case Type::Class:
698#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000699 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000700 break;
701
Chris Lattner692233e2007-07-13 22:27:08 +0000702 case Type::FunctionNoProto:
703 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000704 // GCC extension: alignof(function) = 32 bits
705 Width = 0;
706 Align = 32;
707 break;
708
Douglas Gregor72564e72009-02-26 23:50:07 +0000709 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000710 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000711 Width = 0;
712 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
713 break;
714
Steve Narofffb22d962007-08-30 01:06:46 +0000715 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000716 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Chris Lattner98be4942008-03-05 18:54:05 +0000718 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000719 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000720 Align = EltInfo.second;
721 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000722 }
Nate Begeman213541a2008-04-18 23:10:10 +0000723 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000724 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000725 const VectorType *VT = cast<VectorType>(T);
726 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
727 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000728 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000729 // If the alignment is not a power of 2, round up to the next power of 2.
730 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000731 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000732 Align = llvm::NextPowerOf2(Align);
733 Width = llvm::RoundUpToAlignment(Width, Align);
734 }
Chris Lattner030d8842007-07-19 22:06:24 +0000735 break;
736 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000737
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000738 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000739 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000740 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000741 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000742 // GCC extension: alignof(void) = 8 bits.
743 Width = 0;
744 Align = 8;
745 break;
746
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000747 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000748 Width = Target.getBoolWidth();
749 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000750 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000751 case BuiltinType::Char_S:
752 case BuiltinType::Char_U:
753 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000754 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000755 Width = Target.getCharWidth();
756 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000757 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000758 case BuiltinType::WChar_S:
759 case BuiltinType::WChar_U:
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000760 Width = Target.getWCharWidth();
761 Align = Target.getWCharAlign();
762 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000763 case BuiltinType::Char16:
764 Width = Target.getChar16Width();
765 Align = Target.getChar16Align();
766 break;
767 case BuiltinType::Char32:
768 Width = Target.getChar32Width();
769 Align = Target.getChar32Align();
770 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000771 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000772 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000773 Width = Target.getShortWidth();
774 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000775 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000776 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000777 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000778 Width = Target.getIntWidth();
779 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000780 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000781 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000782 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000783 Width = Target.getLongWidth();
784 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000785 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000786 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000787 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000788 Width = Target.getLongLongWidth();
789 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000790 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000791 case BuiltinType::Int128:
792 case BuiltinType::UInt128:
793 Width = 128;
794 Align = 128; // int128_t is 128-bit aligned on all targets.
795 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000796 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000797 Width = Target.getFloatWidth();
798 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000799 break;
800 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000801 Width = Target.getDoubleWidth();
802 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000803 break;
804 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000805 Width = Target.getLongDoubleWidth();
806 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000807 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000808 case BuiltinType::NullPtr:
809 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
810 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000811 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000812 case BuiltinType::ObjCId:
813 case BuiltinType::ObjCClass:
814 case BuiltinType::ObjCSel:
815 Width = Target.getPointerWidth(0);
816 Align = Target.getPointerAlign(0);
817 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000818 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000819 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000820 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000821 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000822 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000823 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000824 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000825 unsigned AS = getTargetAddressSpace(
826 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff485eeff2008-09-24 15:05:44 +0000827 Width = Target.getPointerWidth(AS);
828 Align = Target.getPointerAlign(AS);
829 break;
830 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000831 case Type::LValueReference:
832 case Type::RValueReference: {
833 // alignof and sizeof should never enter this code path here, so we go
834 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000835 unsigned AS = getTargetAddressSpace(
836 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl5d484e82009-11-23 17:18:46 +0000837 Width = Target.getPointerWidth(AS);
838 Align = Target.getPointerAlign(AS);
839 break;
840 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000841 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000842 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner5426bf62008-04-07 07:01:58 +0000843 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000844 Align = Target.getPointerAlign(AS);
845 break;
846 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000847 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000848 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000849 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000850 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000851 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000852 Align = PtrDiffInfo.second;
853 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000854 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000855 case Type::Complex: {
856 // Complex types have the same alignment as their elements, but twice the
857 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000858 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000859 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000860 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000861 Align = EltInfo.second;
862 break;
863 }
John McCallc12c5bb2010-05-15 11:32:37 +0000864 case Type::ObjCObject:
865 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000866 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000867 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000868 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000869 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000870 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +0000871 break;
872 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000873 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000874 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000875 const TagType *TT = cast<TagType>(T);
876
877 if (TT->getDecl()->isInvalidDecl()) {
Chris Lattner8389eab2008-08-09 21:35:13 +0000878 Width = 1;
879 Align = 1;
880 break;
881 }
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Daniel Dunbar1d751182008-11-08 05:48:37 +0000883 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000884 return getTypeInfo(ET->getDecl()->getIntegerType());
885
Daniel Dunbar1d751182008-11-08 05:48:37 +0000886 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000887 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000888 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000889 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000890 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000891 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000892
Chris Lattner9fcfe922009-10-22 05:17:15 +0000893 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000894 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
895 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000896
Richard Smith34b41d92011-02-20 03:19:35 +0000897 case Type::Auto: {
898 const AutoType *A = cast<AutoType>(T);
899 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +0000900 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +0000901 }
902
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000903 case Type::Paren:
904 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
905
Douglas Gregor18857642009-04-30 17:32:17 +0000906 case Type::Typedef: {
907 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000908 std::pair<uint64_t, unsigned> Info
909 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +0000910 // If the typedef has an aligned attribute on it, it overrides any computed
911 // alignment we have. This violates the GCC documentation (which says that
912 // attribute(aligned) can only round up) but matches its implementation.
913 if (unsigned AttrAlign = Typedef->getMaxAlignment())
914 Align = AttrAlign;
915 else
916 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +0000917 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000918 break;
Chris Lattner71763312008-04-06 22:05:18 +0000919 }
Douglas Gregor18857642009-04-30 17:32:17 +0000920
921 case Type::TypeOfExpr:
922 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
923 .getTypePtr());
924
925 case Type::TypeOf:
926 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
927
Anders Carlsson395b4752009-06-24 19:06:50 +0000928 case Type::Decltype:
929 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
930 .getTypePtr());
931
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000932 case Type::Elaborated:
933 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000934
John McCall9d156a72011-01-06 01:58:22 +0000935 case Type::Attributed:
936 return getTypeInfo(
937 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
938
Douglas Gregor18857642009-04-30 17:32:17 +0000939 case Type::TemplateSpecialization:
Mike Stump1eb44332009-09-09 15:08:12 +0000940 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000941 "Cannot request the size of a dependent type");
942 // FIXME: this is likely to be wrong once we support template
943 // aliases, since a template alias could refer to a typedef that
944 // has an __aligned__ attribute on it.
945 return getTypeInfo(getCanonicalType(T));
946 }
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Chris Lattner464175b2007-07-18 17:52:12 +0000948 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000949 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +0000950}
951
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000952/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
953CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
954 return CharUnits::fromQuantity(BitSize / getCharWidth());
955}
956
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000957/// toBits - Convert a size in characters to a size in characters.
958int64_t ASTContext::toBits(CharUnits CharSize) const {
959 return CharSize.getQuantity() * getCharWidth();
960}
961
Ken Dyckbdc601b2009-12-22 14:23:30 +0000962/// getTypeSizeInChars - Return the size of the specified type, in characters.
963/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +0000964CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000965 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +0000966}
Jay Foad4ba2a172011-01-12 09:06:06 +0000967CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000968 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +0000969}
970
Ken Dyck16e20cc2010-01-26 17:25:18 +0000971/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +0000972/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +0000973CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000974 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +0000975}
Jay Foad4ba2a172011-01-12 09:06:06 +0000976CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000977 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +0000978}
979
Chris Lattner34ebde42009-01-27 18:08:34 +0000980/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
981/// type for the current target in bits. This can be different than the ABI
982/// alignment in cases where it is beneficial for performance to overalign
983/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +0000984unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +0000985 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +0000986
987 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +0000988 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +0000989 T = CT->getElementType().getTypePtr();
990 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
991 T->isSpecificBuiltinType(BuiltinType::LongLong))
992 return std::max(ABIAlign, (unsigned)getTypeSize(T));
993
Chris Lattner34ebde42009-01-27 18:08:34 +0000994 return ABIAlign;
995}
996
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +0000997/// ShallowCollectObjCIvars -
998/// Collect all ivars, including those synthesized, in the current class.
999///
1000void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad4ba2a172011-01-12 09:06:06 +00001001 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001002 // FIXME. This need be removed but there are two many places which
1003 // assume const-ness of ObjCInterfaceDecl
1004 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1005 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1006 Iv= Iv->getNextIvar())
1007 Ivars.push_back(Iv);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001008}
1009
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001010/// DeepCollectObjCIvars -
1011/// This routine first collects all declared, but not synthesized, ivars in
1012/// super class and then collects all ivars, including those synthesized for
1013/// current class. This routine is used for implementation of current class
1014/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001015///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001016void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1017 bool leafClass,
Jay Foad4ba2a172011-01-12 09:06:06 +00001018 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001019 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1020 DeepCollectObjCIvars(SuperClass, false, Ivars);
1021 if (!leafClass) {
1022 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1023 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001024 Ivars.push_back(*I);
1025 }
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001026 else
1027 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian98200742009-05-12 18:14:29 +00001028}
1029
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001030/// CollectInheritedProtocols - Collect all protocols in current class and
1031/// those inherited by it.
1032void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001033 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001034 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001035 // We can use protocol_iterator here instead of
1036 // all_referenced_protocol_iterator since we are walking all categories.
1037 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1038 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001039 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001040 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001041 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001042 PE = Proto->protocol_end(); P != PE; ++P) {
1043 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001044 CollectInheritedProtocols(*P, Protocols);
1045 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001046 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001047
1048 // Categories of this Interface.
1049 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1050 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1051 CollectInheritedProtocols(CDeclChain, Protocols);
1052 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1053 while (SD) {
1054 CollectInheritedProtocols(SD, Protocols);
1055 SD = SD->getSuperClass();
1056 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001057 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001058 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001059 PE = OC->protocol_end(); P != PE; ++P) {
1060 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001061 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001062 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1063 PE = Proto->protocol_end(); P != PE; ++P)
1064 CollectInheritedProtocols(*P, Protocols);
1065 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001066 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001067 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1068 PE = OP->protocol_end(); P != PE; ++P) {
1069 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001070 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001071 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1072 PE = Proto->protocol_end(); P != PE; ++P)
1073 CollectInheritedProtocols(*P, Protocols);
1074 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001075 }
1076}
1077
Jay Foad4ba2a172011-01-12 09:06:06 +00001078unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001079 unsigned count = 0;
1080 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001081 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1082 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001083 count += CDecl->ivar_size();
1084
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001085 // Count ivar defined in this class's implementation. This
1086 // includes synthesized ivars.
1087 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001088 count += ImplDecl->ivar_size();
1089
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001090 return count;
1091}
1092
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001093/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1094ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1095 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1096 I = ObjCImpls.find(D);
1097 if (I != ObjCImpls.end())
1098 return cast<ObjCImplementationDecl>(I->second);
1099 return 0;
1100}
1101/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1102ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1103 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1104 I = ObjCImpls.find(D);
1105 if (I != ObjCImpls.end())
1106 return cast<ObjCCategoryImplDecl>(I->second);
1107 return 0;
1108}
1109
1110/// \brief Set the implementation of ObjCInterfaceDecl.
1111void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1112 ObjCImplementationDecl *ImplD) {
1113 assert(IFaceD && ImplD && "Passed null params");
1114 ObjCImpls[IFaceD] = ImplD;
1115}
1116/// \brief Set the implementation of ObjCCategoryDecl.
1117void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1118 ObjCCategoryImplDecl *ImplD) {
1119 assert(CatD && ImplD && "Passed null params");
1120 ObjCImpls[CatD] = ImplD;
1121}
1122
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001123/// \brief Get the copy initialization expression of VarDecl,or NULL if
1124/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001125Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001126 assert(VD && "Passed null params");
1127 assert(VD->hasAttr<BlocksAttr>() &&
1128 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001129 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001130 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001131 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1132}
1133
1134/// \brief Set the copy inialization expression of a block var decl.
1135void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1136 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001137 assert(VD->hasAttr<BlocksAttr>() &&
1138 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001139 BlockVarCopyInits[VD] = Init;
1140}
1141
John McCalla93c9342009-12-07 02:54:59 +00001142/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001143///
John McCalla93c9342009-12-07 02:54:59 +00001144/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001145/// the TypeLoc wrappers.
1146///
1147/// \param T the type that will be the basis for type source info. This type
1148/// should refer to how the declarator was written in source code, not to
1149/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001150TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001151 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001152 if (!DataSize)
1153 DataSize = TypeLoc::getFullDataSizeForType(T);
1154 else
1155 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001156 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001157
John McCalla93c9342009-12-07 02:54:59 +00001158 TypeSourceInfo *TInfo =
1159 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1160 new (TInfo) TypeSourceInfo(T);
1161 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001162}
1163
John McCalla93c9342009-12-07 02:54:59 +00001164TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001165 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001166 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001167 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001168 return DI;
1169}
1170
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001171const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001172ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001173 return getObjCLayout(D, 0);
1174}
1175
1176const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001177ASTContext::getASTObjCImplementationLayout(
1178 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001179 return getObjCLayout(D->getClassInterface(), D);
1180}
1181
Chris Lattnera7674d82007-07-13 22:13:22 +00001182//===----------------------------------------------------------------------===//
1183// Type creation/memoization methods
1184//===----------------------------------------------------------------------===//
1185
Jay Foad4ba2a172011-01-12 09:06:06 +00001186QualType
John McCall3b657512011-01-19 10:06:00 +00001187ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1188 unsigned fastQuals = quals.getFastQualifiers();
1189 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001190
1191 // Check if we've already instantiated this type.
1192 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001193 ExtQuals::Profile(ID, baseType, quals);
1194 void *insertPos = 0;
1195 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1196 assert(eq->getQualifiers() == quals);
1197 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001198 }
1199
John McCall3b657512011-01-19 10:06:00 +00001200 // If the base type is not canonical, make the appropriate canonical type.
1201 QualType canon;
1202 if (!baseType->isCanonicalUnqualified()) {
1203 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1204 canonSplit.second.addConsistentQualifiers(quals);
1205 canon = getExtQualType(canonSplit.first, canonSplit.second);
1206
1207 // Re-find the insert position.
1208 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1209 }
1210
1211 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1212 ExtQualNodes.InsertNode(eq, insertPos);
1213 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001214}
1215
Jay Foad4ba2a172011-01-12 09:06:06 +00001216QualType
1217ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001218 QualType CanT = getCanonicalType(T);
1219 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001220 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001221
John McCall0953e762009-09-24 19:53:00 +00001222 // If we are composing extended qualifiers together, merge together
1223 // into one ExtQuals node.
1224 QualifierCollector Quals;
1225 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001226
John McCall0953e762009-09-24 19:53:00 +00001227 // If this type already has an address space specified, it cannot get
1228 // another one.
1229 assert(!Quals.hasAddressSpace() &&
1230 "Type cannot be in multiple addr spaces!");
1231 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001232
John McCall0953e762009-09-24 19:53:00 +00001233 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001234}
1235
Chris Lattnerb7d25532009-02-18 22:53:11 +00001236QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001237 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001238 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001239 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001240 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001241
John McCall7f040a92010-12-24 02:08:15 +00001242 if (const PointerType *ptr = T->getAs<PointerType>()) {
1243 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001244 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001245 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1246 return getPointerType(ResultType);
1247 }
1248 }
Mike Stump1eb44332009-09-09 15:08:12 +00001249
John McCall0953e762009-09-24 19:53:00 +00001250 // If we are composing extended qualifiers together, merge together
1251 // into one ExtQuals node.
1252 QualifierCollector Quals;
1253 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001254
John McCall0953e762009-09-24 19:53:00 +00001255 // If this type already has an ObjCGC specified, it cannot get
1256 // another one.
1257 assert(!Quals.hasObjCGCAttr() &&
1258 "Type cannot have multiple ObjCGCs!");
1259 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001260
John McCall0953e762009-09-24 19:53:00 +00001261 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001262}
Chris Lattnera7674d82007-07-13 22:13:22 +00001263
John McCalle6a365d2010-12-19 02:44:49 +00001264const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1265 FunctionType::ExtInfo Info) {
1266 if (T->getExtInfo() == Info)
1267 return T;
1268
1269 QualType Result;
1270 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1271 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1272 } else {
1273 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1274 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1275 EPI.ExtInfo = Info;
1276 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1277 FPT->getNumArgs(), EPI);
1278 }
1279
1280 return cast<FunctionType>(Result.getTypePtr());
1281}
1282
Reid Spencer5f016e22007-07-11 17:01:13 +00001283/// getComplexType - Return the uniqued reference to the type for a complex
1284/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001285QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001286 // Unique pointers, to guarantee there is only one pointer of a particular
1287 // structure.
1288 llvm::FoldingSetNodeID ID;
1289 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 void *InsertPos = 0;
1292 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1293 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 // If the pointee type isn't canonical, this won't be a canonical type either,
1296 // so fill in the canonical type field.
1297 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001298 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001299 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 // Get the new insert position for the node we care about.
1302 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001303 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001304 }
John McCall6b304a02009-09-24 23:30:46 +00001305 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 Types.push_back(New);
1307 ComplexTypes.InsertNode(New, InsertPos);
1308 return QualType(New, 0);
1309}
1310
Reid Spencer5f016e22007-07-11 17:01:13 +00001311/// getPointerType - Return the uniqued reference to the type for a pointer to
1312/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001313QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 // Unique pointers, to guarantee there is only one pointer of a particular
1315 // structure.
1316 llvm::FoldingSetNodeID ID;
1317 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 void *InsertPos = 0;
1320 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1321 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Reid Spencer5f016e22007-07-11 17:01:13 +00001323 // If the pointee type isn't canonical, this won't be a canonical type either,
1324 // so fill in the canonical type field.
1325 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001326 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001327 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Reid Spencer5f016e22007-07-11 17:01:13 +00001329 // Get the new insert position for the node we care about.
1330 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001331 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001332 }
John McCall6b304a02009-09-24 23:30:46 +00001333 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001334 Types.push_back(New);
1335 PointerTypes.InsertNode(New, InsertPos);
1336 return QualType(New, 0);
1337}
1338
Mike Stump1eb44332009-09-09 15:08:12 +00001339/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001340/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001341QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001342 assert(T->isFunctionType() && "block of function types only");
1343 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001344 // structure.
1345 llvm::FoldingSetNodeID ID;
1346 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Steve Naroff5618bd42008-08-27 16:04:49 +00001348 void *InsertPos = 0;
1349 if (BlockPointerType *PT =
1350 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1351 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001352
1353 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001354 // type either so fill in the canonical type field.
1355 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001356 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001357 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001358
Steve Naroff5618bd42008-08-27 16:04:49 +00001359 // Get the new insert position for the node we care about.
1360 BlockPointerType *NewIP =
1361 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001362 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001363 }
John McCall6b304a02009-09-24 23:30:46 +00001364 BlockPointerType *New
1365 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001366 Types.push_back(New);
1367 BlockPointerTypes.InsertNode(New, InsertPos);
1368 return QualType(New, 0);
1369}
1370
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001371/// getLValueReferenceType - Return the uniqued reference to the type for an
1372/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001373QualType
1374ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001375 // Unique pointers, to guarantee there is only one pointer of a particular
1376 // structure.
1377 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001378 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001379
1380 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001381 if (LValueReferenceType *RT =
1382 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001383 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001384
John McCall54e14c42009-10-22 22:37:11 +00001385 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1386
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 // If the referencee type isn't canonical, this won't be a canonical type
1388 // either, so fill in the canonical type field.
1389 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001390 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1391 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1392 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001393
Reid Spencer5f016e22007-07-11 17:01:13 +00001394 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001395 LValueReferenceType *NewIP =
1396 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001397 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001398 }
1399
John McCall6b304a02009-09-24 23:30:46 +00001400 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001401 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1402 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001403 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001404 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001405
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001406 return QualType(New, 0);
1407}
1408
1409/// getRValueReferenceType - Return the uniqued reference to the type for an
1410/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001411QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001412 // Unique pointers, to guarantee there is only one pointer of a particular
1413 // structure.
1414 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001415 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001416
1417 void *InsertPos = 0;
1418 if (RValueReferenceType *RT =
1419 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1420 return QualType(RT, 0);
1421
John McCall54e14c42009-10-22 22:37:11 +00001422 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1423
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001424 // If the referencee type isn't canonical, this won't be a canonical type
1425 // either, so fill in the canonical type field.
1426 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001427 if (InnerRef || !T.isCanonical()) {
1428 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1429 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001430
1431 // Get the new insert position for the node we care about.
1432 RValueReferenceType *NewIP =
1433 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001434 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001435 }
1436
John McCall6b304a02009-09-24 23:30:46 +00001437 RValueReferenceType *New
1438 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001439 Types.push_back(New);
1440 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 return QualType(New, 0);
1442}
1443
Sebastian Redlf30208a2009-01-24 21:16:55 +00001444/// getMemberPointerType - Return the uniqued reference to the type for a
1445/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001446QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001447 // Unique pointers, to guarantee there is only one pointer of a particular
1448 // structure.
1449 llvm::FoldingSetNodeID ID;
1450 MemberPointerType::Profile(ID, T, Cls);
1451
1452 void *InsertPos = 0;
1453 if (MemberPointerType *PT =
1454 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1455 return QualType(PT, 0);
1456
1457 // If the pointee or class type isn't canonical, this won't be a canonical
1458 // type either, so fill in the canonical type field.
1459 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001460 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001461 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1462
1463 // Get the new insert position for the node we care about.
1464 MemberPointerType *NewIP =
1465 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001466 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001467 }
John McCall6b304a02009-09-24 23:30:46 +00001468 MemberPointerType *New
1469 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001470 Types.push_back(New);
1471 MemberPointerTypes.InsertNode(New, InsertPos);
1472 return QualType(New, 0);
1473}
1474
Mike Stump1eb44332009-09-09 15:08:12 +00001475/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001476/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001477QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001478 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001479 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001480 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001481 assert((EltTy->isDependentType() ||
1482 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001483 "Constant array of VLAs is illegal!");
1484
Chris Lattner38aeec72009-05-13 04:12:56 +00001485 // Convert the array size into a canonical width matching the pointer size for
1486 // the target.
1487 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001488 ArySize =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001489 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Reid Spencer5f016e22007-07-11 17:01:13 +00001491 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001492 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001495 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001496 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001498
John McCall3b657512011-01-19 10:06:00 +00001499 // If the element type isn't canonical or has qualifiers, this won't
1500 // be a canonical type either, so fill in the canonical type field.
1501 QualType Canon;
1502 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1503 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1504 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001505 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001506 Canon = getQualifiedType(Canon, canonSplit.second);
1507
Reid Spencer5f016e22007-07-11 17:01:13 +00001508 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001509 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001510 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001511 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001512 }
Mike Stump1eb44332009-09-09 15:08:12 +00001513
John McCall6b304a02009-09-24 23:30:46 +00001514 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001515 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001516 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001517 Types.push_back(New);
1518 return QualType(New, 0);
1519}
1520
John McCallce889032011-01-18 08:40:38 +00001521/// getVariableArrayDecayedType - Turns the given type, which may be
1522/// variably-modified, into the corresponding type with all the known
1523/// sizes replaced with [*].
1524QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1525 // Vastly most common case.
1526 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001527
John McCallce889032011-01-18 08:40:38 +00001528 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001529
John McCallce889032011-01-18 08:40:38 +00001530 SplitQualType split = type.getSplitDesugaredType();
1531 const Type *ty = split.first;
1532 switch (ty->getTypeClass()) {
1533#define TYPE(Class, Base)
1534#define ABSTRACT_TYPE(Class, Base)
1535#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1536#include "clang/AST/TypeNodes.def"
1537 llvm_unreachable("didn't desugar past all non-canonical types?");
1538
1539 // These types should never be variably-modified.
1540 case Type::Builtin:
1541 case Type::Complex:
1542 case Type::Vector:
1543 case Type::ExtVector:
1544 case Type::DependentSizedExtVector:
1545 case Type::ObjCObject:
1546 case Type::ObjCInterface:
1547 case Type::ObjCObjectPointer:
1548 case Type::Record:
1549 case Type::Enum:
1550 case Type::UnresolvedUsing:
1551 case Type::TypeOfExpr:
1552 case Type::TypeOf:
1553 case Type::Decltype:
1554 case Type::DependentName:
1555 case Type::InjectedClassName:
1556 case Type::TemplateSpecialization:
1557 case Type::DependentTemplateSpecialization:
1558 case Type::TemplateTypeParm:
1559 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001560 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001561 case Type::PackExpansion:
1562 llvm_unreachable("type should never be variably-modified");
1563
1564 // These types can be variably-modified but should never need to
1565 // further decay.
1566 case Type::FunctionNoProto:
1567 case Type::FunctionProto:
1568 case Type::BlockPointer:
1569 case Type::MemberPointer:
1570 return type;
1571
1572 // These types can be variably-modified. All these modifications
1573 // preserve structure except as noted by comments.
1574 // TODO: if we ever care about optimizing VLAs, there are no-op
1575 // optimizations available here.
1576 case Type::Pointer:
1577 result = getPointerType(getVariableArrayDecayedType(
1578 cast<PointerType>(ty)->getPointeeType()));
1579 break;
1580
1581 case Type::LValueReference: {
1582 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1583 result = getLValueReferenceType(
1584 getVariableArrayDecayedType(lv->getPointeeType()),
1585 lv->isSpelledAsLValue());
1586 break;
1587 }
1588
1589 case Type::RValueReference: {
1590 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1591 result = getRValueReferenceType(
1592 getVariableArrayDecayedType(lv->getPointeeType()));
1593 break;
1594 }
1595
1596 case Type::ConstantArray: {
1597 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1598 result = getConstantArrayType(
1599 getVariableArrayDecayedType(cat->getElementType()),
1600 cat->getSize(),
1601 cat->getSizeModifier(),
1602 cat->getIndexTypeCVRQualifiers());
1603 break;
1604 }
1605
1606 case Type::DependentSizedArray: {
1607 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1608 result = getDependentSizedArrayType(
1609 getVariableArrayDecayedType(dat->getElementType()),
1610 dat->getSizeExpr(),
1611 dat->getSizeModifier(),
1612 dat->getIndexTypeCVRQualifiers(),
1613 dat->getBracketsRange());
1614 break;
1615 }
1616
1617 // Turn incomplete types into [*] types.
1618 case Type::IncompleteArray: {
1619 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1620 result = getVariableArrayType(
1621 getVariableArrayDecayedType(iat->getElementType()),
1622 /*size*/ 0,
1623 ArrayType::Normal,
1624 iat->getIndexTypeCVRQualifiers(),
1625 SourceRange());
1626 break;
1627 }
1628
1629 // Turn VLA types into [*] types.
1630 case Type::VariableArray: {
1631 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1632 result = getVariableArrayType(
1633 getVariableArrayDecayedType(vat->getElementType()),
1634 /*size*/ 0,
1635 ArrayType::Star,
1636 vat->getIndexTypeCVRQualifiers(),
1637 vat->getBracketsRange());
1638 break;
1639 }
1640 }
1641
1642 // Apply the top-level qualifiers from the original.
1643 return getQualifiedType(result, split.second);
1644}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001645
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001646/// getVariableArrayType - Returns a non-unique reference to the type for a
1647/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001648QualType ASTContext::getVariableArrayType(QualType EltTy,
1649 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001650 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001651 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001652 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001653 // Since we don't unique expressions, it isn't possible to unique VLA's
1654 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001655 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001656
John McCall3b657512011-01-19 10:06:00 +00001657 // Be sure to pull qualifiers off the element type.
1658 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1659 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1660 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001661 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001662 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001663 }
1664
John McCall6b304a02009-09-24 23:30:46 +00001665 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001666 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001667
1668 VariableArrayTypes.push_back(New);
1669 Types.push_back(New);
1670 return QualType(New, 0);
1671}
1672
Douglas Gregor898574e2008-12-05 23:32:09 +00001673/// getDependentSizedArrayType - Returns a non-unique reference to
1674/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001675/// type.
John McCall3b657512011-01-19 10:06:00 +00001676QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1677 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001678 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001679 unsigned elementTypeQuals,
1680 SourceRange brackets) const {
1681 assert((!numElements || numElements->isTypeDependent() ||
1682 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001683 "Size must be type- or value-dependent!");
1684
John McCall3b657512011-01-19 10:06:00 +00001685 // Dependently-sized array types that do not have a specified number
1686 // of elements will have their sizes deduced from a dependent
1687 // initializer. We do no canonicalization here at all, which is okay
1688 // because they can't be used in most locations.
1689 if (!numElements) {
1690 DependentSizedArrayType *newType
1691 = new (*this, TypeAlignment)
1692 DependentSizedArrayType(*this, elementType, QualType(),
1693 numElements, ASM, elementTypeQuals,
1694 brackets);
1695 Types.push_back(newType);
1696 return QualType(newType, 0);
1697 }
1698
1699 // Otherwise, we actually build a new type every time, but we
1700 // also build a canonical type.
1701
1702 SplitQualType canonElementType = getCanonicalType(elementType).split();
1703
1704 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001705 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001706 DependentSizedArrayType::Profile(ID, *this,
1707 QualType(canonElementType.first, 0),
1708 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001709
John McCall3b657512011-01-19 10:06:00 +00001710 // Look for an existing type with these properties.
1711 DependentSizedArrayType *canonTy =
1712 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001713
John McCall3b657512011-01-19 10:06:00 +00001714 // If we don't have one, build one.
1715 if (!canonTy) {
1716 canonTy = new (*this, TypeAlignment)
1717 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1718 QualType(), numElements, ASM, elementTypeQuals,
1719 brackets);
1720 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1721 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001722 }
1723
John McCall3b657512011-01-19 10:06:00 +00001724 // Apply qualifiers from the element type to the array.
1725 QualType canon = getQualifiedType(QualType(canonTy,0),
1726 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001727
John McCall3b657512011-01-19 10:06:00 +00001728 // If we didn't need extra canonicalization for the element type,
1729 // then just use that as our result.
1730 if (QualType(canonElementType.first, 0) == elementType)
1731 return canon;
1732
1733 // Otherwise, we need to build a type which follows the spelling
1734 // of the element type.
1735 DependentSizedArrayType *sugaredType
1736 = new (*this, TypeAlignment)
1737 DependentSizedArrayType(*this, elementType, canon, numElements,
1738 ASM, elementTypeQuals, brackets);
1739 Types.push_back(sugaredType);
1740 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001741}
1742
John McCall3b657512011-01-19 10:06:00 +00001743QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001744 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001745 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001746 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001747 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001748
John McCall3b657512011-01-19 10:06:00 +00001749 void *insertPos = 0;
1750 if (IncompleteArrayType *iat =
1751 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1752 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001753
1754 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001755 // either, so fill in the canonical type field. We also have to pull
1756 // qualifiers off the element type.
1757 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001758
John McCall3b657512011-01-19 10:06:00 +00001759 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1760 SplitQualType canonSplit = getCanonicalType(elementType).split();
1761 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1762 ASM, elementTypeQuals);
1763 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001764
1765 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001766 IncompleteArrayType *existing =
1767 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1768 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001769 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001770
John McCall3b657512011-01-19 10:06:00 +00001771 IncompleteArrayType *newType = new (*this, TypeAlignment)
1772 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001773
John McCall3b657512011-01-19 10:06:00 +00001774 IncompleteArrayTypes.InsertNode(newType, insertPos);
1775 Types.push_back(newType);
1776 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001777}
1778
Steve Naroff73322922007-07-18 18:00:27 +00001779/// getVectorType - Return the unique reference to a vector type of
1780/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001781QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001782 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001783 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 // Check if we've already instantiated a vector of this type.
1786 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001787 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001788
Reid Spencer5f016e22007-07-11 17:01:13 +00001789 void *InsertPos = 0;
1790 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1791 return QualType(VTP, 0);
1792
1793 // If the element type isn't canonical, this won't be a canonical type either,
1794 // so fill in the canonical type field.
1795 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001796 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001797 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Reid Spencer5f016e22007-07-11 17:01:13 +00001799 // Get the new insert position for the node we care about.
1800 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001801 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 }
John McCall6b304a02009-09-24 23:30:46 +00001803 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001804 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001805 VectorTypes.InsertNode(New, InsertPos);
1806 Types.push_back(New);
1807 return QualType(New, 0);
1808}
1809
Nate Begeman213541a2008-04-18 23:10:10 +00001810/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001811/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001812QualType
1813ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall3b657512011-01-19 10:06:00 +00001814 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001815
Steve Naroff73322922007-07-18 18:00:27 +00001816 // Check if we've already instantiated a vector of this type.
1817 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001818 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001819 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001820 void *InsertPos = 0;
1821 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1822 return QualType(VTP, 0);
1823
1824 // If the element type isn't canonical, this won't be a canonical type either,
1825 // so fill in the canonical type field.
1826 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001827 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001828 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Steve Naroff73322922007-07-18 18:00:27 +00001830 // Get the new insert position for the node we care about.
1831 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001832 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001833 }
John McCall6b304a02009-09-24 23:30:46 +00001834 ExtVectorType *New = new (*this, TypeAlignment)
1835 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001836 VectorTypes.InsertNode(New, InsertPos);
1837 Types.push_back(New);
1838 return QualType(New, 0);
1839}
1840
Jay Foad4ba2a172011-01-12 09:06:06 +00001841QualType
1842ASTContext::getDependentSizedExtVectorType(QualType vecType,
1843 Expr *SizeExpr,
1844 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001845 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001846 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001847 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001849 void *InsertPos = 0;
1850 DependentSizedExtVectorType *Canon
1851 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1852 DependentSizedExtVectorType *New;
1853 if (Canon) {
1854 // We already have a canonical version of this array type; use it as
1855 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001856 New = new (*this, TypeAlignment)
1857 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1858 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001859 } else {
1860 QualType CanonVecTy = getCanonicalType(vecType);
1861 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001862 New = new (*this, TypeAlignment)
1863 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1864 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001865
1866 DependentSizedExtVectorType *CanonCheck
1867 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1868 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1869 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001870 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1871 } else {
1872 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1873 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001874 New = new (*this, TypeAlignment)
1875 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001876 }
1877 }
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001879 Types.push_back(New);
1880 return QualType(New, 0);
1881}
1882
Douglas Gregor72564e72009-02-26 23:50:07 +00001883/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001884///
Jay Foad4ba2a172011-01-12 09:06:06 +00001885QualType
1886ASTContext::getFunctionNoProtoType(QualType ResultTy,
1887 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00001888 const CallingConv DefaultCC = Info.getCC();
1889 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1890 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00001891 // Unique functions, to guarantee there is only one function of a particular
1892 // structure.
1893 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001894 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Reid Spencer5f016e22007-07-11 17:01:13 +00001896 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001897 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001898 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001899 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Reid Spencer5f016e22007-07-11 17:01:13 +00001901 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001902 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001903 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001904 Canonical =
1905 getFunctionNoProtoType(getCanonicalType(ResultTy),
1906 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Reid Spencer5f016e22007-07-11 17:01:13 +00001908 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001909 FunctionNoProtoType *NewIP =
1910 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001911 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001912 }
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Roman Divackycfe9af22011-03-01 17:40:53 +00001914 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00001915 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00001916 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00001917 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001918 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 return QualType(New, 0);
1920}
1921
1922/// getFunctionType - Return a normal function type with a typed argument
1923/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00001924QualType
1925ASTContext::getFunctionType(QualType ResultTy,
1926 const QualType *ArgArray, unsigned NumArgs,
1927 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001928 // Unique functions, to guarantee there is only one function of a particular
1929 // structure.
1930 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001931 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00001932
1933 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001934 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001935 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001936 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001937
1938 // Determine whether the type being created is already canonical or not.
Sebastian Redl8b5b4092011-03-06 10:52:04 +00001939 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001940 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001941 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00001942 isCanonical = false;
1943
Roman Divackycfe9af22011-03-01 17:40:53 +00001944 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
1945 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1946 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00001947
Reid Spencer5f016e22007-07-11 17:01:13 +00001948 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00001949 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00001950 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00001951 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001952 llvm::SmallVector<QualType, 16> CanonicalArgs;
1953 CanonicalArgs.reserve(NumArgs);
1954 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001955 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00001956
John McCalle23cf432010-12-14 08:05:40 +00001957 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00001958 CanonicalEPI.ExceptionSpecType = EST_None;
1959 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00001960 CanonicalEPI.ExtInfo
1961 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
1962
Chris Lattnerf52ab252008-04-06 22:59:24 +00001963 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00001964 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00001965 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00001966
Reid Spencer5f016e22007-07-11 17:01:13 +00001967 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001968 FunctionProtoType *NewIP =
1969 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001970 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001971 }
Sebastian Redl465226e2009-05-27 22:11:52 +00001972
Douglas Gregor72564e72009-02-26 23:50:07 +00001973 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00001974 // for two variable size arrays (for parameter and exception types) at the
Sebastian Redl60618fa2011-03-12 11:50:43 +00001975 // end of them. Instead of the exception types, there could be a noexcept
1976 // expression and a context pointer.
John McCalle23cf432010-12-14 08:05:40 +00001977 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00001978 NumArgs * sizeof(QualType);
1979 if (EPI.ExceptionSpecType == EST_Dynamic)
1980 Size += EPI.NumExceptions * sizeof(QualType);
1981 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001982 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00001983 }
John McCalle23cf432010-12-14 08:05:40 +00001984 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00001985 FunctionProtoType::ExtProtoInfo newEPI = EPI;
1986 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001987 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00001988 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00001989 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001990 return QualType(FTP, 0);
1991}
1992
John McCall3cb0ebd2010-03-10 03:28:59 +00001993#ifndef NDEBUG
1994static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1995 if (!isa<CXXRecordDecl>(D)) return false;
1996 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1997 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1998 return true;
1999 if (RD->getDescribedClassTemplate() &&
2000 !isa<ClassTemplateSpecializationDecl>(RD))
2001 return true;
2002 return false;
2003}
2004#endif
2005
2006/// getInjectedClassNameType - Return the unique reference to the
2007/// injected class name type for the specified templated declaration.
2008QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002009 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002010 assert(NeedsInjectedClassNameType(Decl));
2011 if (Decl->TypeForDecl) {
2012 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00002013 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002014 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2015 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2016 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2017 } else {
John McCallf4c73712011-01-19 06:33:43 +00002018 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002019 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002020 Decl->TypeForDecl = newType;
2021 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002022 }
2023 return QualType(Decl->TypeForDecl, 0);
2024}
2025
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002026/// getTypeDeclType - Return the unique reference to the type for the
2027/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002028QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002029 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002030 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002031
John McCall19c85762010-02-16 03:57:14 +00002032 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002033 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002034
John McCallbecb8d52010-03-10 06:48:02 +00002035 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2036 "Template type parameter types are always available.");
2037
John McCall19c85762010-02-16 03:57:14 +00002038 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002039 assert(!Record->getPreviousDeclaration() &&
2040 "struct/union has previous declaration");
2041 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002042 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002043 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002044 assert(!Enum->getPreviousDeclaration() &&
2045 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002046 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002047 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002048 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002049 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2050 Decl->TypeForDecl = newType;
2051 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002052 } else
John McCallbecb8d52010-03-10 06:48:02 +00002053 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002054
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002055 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002056}
2057
Reid Spencer5f016e22007-07-11 17:01:13 +00002058/// getTypedefType - Return the unique reference to the type for the
2059/// specified typename decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002060QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002061ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002062 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002064 if (Canonical.isNull())
2065 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002066 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002067 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002068 Decl->TypeForDecl = newType;
2069 Types.push_back(newType);
2070 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002071}
2072
Jay Foad4ba2a172011-01-12 09:06:06 +00002073QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002074 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2075
2076 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2077 if (PrevDecl->TypeForDecl)
2078 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2079
John McCallf4c73712011-01-19 06:33:43 +00002080 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2081 Decl->TypeForDecl = newType;
2082 Types.push_back(newType);
2083 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002084}
2085
Jay Foad4ba2a172011-01-12 09:06:06 +00002086QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002087 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2088
2089 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2090 if (PrevDecl->TypeForDecl)
2091 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2092
John McCallf4c73712011-01-19 06:33:43 +00002093 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2094 Decl->TypeForDecl = newType;
2095 Types.push_back(newType);
2096 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002097}
2098
John McCall9d156a72011-01-06 01:58:22 +00002099QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2100 QualType modifiedType,
2101 QualType equivalentType) {
2102 llvm::FoldingSetNodeID id;
2103 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2104
2105 void *insertPos = 0;
2106 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2107 if (type) return QualType(type, 0);
2108
2109 QualType canon = getCanonicalType(equivalentType);
2110 type = new (*this, TypeAlignment)
2111 AttributedType(canon, attrKind, modifiedType, equivalentType);
2112
2113 Types.push_back(type);
2114 AttributedTypes.InsertNode(type, insertPos);
2115
2116 return QualType(type, 0);
2117}
2118
2119
John McCall49a832b2009-10-18 09:09:24 +00002120/// \brief Retrieve a substitution-result type.
2121QualType
2122ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002123 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002124 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002125 && "replacement types must always be canonical");
2126
2127 llvm::FoldingSetNodeID ID;
2128 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2129 void *InsertPos = 0;
2130 SubstTemplateTypeParmType *SubstParm
2131 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2132
2133 if (!SubstParm) {
2134 SubstParm = new (*this, TypeAlignment)
2135 SubstTemplateTypeParmType(Parm, Replacement);
2136 Types.push_back(SubstParm);
2137 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2138 }
2139
2140 return QualType(SubstParm, 0);
2141}
2142
Douglas Gregorc3069d62011-01-14 02:55:32 +00002143/// \brief Retrieve a
2144QualType ASTContext::getSubstTemplateTypeParmPackType(
2145 const TemplateTypeParmType *Parm,
2146 const TemplateArgument &ArgPack) {
2147#ifndef NDEBUG
2148 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2149 PEnd = ArgPack.pack_end();
2150 P != PEnd; ++P) {
2151 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2152 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2153 }
2154#endif
2155
2156 llvm::FoldingSetNodeID ID;
2157 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2158 void *InsertPos = 0;
2159 if (SubstTemplateTypeParmPackType *SubstParm
2160 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2161 return QualType(SubstParm, 0);
2162
2163 QualType Canon;
2164 if (!Parm->isCanonicalUnqualified()) {
2165 Canon = getCanonicalType(QualType(Parm, 0));
2166 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2167 ArgPack);
2168 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2169 }
2170
2171 SubstTemplateTypeParmPackType *SubstParm
2172 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2173 ArgPack);
2174 Types.push_back(SubstParm);
2175 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2176 return QualType(SubstParm, 0);
2177}
2178
Douglas Gregorfab9d672009-02-05 23:33:38 +00002179/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002180/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002181/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002182QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002183 bool ParameterPack,
Jay Foad4ba2a172011-01-12 09:06:06 +00002184 IdentifierInfo *Name) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002185 llvm::FoldingSetNodeID ID;
Douglas Gregorefed5c82010-06-16 15:23:05 +00002186 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002187 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002188 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002189 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2190
2191 if (TypeParm)
2192 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Douglas Gregorefed5c82010-06-16 15:23:05 +00002194 if (Name) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002195 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorefed5c82010-06-16 15:23:05 +00002196 TypeParm = new (*this, TypeAlignment)
2197 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002198
2199 TemplateTypeParmType *TypeCheck
2200 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2201 assert(!TypeCheck && "Template type parameter canonical type broken");
2202 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002203 } else
John McCall6b304a02009-09-24 23:30:46 +00002204 TypeParm = new (*this, TypeAlignment)
2205 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002206
2207 Types.push_back(TypeParm);
2208 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2209
2210 return QualType(TypeParm, 0);
2211}
2212
John McCall3cb0ebd2010-03-10 03:28:59 +00002213TypeSourceInfo *
2214ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2215 SourceLocation NameLoc,
2216 const TemplateArgumentListInfo &Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002217 QualType CanonType) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002218 assert(!Name.getAsDependentTemplateName() &&
2219 "No dependent template names here!");
John McCall3cb0ebd2010-03-10 03:28:59 +00002220 QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
2221
2222 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2223 TemplateSpecializationTypeLoc TL
2224 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2225 TL.setTemplateNameLoc(NameLoc);
2226 TL.setLAngleLoc(Args.getLAngleLoc());
2227 TL.setRAngleLoc(Args.getRAngleLoc());
2228 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2229 TL.setArgLocInfo(i, Args[i].getLocInfo());
2230 return DI;
2231}
2232
Mike Stump1eb44332009-09-09 15:08:12 +00002233QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002234ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002235 const TemplateArgumentListInfo &Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002236 QualType Canon) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002237 assert(!Template.getAsDependentTemplateName() &&
2238 "No dependent template names here!");
2239
John McCalld5532b62009-11-23 01:53:49 +00002240 unsigned NumArgs = Args.size();
2241
John McCall833ca992009-10-29 08:12:44 +00002242 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2243 ArgVec.reserve(NumArgs);
2244 for (unsigned i = 0; i != NumArgs; ++i)
2245 ArgVec.push_back(Args[i].getArgument());
2246
John McCall31f17ec2010-04-27 00:57:59 +00002247 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
John McCall71d74bc2010-06-13 09:25:03 +00002248 Canon);
John McCall833ca992009-10-29 08:12:44 +00002249}
2250
2251QualType
2252ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002253 const TemplateArgument *Args,
2254 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002255 QualType Canon) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002256 assert(!Template.getAsDependentTemplateName() &&
2257 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002258 // Look through qualified template names.
2259 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2260 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002261
Douglas Gregorb88e8882009-07-30 17:40:51 +00002262 if (!Canon.isNull())
2263 Canon = getCanonicalType(Canon);
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002264 else
2265 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs);
Douglas Gregorfc705b82009-02-26 22:19:44 +00002266
Douglas Gregor1275ae02009-07-28 23:00:59 +00002267 // Allocate the (non-canonical) template specialization type, but don't
2268 // try to unique it: these types typically have location information that
2269 // we don't unique and don't want to lose.
Mike Stump1eb44332009-09-09 15:08:12 +00002270 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
Douglas Gregor40808ce2009-03-09 23:48:35 +00002271 sizeof(TemplateArgument) * NumArgs),
John McCall6b304a02009-09-24 23:30:46 +00002272 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002273 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002274 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002275 Args, NumArgs,
Douglas Gregor828e2262009-07-29 16:09:57 +00002276 Canon);
Mike Stump1eb44332009-09-09 15:08:12 +00002277
Douglas Gregor55f6b142009-02-09 18:46:07 +00002278 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002279 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002280}
2281
Mike Stump1eb44332009-09-09 15:08:12 +00002282QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002283ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2284 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002285 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002286 assert(!Template.getAsDependentTemplateName() &&
2287 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002288 // Look through qualified template names.
2289 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2290 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002291
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002292 // Build the canonical template specialization type.
2293 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2294 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2295 CanonArgs.reserve(NumArgs);
2296 for (unsigned I = 0; I != NumArgs; ++I)
2297 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2298
2299 // Determine whether this canonical template specialization type already
2300 // exists.
2301 llvm::FoldingSetNodeID ID;
2302 TemplateSpecializationType::Profile(ID, CanonTemplate,
2303 CanonArgs.data(), NumArgs, *this);
2304
2305 void *InsertPos = 0;
2306 TemplateSpecializationType *Spec
2307 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2308
2309 if (!Spec) {
2310 // Allocate a new canonical template specialization type.
2311 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2312 sizeof(TemplateArgument) * NumArgs),
2313 TypeAlignment);
2314 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2315 CanonArgs.data(), NumArgs,
2316 QualType());
2317 Types.push_back(Spec);
2318 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2319 }
2320
2321 assert(Spec->isDependentType() &&
2322 "Non-dependent template-id type must have a canonical type");
2323 return QualType(Spec, 0);
2324}
2325
2326QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002327ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2328 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002329 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002330 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002331 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002332
2333 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002334 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002335 if (T)
2336 return QualType(T, 0);
2337
Douglas Gregor789b1f62010-02-04 18:10:26 +00002338 QualType Canon = NamedType;
2339 if (!Canon.isCanonical()) {
2340 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002341 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2342 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002343 (void)CheckT;
2344 }
2345
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002346 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002347 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002348 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002349 return QualType(T, 0);
2350}
2351
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002352QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002353ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002354 llvm::FoldingSetNodeID ID;
2355 ParenType::Profile(ID, InnerType);
2356
2357 void *InsertPos = 0;
2358 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2359 if (T)
2360 return QualType(T, 0);
2361
2362 QualType Canon = InnerType;
2363 if (!Canon.isCanonical()) {
2364 Canon = getCanonicalType(InnerType);
2365 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2366 assert(!CheckT && "Paren canonical type broken");
2367 (void)CheckT;
2368 }
2369
2370 T = new (*this) ParenType(InnerType, Canon);
2371 Types.push_back(T);
2372 ParenTypes.InsertNode(T, InsertPos);
2373 return QualType(T, 0);
2374}
2375
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002376QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2377 NestedNameSpecifier *NNS,
2378 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002379 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002380 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2381
2382 if (Canon.isNull()) {
2383 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002384 ElaboratedTypeKeyword CanonKeyword = Keyword;
2385 if (Keyword == ETK_None)
2386 CanonKeyword = ETK_Typename;
2387
2388 if (CanonNNS != NNS || CanonKeyword != Keyword)
2389 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002390 }
2391
2392 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002393 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002394
2395 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002396 DependentNameType *T
2397 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002398 if (T)
2399 return QualType(T, 0);
2400
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002401 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002402 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002403 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002404 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002405}
2406
Mike Stump1eb44332009-09-09 15:08:12 +00002407QualType
John McCall33500952010-06-11 00:33:02 +00002408ASTContext::getDependentTemplateSpecializationType(
2409 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002410 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002411 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002412 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002413 // TODO: avoid this copy
2414 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2415 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2416 ArgCopy.push_back(Args[I].getArgument());
2417 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2418 ArgCopy.size(),
2419 ArgCopy.data());
2420}
2421
2422QualType
2423ASTContext::getDependentTemplateSpecializationType(
2424 ElaboratedTypeKeyword Keyword,
2425 NestedNameSpecifier *NNS,
2426 const IdentifierInfo *Name,
2427 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002428 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002429 assert((!NNS || NNS->isDependent()) &&
2430 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002431
Douglas Gregor789b1f62010-02-04 18:10:26 +00002432 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002433 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2434 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002435
2436 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002437 DependentTemplateSpecializationType *T
2438 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002439 if (T)
2440 return QualType(T, 0);
2441
John McCall33500952010-06-11 00:33:02 +00002442 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002443
John McCall33500952010-06-11 00:33:02 +00002444 ElaboratedTypeKeyword CanonKeyword = Keyword;
2445 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2446
2447 bool AnyNonCanonArgs = false;
2448 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2449 for (unsigned I = 0; I != NumArgs; ++I) {
2450 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2451 if (!CanonArgs[I].structurallyEquals(Args[I]))
2452 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002453 }
2454
John McCall33500952010-06-11 00:33:02 +00002455 QualType Canon;
2456 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2457 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2458 Name, NumArgs,
2459 CanonArgs.data());
2460
2461 // Find the insert position again.
2462 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2463 }
2464
2465 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2466 sizeof(TemplateArgument) * NumArgs),
2467 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002468 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002469 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002470 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002471 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002472 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002473}
2474
Douglas Gregorcded4f62011-01-14 17:04:44 +00002475QualType ASTContext::getPackExpansionType(QualType Pattern,
2476 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002477 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002478 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002479
2480 assert(Pattern->containsUnexpandedParameterPack() &&
2481 "Pack expansions must expand one or more parameter packs");
2482 void *InsertPos = 0;
2483 PackExpansionType *T
2484 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2485 if (T)
2486 return QualType(T, 0);
2487
2488 QualType Canon;
2489 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002490 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002491
2492 // Find the insert position again.
2493 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2494 }
2495
Douglas Gregorcded4f62011-01-14 17:04:44 +00002496 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002497 Types.push_back(T);
2498 PackExpansionTypes.InsertNode(T, InsertPos);
2499 return QualType(T, 0);
2500}
2501
Chris Lattner88cb27a2008-04-07 04:56:42 +00002502/// CmpProtocolNames - Comparison predicate for sorting protocols
2503/// alphabetically.
2504static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2505 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002506 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002507}
2508
John McCallc12c5bb2010-05-15 11:32:37 +00002509static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002510 unsigned NumProtocols) {
2511 if (NumProtocols == 0) return true;
2512
2513 for (unsigned i = 1; i != NumProtocols; ++i)
2514 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2515 return false;
2516 return true;
2517}
2518
2519static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002520 unsigned &NumProtocols) {
2521 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002522
Chris Lattner88cb27a2008-04-07 04:56:42 +00002523 // Sort protocols, keyed by name.
2524 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2525
2526 // Remove duplicates.
2527 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2528 NumProtocols = ProtocolsEnd-Protocols;
2529}
2530
John McCallc12c5bb2010-05-15 11:32:37 +00002531QualType ASTContext::getObjCObjectType(QualType BaseType,
2532 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002533 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002534 // If the base type is an interface and there aren't any protocols
2535 // to add, then the interface type will do just fine.
2536 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2537 return BaseType;
2538
2539 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002540 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002541 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002542 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002543 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2544 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002545
John McCallc12c5bb2010-05-15 11:32:37 +00002546 // Build the canonical type, which has the canonical base type and
2547 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002548 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002549 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2550 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2551 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002552 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2553 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002554 unsigned UniqueCount = NumProtocols;
2555
John McCall54e14c42009-10-22 22:37:11 +00002556 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002557 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2558 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002559 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002560 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2561 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002562 }
2563
2564 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002565 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2566 }
2567
2568 unsigned Size = sizeof(ObjCObjectTypeImpl);
2569 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2570 void *Mem = Allocate(Size, TypeAlignment);
2571 ObjCObjectTypeImpl *T =
2572 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2573
2574 Types.push_back(T);
2575 ObjCObjectTypes.InsertNode(T, InsertPos);
2576 return QualType(T, 0);
2577}
2578
2579/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2580/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002581QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002582 llvm::FoldingSetNodeID ID;
2583 ObjCObjectPointerType::Profile(ID, ObjectT);
2584
2585 void *InsertPos = 0;
2586 if (ObjCObjectPointerType *QT =
2587 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2588 return QualType(QT, 0);
2589
2590 // Find the canonical object type.
2591 QualType Canonical;
2592 if (!ObjectT.isCanonical()) {
2593 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2594
2595 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002596 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2597 }
2598
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002599 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002600 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2601 ObjCObjectPointerType *QType =
2602 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002603
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002604 Types.push_back(QType);
2605 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002606 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002607}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002608
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002609/// getObjCInterfaceType - Return the unique reference to the type for the
2610/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad4ba2a172011-01-12 09:06:06 +00002611QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002612 if (Decl->TypeForDecl)
2613 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002614
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002615 // FIXME: redeclarations?
2616 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2617 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2618 Decl->TypeForDecl = T;
2619 Types.push_back(T);
2620 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002621}
2622
Douglas Gregor72564e72009-02-26 23:50:07 +00002623/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2624/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002625/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002626/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002627/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002628QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002629 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002630 if (tofExpr->isTypeDependent()) {
2631 llvm::FoldingSetNodeID ID;
2632 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002633
Douglas Gregorb1975722009-07-30 23:18:24 +00002634 void *InsertPos = 0;
2635 DependentTypeOfExprType *Canon
2636 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2637 if (Canon) {
2638 // We already have a "canonical" version of an identical, dependent
2639 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002640 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002641 QualType((TypeOfExprType*)Canon, 0));
2642 }
2643 else {
2644 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002645 Canon
2646 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002647 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2648 toe = Canon;
2649 }
2650 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002651 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002652 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002653 }
Steve Naroff9752f252007-08-01 18:02:17 +00002654 Types.push_back(toe);
2655 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002656}
2657
Steve Naroff9752f252007-08-01 18:02:17 +00002658/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2659/// TypeOfType AST's. The only motivation to unique these nodes would be
2660/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002661/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002662/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002663QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002664 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002665 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002666 Types.push_back(tot);
2667 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002668}
2669
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002670/// getDecltypeForExpr - Given an expr, will return the decltype for that
2671/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002672static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002673 if (e->isTypeDependent())
2674 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002675
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002676 // If e is an id expression or a class member access, decltype(e) is defined
2677 // as the type of the entity named by e.
2678 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2679 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2680 return VD->getType();
2681 }
2682 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2683 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2684 return FD->getType();
2685 }
2686 // If e is a function call or an invocation of an overloaded operator,
2687 // (parentheses around e are ignored), decltype(e) is defined as the
2688 // return type of that function.
2689 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2690 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002691
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002692 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002693
2694 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002695 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002696 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002697 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002698
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002699 return T;
2700}
2701
Anders Carlsson395b4752009-06-24 19:06:50 +00002702/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2703/// DecltypeType AST's. The only motivation to unique these nodes would be
2704/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002705/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002706/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002707QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002708 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002709 if (e->isTypeDependent()) {
2710 llvm::FoldingSetNodeID ID;
2711 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002712
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002713 void *InsertPos = 0;
2714 DependentDecltypeType *Canon
2715 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2716 if (Canon) {
2717 // We already have a "canonical" version of an equivalent, dependent
2718 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002719 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002720 QualType((DecltypeType*)Canon, 0));
2721 }
2722 else {
2723 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002724 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002725 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2726 dt = Canon;
2727 }
2728 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002729 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002730 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002731 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002732 Types.push_back(dt);
2733 return QualType(dt, 0);
2734}
2735
Richard Smith483b9f32011-02-21 20:05:19 +00002736/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002737QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002738 void *InsertPos = 0;
2739 if (!DeducedType.isNull()) {
2740 // Look in the folding set for an existing type.
2741 llvm::FoldingSetNodeID ID;
2742 AutoType::Profile(ID, DeducedType);
2743 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2744 return QualType(AT, 0);
2745 }
2746
2747 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2748 Types.push_back(AT);
2749 if (InsertPos)
2750 AutoTypes.InsertNode(AT, InsertPos);
2751 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002752}
2753
Reid Spencer5f016e22007-07-11 17:01:13 +00002754/// getTagDeclType - Return the unique reference to the type for the
2755/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00002756QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00002757 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002758 // FIXME: What is the design on getTagDeclType when it requires casting
2759 // away const? mutable?
2760 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002761}
2762
Mike Stump1eb44332009-09-09 15:08:12 +00002763/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2764/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2765/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002766CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002767 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002768}
2769
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002770/// getSignedWCharType - Return the type of "signed wchar_t".
2771/// Used when in C++, as a GCC extension.
2772QualType ASTContext::getSignedWCharType() const {
2773 // FIXME: derive from "Target" ?
2774 return WCharTy;
2775}
2776
2777/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2778/// Used when in C++, as a GCC extension.
2779QualType ASTContext::getUnsignedWCharType() const {
2780 // FIXME: derive from "Target" ?
2781 return UnsignedIntTy;
2782}
2783
Chris Lattner8b9023b2007-07-13 03:05:23 +00002784/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2785/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2786QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002787 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002788}
2789
Chris Lattnere6327742008-04-02 05:18:44 +00002790//===----------------------------------------------------------------------===//
2791// Type Operators
2792//===----------------------------------------------------------------------===//
2793
Jay Foad4ba2a172011-01-12 09:06:06 +00002794CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00002795 // Push qualifiers into arrays, and then discard any remaining
2796 // qualifiers.
2797 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002798 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002799 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002800 QualType Result;
2801 if (isa<ArrayType>(Ty)) {
2802 Result = getArrayDecayedType(QualType(Ty,0));
2803 } else if (isa<FunctionType>(Ty)) {
2804 Result = getPointerType(QualType(Ty, 0));
2805 } else {
2806 Result = QualType(Ty, 0);
2807 }
2808
2809 return CanQualType::CreateUnsafe(Result);
2810}
2811
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002812
John McCall62c28c82011-01-18 07:41:22 +00002813QualType ASTContext::getUnqualifiedArrayType(QualType type,
2814 Qualifiers &quals) {
2815 SplitQualType splitType = type.getSplitUnqualifiedType();
2816
2817 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2818 // the unqualified desugared type and then drops it on the floor.
2819 // We then have to strip that sugar back off with
2820 // getUnqualifiedDesugaredType(), which is silly.
2821 const ArrayType *AT =
2822 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2823
2824 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00002825 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00002826 quals = splitType.second;
2827 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002828 }
2829
John McCall62c28c82011-01-18 07:41:22 +00002830 // Otherwise, recurse on the array's element type.
2831 QualType elementType = AT->getElementType();
2832 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2833
2834 // If that didn't change the element type, AT has no qualifiers, so we
2835 // can just use the results in splitType.
2836 if (elementType == unqualElementType) {
2837 assert(quals.empty()); // from the recursive call
2838 quals = splitType.second;
2839 return QualType(splitType.first, 0);
2840 }
2841
2842 // Otherwise, add in the qualifiers from the outermost type, then
2843 // build the type back up.
2844 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002845
Douglas Gregor9dadd942010-05-17 18:45:21 +00002846 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002847 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002848 CAT->getSizeModifier(), 0);
2849 }
2850
Douglas Gregor9dadd942010-05-17 18:45:21 +00002851 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002852 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002853 }
2854
Douglas Gregor9dadd942010-05-17 18:45:21 +00002855 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002856 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00002857 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00002858 VAT->getSizeModifier(),
2859 VAT->getIndexTypeCVRQualifiers(),
2860 VAT->getBracketsRange());
2861 }
2862
2863 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00002864 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002865 DSAT->getSizeModifier(), 0,
2866 SourceRange());
2867}
2868
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002869/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2870/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2871/// they point to and return true. If T1 and T2 aren't pointer types
2872/// or pointer-to-member types, or if they are not similar at this
2873/// level, returns false and leaves T1 and T2 unchanged. Top-level
2874/// qualifiers on T1 and T2 are ignored. This function will typically
2875/// be called in a loop that successively "unwraps" pointer and
2876/// pointer-to-member types to compare them at each level.
2877bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2878 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2879 *T2PtrType = T2->getAs<PointerType>();
2880 if (T1PtrType && T2PtrType) {
2881 T1 = T1PtrType->getPointeeType();
2882 T2 = T2PtrType->getPointeeType();
2883 return true;
2884 }
2885
2886 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2887 *T2MPType = T2->getAs<MemberPointerType>();
2888 if (T1MPType && T2MPType &&
2889 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2890 QualType(T2MPType->getClass(), 0))) {
2891 T1 = T1MPType->getPointeeType();
2892 T2 = T2MPType->getPointeeType();
2893 return true;
2894 }
2895
2896 if (getLangOptions().ObjC1) {
2897 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2898 *T2OPType = T2->getAs<ObjCObjectPointerType>();
2899 if (T1OPType && T2OPType) {
2900 T1 = T1OPType->getPointeeType();
2901 T2 = T2OPType->getPointeeType();
2902 return true;
2903 }
2904 }
2905
2906 // FIXME: Block pointers, too?
2907
2908 return false;
2909}
2910
Jay Foad4ba2a172011-01-12 09:06:06 +00002911DeclarationNameInfo
2912ASTContext::getNameForTemplate(TemplateName Name,
2913 SourceLocation NameLoc) const {
John McCall80ad16f2009-11-24 18:42:40 +00002914 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00002915 // DNInfo work in progress: CHECKME: what about DNLoc?
2916 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
2917
John McCall80ad16f2009-11-24 18:42:40 +00002918 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002919 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00002920 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00002921 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
2922 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002923 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00002924 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
2925 // DNInfo work in progress: FIXME: source locations?
2926 DeclarationNameLoc DNLoc;
2927 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
2928 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
2929 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002930 }
2931 }
2932
John McCall0bd6feb2009-12-02 08:04:21 +00002933 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2934 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00002935 // DNInfo work in progress: CHECKME: what about DNLoc?
2936 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00002937}
2938
Jay Foad4ba2a172011-01-12 09:06:06 +00002939TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002940 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2941 if (TemplateTemplateParmDecl *TTP
2942 = dyn_cast<TemplateTemplateParmDecl>(Template))
2943 Template = getCanonicalTemplateTemplateParmDecl(TTP);
2944
2945 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002946 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00002947 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002948
Douglas Gregor1aee05d2011-01-15 06:45:20 +00002949 if (SubstTemplateTemplateParmPackStorage *SubstPack
2950 = Name.getAsSubstTemplateTemplateParmPack()) {
2951 TemplateTemplateParmDecl *CanonParam
2952 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
2953 TemplateArgument CanonArgPack
2954 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
2955 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
2956 }
2957
John McCall0bd6feb2009-12-02 08:04:21 +00002958 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00002959
Douglas Gregor25a3ef72009-05-07 06:41:52 +00002960 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2961 assert(DTN && "Non-dependent template names must refer to template decls.");
2962 return DTN->CanonicalTemplateName;
2963}
2964
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002965bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2966 X = getCanonicalTemplateName(X);
2967 Y = getCanonicalTemplateName(Y);
2968 return X.getAsVoidPointer() == Y.getAsVoidPointer();
2969}
2970
Mike Stump1eb44332009-09-09 15:08:12 +00002971TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00002972ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00002973 switch (Arg.getKind()) {
2974 case TemplateArgument::Null:
2975 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002976
Douglas Gregor1275ae02009-07-28 23:00:59 +00002977 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00002978 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00002979
Douglas Gregor1275ae02009-07-28 23:00:59 +00002980 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00002981 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002982
Douglas Gregor788cd062009-11-11 01:00:40 +00002983 case TemplateArgument::Template:
2984 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00002985
2986 case TemplateArgument::TemplateExpansion:
2987 return TemplateArgument(getCanonicalTemplateName(
2988 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00002989 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00002990
Douglas Gregor1275ae02009-07-28 23:00:59 +00002991 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00002992 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00002993 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002994
Douglas Gregor1275ae02009-07-28 23:00:59 +00002995 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00002996 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00002997
Douglas Gregor1275ae02009-07-28 23:00:59 +00002998 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00002999 if (Arg.pack_size() == 0)
3000 return Arg;
3001
Douglas Gregor910f8002010-11-07 23:05:16 +00003002 TemplateArgument *CanonArgs
3003 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003004 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003005 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003006 AEnd = Arg.pack_end();
3007 A != AEnd; (void)++A, ++Idx)
3008 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003009
Douglas Gregor910f8002010-11-07 23:05:16 +00003010 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003011 }
3012 }
3013
3014 // Silence GCC warning
3015 assert(false && "Unhandled template argument kind");
3016 return TemplateArgument();
3017}
3018
Douglas Gregord57959a2009-03-27 23:10:48 +00003019NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003020ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003021 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003022 return 0;
3023
3024 switch (NNS->getKind()) {
3025 case NestedNameSpecifier::Identifier:
3026 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003027 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003028 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3029 NNS->getAsIdentifier());
3030
3031 case NestedNameSpecifier::Namespace:
3032 // A namespace is canonical; build a nested-name-specifier with
3033 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003034 return NestedNameSpecifier::Create(*this, 0,
3035 NNS->getAsNamespace()->getOriginalNamespace());
3036
3037 case NestedNameSpecifier::NamespaceAlias:
3038 // A namespace is canonical; build a nested-name-specifier with
3039 // this namespace and no prefix.
3040 return NestedNameSpecifier::Create(*this, 0,
3041 NNS->getAsNamespaceAlias()->getNamespace()
3042 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003043
3044 case NestedNameSpecifier::TypeSpec:
3045 case NestedNameSpecifier::TypeSpecWithTemplate: {
3046 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003047
3048 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3049 // break it apart into its prefix and identifier, then reconsititute those
3050 // as the canonical nested-name-specifier. This is required to canonicalize
3051 // a dependent nested-name-specifier involving typedefs of dependent-name
3052 // types, e.g.,
3053 // typedef typename T::type T1;
3054 // typedef typename T1::type T2;
3055 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3056 NestedNameSpecifier *Prefix
3057 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3058 return NestedNameSpecifier::Create(*this, Prefix,
3059 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3060 }
3061
Douglas Gregor643f8432010-11-04 00:14:23 +00003062 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003063 if (const DependentTemplateSpecializationType *DTST
3064 = T->getAs<DependentTemplateSpecializationType>()) {
3065 NestedNameSpecifier *Prefix
3066 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003067
3068 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3069 Prefix, DTST->getIdentifier(),
3070 DTST->getNumArgs(),
3071 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003072 T = getCanonicalType(T);
3073 }
3074
John McCall3b657512011-01-19 10:06:00 +00003075 return NestedNameSpecifier::Create(*this, 0, false,
3076 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003077 }
3078
3079 case NestedNameSpecifier::Global:
3080 // The global specifier is canonical and unique.
3081 return NNS;
3082 }
3083
3084 // Required to silence a GCC warning
3085 return 0;
3086}
3087
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003088
Jay Foad4ba2a172011-01-12 09:06:06 +00003089const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003090 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003091 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003092 // Handle the common positive case fast.
3093 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3094 return AT;
3095 }
Mike Stump1eb44332009-09-09 15:08:12 +00003096
John McCall0953e762009-09-24 19:53:00 +00003097 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003098 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003099 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003100
John McCall0953e762009-09-24 19:53:00 +00003101 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003102 // implements C99 6.7.3p8: "If the specification of an array type includes
3103 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003104
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003105 // If we get here, we either have type qualifiers on the type, or we have
3106 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003107 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003108
John McCall3b657512011-01-19 10:06:00 +00003109 SplitQualType split = T.getSplitDesugaredType();
3110 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003111
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003112 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003113 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3114 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003115 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003116
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003117 // Otherwise, we have an array and we have qualifiers on it. Push the
3118 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003119 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003120
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003121 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3122 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3123 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003124 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003125 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3126 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3127 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003128 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003129
Mike Stump1eb44332009-09-09 15:08:12 +00003130 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003131 = dyn_cast<DependentSizedArrayType>(ATy))
3132 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003133 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003134 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003135 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003136 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003137 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003138
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003139 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003140 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003141 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003142 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003143 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003144 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003145}
3146
Chris Lattnere6327742008-04-02 05:18:44 +00003147/// getArrayDecayedType - Return the properly qualified result of decaying the
3148/// specified array type to a pointer. This operation is non-trivial when
3149/// handling typedefs etc. The canonical type of "T" must be an array type,
3150/// this returns a pointer to a properly qualified element of the array.
3151///
3152/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003153QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003154 // Get the element type with 'getAsArrayType' so that we don't lose any
3155 // typedefs in the element type of the array. This also handles propagation
3156 // of type qualifiers from the array type into the element type if present
3157 // (C99 6.7.3p8).
3158 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3159 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003160
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003161 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003162
3163 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003164 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003165}
3166
John McCall3b657512011-01-19 10:06:00 +00003167QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3168 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003169}
3170
John McCall3b657512011-01-19 10:06:00 +00003171QualType ASTContext::getBaseElementType(QualType type) const {
3172 Qualifiers qs;
3173 while (true) {
3174 SplitQualType split = type.getSplitDesugaredType();
3175 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3176 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003177
John McCall3b657512011-01-19 10:06:00 +00003178 type = array->getElementType();
3179 qs.addConsistentQualifiers(split.second);
3180 }
Mike Stump1eb44332009-09-09 15:08:12 +00003181
John McCall3b657512011-01-19 10:06:00 +00003182 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003183}
3184
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003185/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003186uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003187ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3188 uint64_t ElementCount = 1;
3189 do {
3190 ElementCount *= CA->getSize().getZExtValue();
3191 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3192 } while (CA);
3193 return ElementCount;
3194}
3195
Reid Spencer5f016e22007-07-11 17:01:13 +00003196/// getFloatingRank - Return a relative rank for floating point types.
3197/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003198static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003199 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003200 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003201
John McCall183700f2009-09-21 23:43:11 +00003202 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3203 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00003204 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003205 case BuiltinType::Float: return FloatRank;
3206 case BuiltinType::Double: return DoubleRank;
3207 case BuiltinType::LongDouble: return LongDoubleRank;
3208 }
3209}
3210
Mike Stump1eb44332009-09-09 15:08:12 +00003211/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3212/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003213/// 'typeDomain' is a real floating point or complex type.
3214/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003215QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3216 QualType Domain) const {
3217 FloatingRank EltRank = getFloatingRank(Size);
3218 if (Domain->isComplexType()) {
3219 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00003220 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003221 case FloatRank: return FloatComplexTy;
3222 case DoubleRank: return DoubleComplexTy;
3223 case LongDoubleRank: return LongDoubleComplexTy;
3224 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003225 }
Chris Lattner1361b112008-04-06 23:58:54 +00003226
3227 assert(Domain->isRealFloatingType() && "Unknown domain!");
3228 switch (EltRank) {
3229 default: assert(0 && "getFloatingRank(): illegal value for rank");
3230 case FloatRank: return FloatTy;
3231 case DoubleRank: return DoubleTy;
3232 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003233 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003234}
3235
Chris Lattner7cfeb082008-04-06 23:55:33 +00003236/// getFloatingTypeOrder - Compare the rank of the two specified floating
3237/// point types, ignoring the domain of the type (i.e. 'double' ==
3238/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003239/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003240int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003241 FloatingRank LHSR = getFloatingRank(LHS);
3242 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003243
Chris Lattnera75cea32008-04-06 23:38:49 +00003244 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003245 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003246 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003247 return 1;
3248 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003249}
3250
Chris Lattnerf52ab252008-04-06 22:59:24 +00003251/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3252/// routine will assert if passed a built-in type that isn't an integer or enum,
3253/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003254unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003255 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCallf4c73712011-01-19 06:33:43 +00003256 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00003257 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00003258
Chris Lattner3f59c972010-12-25 23:25:43 +00003259 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3260 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmana3426752009-07-05 23:44:27 +00003261 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3262
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003263 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3264 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3265
3266 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3267 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3268
Chris Lattnerf52ab252008-04-06 22:59:24 +00003269 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00003270 default: assert(0 && "getIntegerRank(): not a built-in integer");
3271 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003272 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003273 case BuiltinType::Char_S:
3274 case BuiltinType::Char_U:
3275 case BuiltinType::SChar:
3276 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003277 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003278 case BuiltinType::Short:
3279 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003280 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003281 case BuiltinType::Int:
3282 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003283 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003284 case BuiltinType::Long:
3285 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003286 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003287 case BuiltinType::LongLong:
3288 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003289 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003290 case BuiltinType::Int128:
3291 case BuiltinType::UInt128:
3292 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003293 }
3294}
3295
Eli Friedman04e83572009-08-20 04:21:42 +00003296/// \brief Whether this is a promotable bitfield reference according
3297/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3298///
3299/// \returns the type this bit-field will promote to, or NULL if no
3300/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003301QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003302 if (E->isTypeDependent() || E->isValueDependent())
3303 return QualType();
3304
Eli Friedman04e83572009-08-20 04:21:42 +00003305 FieldDecl *Field = E->getBitField();
3306 if (!Field)
3307 return QualType();
3308
3309 QualType FT = Field->getType();
3310
3311 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3312 uint64_t BitWidth = BitWidthAP.getZExtValue();
3313 uint64_t IntSize = getTypeSize(IntTy);
3314 // GCC extension compatibility: if the bit-field size is less than or equal
3315 // to the size of int, it gets promoted no matter what its type is.
3316 // For instance, unsigned long bf : 4 gets promoted to signed int.
3317 if (BitWidth < IntSize)
3318 return IntTy;
3319
3320 if (BitWidth == IntSize)
3321 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3322
3323 // Types bigger than int are not subject to promotions, and therefore act
3324 // like the base type.
3325 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3326 // is ridiculous.
3327 return QualType();
3328}
3329
Eli Friedmana95d7572009-08-19 07:44:53 +00003330/// getPromotedIntegerType - Returns the type that Promotable will
3331/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3332/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003333QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003334 assert(!Promotable.isNull());
3335 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003336 if (const EnumType *ET = Promotable->getAs<EnumType>())
3337 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003338 if (Promotable->isSignedIntegerType())
3339 return IntTy;
3340 uint64_t PromotableSize = getTypeSize(Promotable);
3341 uint64_t IntSize = getTypeSize(IntTy);
3342 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3343 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3344}
3345
Mike Stump1eb44332009-09-09 15:08:12 +00003346/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003347/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003348/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003349int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003350 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3351 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003352 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003353
Chris Lattnerf52ab252008-04-06 22:59:24 +00003354 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3355 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003356
Chris Lattner7cfeb082008-04-06 23:55:33 +00003357 unsigned LHSRank = getIntegerRank(LHSC);
3358 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003359
Chris Lattner7cfeb082008-04-06 23:55:33 +00003360 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3361 if (LHSRank == RHSRank) return 0;
3362 return LHSRank > RHSRank ? 1 : -1;
3363 }
Mike Stump1eb44332009-09-09 15:08:12 +00003364
Chris Lattner7cfeb082008-04-06 23:55:33 +00003365 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3366 if (LHSUnsigned) {
3367 // If the unsigned [LHS] type is larger, return it.
3368 if (LHSRank >= RHSRank)
3369 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003370
Chris Lattner7cfeb082008-04-06 23:55:33 +00003371 // If the signed type can represent all values of the unsigned type, it
3372 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003373 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003374 return -1;
3375 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003376
Chris Lattner7cfeb082008-04-06 23:55:33 +00003377 // If the unsigned [RHS] type is larger, return it.
3378 if (RHSRank >= LHSRank)
3379 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003380
Chris Lattner7cfeb082008-04-06 23:55:33 +00003381 // If the signed type can represent all values of the unsigned type, it
3382 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003383 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003384 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003385}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003386
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003387static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003388CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3389 DeclContext *DC, IdentifierInfo *Id) {
3390 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003391 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003392 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003393 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003394 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003395}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003396
Mike Stump1eb44332009-09-09 15:08:12 +00003397// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003398QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003399 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003400 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003401 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003402 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003403 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003404
Anders Carlssonf06273f2007-11-19 00:25:30 +00003405 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003406
Anders Carlsson71993dd2007-08-17 05:31:46 +00003407 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003408 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003409 // int flags;
3410 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003411 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003412 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003413 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003414 FieldTypes[3] = LongTy;
3415
Anders Carlsson71993dd2007-08-17 05:31:46 +00003416 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003417 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003418 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003419 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003420 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003421 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003422 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003423 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003424 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003425 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003426 }
3427
Douglas Gregor838db382010-02-11 01:19:42 +00003428 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003429 }
Mike Stump1eb44332009-09-09 15:08:12 +00003430
Anders Carlsson71993dd2007-08-17 05:31:46 +00003431 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003432}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003433
Douglas Gregor319ac892009-04-23 22:29:11 +00003434void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003435 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003436 assert(Rec && "Invalid CFConstantStringType");
3437 CFConstantStringTypeDecl = Rec->getDecl();
3438}
3439
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003440// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003441QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003442 if (!NSConstantStringTypeDecl) {
3443 NSConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003444 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003445 &Idents.get("__builtin_NSString"));
3446 NSConstantStringTypeDecl->startDefinition();
3447
3448 QualType FieldTypes[3];
3449
3450 // const int *isa;
3451 FieldTypes[0] = getPointerType(IntTy.withConst());
3452 // const char *str;
3453 FieldTypes[1] = getPointerType(CharTy.withConst());
3454 // unsigned int length;
3455 FieldTypes[2] = UnsignedIntTy;
3456
3457 // Create fields
3458 for (unsigned i = 0; i < 3; ++i) {
3459 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003460 SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003461 SourceLocation(), 0,
3462 FieldTypes[i], /*TInfo=*/0,
3463 /*BitWidth=*/0,
3464 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003465 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003466 NSConstantStringTypeDecl->addDecl(Field);
3467 }
3468
3469 NSConstantStringTypeDecl->completeDefinition();
3470 }
3471
3472 return getTagDeclType(NSConstantStringTypeDecl);
3473}
3474
3475void ASTContext::setNSConstantStringType(QualType T) {
3476 const RecordType *Rec = T->getAs<RecordType>();
3477 assert(Rec && "Invalid NSConstantStringType");
3478 NSConstantStringTypeDecl = Rec->getDecl();
3479}
3480
Jay Foad4ba2a172011-01-12 09:06:06 +00003481QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003482 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003483 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003484 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003485 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003486 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003487
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003488 QualType FieldTypes[] = {
3489 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003490 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003491 getPointerType(UnsignedLongTy),
3492 getConstantArrayType(UnsignedLongTy,
3493 llvm::APInt(32, 5), ArrayType::Normal, 0)
3494 };
Mike Stump1eb44332009-09-09 15:08:12 +00003495
Douglas Gregor44b43212008-12-11 16:49:14 +00003496 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003497 FieldDecl *Field = FieldDecl::Create(*this,
3498 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003499 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003500 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003501 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003502 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003503 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003504 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003505 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003506 }
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Douglas Gregor838db382010-02-11 01:19:42 +00003508 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003509 }
Mike Stump1eb44332009-09-09 15:08:12 +00003510
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003511 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3512}
3513
Jay Foad4ba2a172011-01-12 09:06:06 +00003514QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003515 if (BlockDescriptorType)
3516 return getTagDeclType(BlockDescriptorType);
3517
3518 RecordDecl *T;
3519 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003520 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003521 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003522 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003523
3524 QualType FieldTypes[] = {
3525 UnsignedLongTy,
3526 UnsignedLongTy,
3527 };
3528
3529 const char *FieldNames[] = {
3530 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003531 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003532 };
3533
3534 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003535 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003536 SourceLocation(),
3537 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003538 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003539 /*BitWidth=*/0,
3540 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003541 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003542 T->addDecl(Field);
3543 }
3544
Douglas Gregor838db382010-02-11 01:19:42 +00003545 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003546
3547 BlockDescriptorType = T;
3548
3549 return getTagDeclType(BlockDescriptorType);
3550}
3551
3552void ASTContext::setBlockDescriptorType(QualType T) {
3553 const RecordType *Rec = T->getAs<RecordType>();
3554 assert(Rec && "Invalid BlockDescriptorType");
3555 BlockDescriptorType = Rec->getDecl();
3556}
3557
Jay Foad4ba2a172011-01-12 09:06:06 +00003558QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003559 if (BlockDescriptorExtendedType)
3560 return getTagDeclType(BlockDescriptorExtendedType);
3561
3562 RecordDecl *T;
3563 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003564 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003565 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003566 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003567
3568 QualType FieldTypes[] = {
3569 UnsignedLongTy,
3570 UnsignedLongTy,
3571 getPointerType(VoidPtrTy),
3572 getPointerType(VoidPtrTy)
3573 };
3574
3575 const char *FieldNames[] = {
3576 "reserved",
3577 "Size",
3578 "CopyFuncPtr",
3579 "DestroyFuncPtr"
3580 };
3581
3582 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003583 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003584 SourceLocation(),
3585 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003586 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003587 /*BitWidth=*/0,
3588 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003589 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003590 T->addDecl(Field);
3591 }
3592
Douglas Gregor838db382010-02-11 01:19:42 +00003593 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003594
3595 BlockDescriptorExtendedType = T;
3596
3597 return getTagDeclType(BlockDescriptorExtendedType);
3598}
3599
3600void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3601 const RecordType *Rec = T->getAs<RecordType>();
3602 assert(Rec && "Invalid BlockDescriptorType");
3603 BlockDescriptorExtendedType = Rec->getDecl();
3604}
3605
Jay Foad4ba2a172011-01-12 09:06:06 +00003606bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003607 if (Ty->isBlockPointerType())
3608 return true;
3609 if (isObjCNSObjectType(Ty))
3610 return true;
3611 if (Ty->isObjCObjectPointerType())
3612 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003613 if (getLangOptions().CPlusPlus) {
3614 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3615 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3616 return RD->hasConstCopyConstructor(*this);
3617
3618 }
3619 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003620 return false;
3621}
3622
Jay Foad4ba2a172011-01-12 09:06:06 +00003623QualType
3624ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003625 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003626 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003627 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003628 // unsigned int __flags;
3629 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003630 // void *__copy_helper; // as needed
3631 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003632 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003633 // } *
3634
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003635 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3636
3637 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003638 llvm::SmallString<36> Name;
3639 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3640 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003641 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003642 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003643 T->startDefinition();
3644 QualType Int32Ty = IntTy;
3645 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3646 QualType FieldTypes[] = {
3647 getPointerType(VoidPtrTy),
3648 getPointerType(getTagDeclType(T)),
3649 Int32Ty,
3650 Int32Ty,
3651 getPointerType(VoidPtrTy),
3652 getPointerType(VoidPtrTy),
3653 Ty
3654 };
3655
Daniel Dunbar4087f272010-08-17 22:39:59 +00003656 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003657 "__isa",
3658 "__forwarding",
3659 "__flags",
3660 "__size",
3661 "__copy_helper",
3662 "__destroy_helper",
3663 DeclName,
3664 };
3665
3666 for (size_t i = 0; i < 7; ++i) {
3667 if (!HasCopyAndDispose && i >=4 && i <= 5)
3668 continue;
3669 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003670 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003671 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003672 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003673 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003674 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003675 T->addDecl(Field);
3676 }
3677
Douglas Gregor838db382010-02-11 01:19:42 +00003678 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003679
3680 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003681}
3682
Douglas Gregor319ac892009-04-23 22:29:11 +00003683void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003684 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003685 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3686 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3687}
3688
Anders Carlssone8c49532007-10-29 06:33:42 +00003689// This returns true if a type has been typedefed to BOOL:
3690// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003691static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003692 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003693 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3694 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003695
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003696 return false;
3697}
3698
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003699/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003700/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003701CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck199c3d62010-01-11 17:06:35 +00003702 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003703
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003704 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003705 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003706 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003707 // Treat arrays as pointers, since that's how they're passed in.
3708 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003709 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003710 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003711}
3712
3713static inline
3714std::string charUnitsToString(const CharUnits &CU) {
3715 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003716}
3717
John McCall6b5a61b2011-02-07 10:33:21 +00003718/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003719/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00003720std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3721 std::string S;
3722
David Chisnall5e530af2009-11-17 19:33:30 +00003723 const BlockDecl *Decl = Expr->getBlockDecl();
3724 QualType BlockTy =
3725 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3726 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003727 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003728 // Compute size of all parameters.
3729 // Start with computing size of a pointer in number of bytes.
3730 // FIXME: There might(should) be a better way of doing this computation!
3731 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003732 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3733 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003734 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003735 E = Decl->param_end(); PI != E; ++PI) {
3736 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003737 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003738 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003739 ParmOffset += sz;
3740 }
3741 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003742 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003743 // Block pointer and offset.
3744 S += "@?0";
3745 ParmOffset = PtrSize;
3746
3747 // Argument types.
3748 ParmOffset = PtrSize;
3749 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3750 Decl->param_end(); PI != E; ++PI) {
3751 ParmVarDecl *PVDecl = *PI;
3752 QualType PType = PVDecl->getOriginalType();
3753 if (const ArrayType *AT =
3754 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3755 // Use array's original type only if it has known number of
3756 // elements.
3757 if (!isa<ConstantArrayType>(AT))
3758 PType = PVDecl->getType();
3759 } else if (PType->isFunctionType())
3760 PType = PVDecl->getType();
3761 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003762 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003763 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003764 }
John McCall6b5a61b2011-02-07 10:33:21 +00003765
3766 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00003767}
3768
David Chisnall5389f482010-12-30 14:05:53 +00003769void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3770 std::string& S) {
3771 // Encode result type.
3772 getObjCEncodingForType(Decl->getResultType(), S);
3773 CharUnits ParmOffset;
3774 // Compute size of all parameters.
3775 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3776 E = Decl->param_end(); PI != E; ++PI) {
3777 QualType PType = (*PI)->getType();
3778 CharUnits sz = getObjCEncodingTypeSize(PType);
3779 assert (sz.isPositive() &&
3780 "getObjCEncodingForMethodDecl - Incomplete param type");
3781 ParmOffset += sz;
3782 }
3783 S += charUnitsToString(ParmOffset);
3784 ParmOffset = CharUnits::Zero();
3785
3786 // Argument types.
3787 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3788 E = Decl->param_end(); PI != E; ++PI) {
3789 ParmVarDecl *PVDecl = *PI;
3790 QualType PType = PVDecl->getOriginalType();
3791 if (const ArrayType *AT =
3792 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3793 // Use array's original type only if it has known number of
3794 // elements.
3795 if (!isa<ConstantArrayType>(AT))
3796 PType = PVDecl->getType();
3797 } else if (PType->isFunctionType())
3798 PType = PVDecl->getType();
3799 getObjCEncodingForType(PType, S);
3800 S += charUnitsToString(ParmOffset);
3801 ParmOffset += getObjCEncodingTypeSize(PType);
3802 }
3803}
3804
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003805/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003806/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003807void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00003808 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003809 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003810 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003811 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003812 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003813 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003814 // Compute size of all parameters.
3815 // Start with computing size of a pointer in number of bytes.
3816 // FIXME: There might(should) be a better way of doing this computation!
3817 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003818 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003819 // The first two arguments (self and _cmd) are pointers; account for
3820 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003821 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003822 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003823 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003824 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003825 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003826 assert (sz.isPositive() &&
3827 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003828 ParmOffset += sz;
3829 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003830 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003831 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003832 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003833
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003834 // Argument types.
3835 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003836 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003837 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003838 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003839 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003840 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003841 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3842 // Use array's original type only if it has known number of
3843 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003844 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003845 PType = PVDecl->getType();
3846 } else if (PType->isFunctionType())
3847 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003848 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003849 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003850 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003851 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003852 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003853 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003854 }
3855}
3856
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003857/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003858/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003859/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3860/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003861/// Property attributes are stored as a comma-delimited C string. The simple
3862/// attributes readonly and bycopy are encoded as single characters. The
3863/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3864/// encoded as single characters, followed by an identifier. Property types
3865/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003866/// these attributes are defined by the following enumeration:
3867/// @code
3868/// enum PropertyAttributes {
3869/// kPropertyReadOnly = 'R', // property is read-only.
3870/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3871/// kPropertyByref = '&', // property is a reference to the value last assigned
3872/// kPropertyDynamic = 'D', // property is dynamic
3873/// kPropertyGetter = 'G', // followed by getter selector name
3874/// kPropertySetter = 'S', // followed by setter selector name
3875/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3876/// kPropertyType = 't' // followed by old-style type encoding.
3877/// kPropertyWeak = 'W' // 'weak' property
3878/// kPropertyStrong = 'P' // property GC'able
3879/// kPropertyNonAtomic = 'N' // property non-atomic
3880/// };
3881/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003882void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003883 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00003884 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003885 // Collect information from the property implementation decl(s).
3886 bool Dynamic = false;
3887 ObjCPropertyImplDecl *SynthesizePID = 0;
3888
3889 // FIXME: Duplicated code due to poor abstraction.
3890 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003891 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003892 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3893 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003894 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003895 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003896 ObjCPropertyImplDecl *PID = *i;
3897 if (PID->getPropertyDecl() == PD) {
3898 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3899 Dynamic = true;
3900 } else {
3901 SynthesizePID = PID;
3902 }
3903 }
3904 }
3905 } else {
Chris Lattner61710852008-10-05 17:34:18 +00003906 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003907 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003908 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003909 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003910 ObjCPropertyImplDecl *PID = *i;
3911 if (PID->getPropertyDecl() == PD) {
3912 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3913 Dynamic = true;
3914 } else {
3915 SynthesizePID = PID;
3916 }
3917 }
Mike Stump1eb44332009-09-09 15:08:12 +00003918 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003919 }
3920 }
3921
3922 // FIXME: This is not very efficient.
3923 S = "T";
3924
3925 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003926 // GCC has some special rules regarding encoding of properties which
3927 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00003928 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003929 true /* outermost type */,
3930 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003931
3932 if (PD->isReadOnly()) {
3933 S += ",R";
3934 } else {
3935 switch (PD->getSetterKind()) {
3936 case ObjCPropertyDecl::Assign: break;
3937 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00003938 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003939 }
3940 }
3941
3942 // It really isn't clear at all what this means, since properties
3943 // are "dynamic by default".
3944 if (Dynamic)
3945 S += ",D";
3946
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00003947 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3948 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00003949
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003950 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3951 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003952 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003953 }
3954
3955 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3956 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003957 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003958 }
3959
3960 if (SynthesizePID) {
3961 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3962 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00003963 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003964 }
3965
3966 // FIXME: OBJCGC: weak & strong
3967}
3968
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003969/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00003970/// Another legacy compatibility encoding: 32-bit longs are encoded as
3971/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003972/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3973///
3974void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00003975 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00003976 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00003977 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003978 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003979 else
Jay Foad4ba2a172011-01-12 09:06:06 +00003980 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00003981 PointeeTy = IntTy;
3982 }
3983 }
3984}
3985
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00003986void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00003987 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003988 // We follow the behavior of gcc, expanding structures which are
3989 // directly pointed to, and expanding embedded structures. Note that
3990 // these rules are sufficient to prevent recursive encoding of the
3991 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00003992 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00003993 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00003994}
3995
David Chisnall64fd7e82010-06-04 01:10:52 +00003996static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3997 switch (T->getAs<BuiltinType>()->getKind()) {
3998 default: assert(0 && "Unhandled builtin type kind");
3999 case BuiltinType::Void: return 'v';
4000 case BuiltinType::Bool: return 'B';
4001 case BuiltinType::Char_U:
4002 case BuiltinType::UChar: return 'C';
4003 case BuiltinType::UShort: return 'S';
4004 case BuiltinType::UInt: return 'I';
4005 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004006 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004007 case BuiltinType::UInt128: return 'T';
4008 case BuiltinType::ULongLong: return 'Q';
4009 case BuiltinType::Char_S:
4010 case BuiltinType::SChar: return 'c';
4011 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004012 case BuiltinType::WChar_S:
4013 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004014 case BuiltinType::Int: return 'i';
4015 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004016 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004017 case BuiltinType::LongLong: return 'q';
4018 case BuiltinType::Int128: return 't';
4019 case BuiltinType::Float: return 'f';
4020 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004021 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004022 }
4023}
4024
Jay Foad4ba2a172011-01-12 09:06:06 +00004025static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004026 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004027 const Expr *E = FD->getBitWidth();
4028 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004029 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004030 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4031 // The GNU runtime requires more information; bitfields are encoded as b,
4032 // then the offset (in bits) of the first element, then the type of the
4033 // bitfield, then the size in bits. For example, in this structure:
4034 //
4035 // struct
4036 // {
4037 // int integer;
4038 // int flags:2;
4039 // };
4040 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4041 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4042 // information is not especially sensible, but we're stuck with it for
4043 // compatibility with GCC, although providing it breaks anything that
4044 // actually uses runtime introspection and wants to work on both runtimes...
4045 if (!Ctx->getLangOptions().NeXTRuntime) {
4046 const RecordDecl *RD = FD->getParent();
4047 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4048 // FIXME: This same linear search is also used in ExprConstant - it might
4049 // be better if the FieldDecl stored its offset. We'd be increasing the
4050 // size of the object slightly, but saving some time every time it is used.
4051 unsigned i = 0;
4052 for (RecordDecl::field_iterator Field = RD->field_begin(),
4053 FieldEnd = RD->field_end();
4054 Field != FieldEnd; (void)++Field, ++i) {
4055 if (*Field == FD)
4056 break;
4057 }
4058 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnallc7ff82c2010-12-26 20:12:30 +00004059 if (T->isEnumeralType())
4060 S += 'i';
4061 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004062 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004063 }
4064 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004065 S += llvm::utostr(N);
4066}
4067
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004068// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004069void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4070 bool ExpandPointedToStructures,
4071 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004072 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004073 bool OutermostType,
Jay Foad4ba2a172011-01-12 09:06:06 +00004074 bool EncodingProperty) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004075 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004076 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004077 return EncodeBitField(this, S, T, FD);
4078 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004079 return;
4080 }
Mike Stump1eb44332009-09-09 15:08:12 +00004081
John McCall183700f2009-09-21 23:43:11 +00004082 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004083 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004084 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004085 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004086 return;
4087 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004088
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004089 // encoding for pointer or r3eference types.
4090 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004091 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004092 if (PT->isObjCSelType()) {
4093 S += ':';
4094 return;
4095 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004096 PointeeTy = PT->getPointeeType();
4097 }
4098 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4099 PointeeTy = RT->getPointeeType();
4100 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004101 bool isReadOnly = false;
4102 // For historical/compatibility reasons, the read-only qualifier of the
4103 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4104 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004105 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004106 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004107 if (OutermostType && T.isConstQualified()) {
4108 isReadOnly = true;
4109 S += 'r';
4110 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004111 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004112 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004113 while (P->getAs<PointerType>())
4114 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004115 if (P.isConstQualified()) {
4116 isReadOnly = true;
4117 S += 'r';
4118 }
4119 }
4120 if (isReadOnly) {
4121 // Another legacy compatibility encoding. Some ObjC qualifier and type
4122 // combinations need to be rearranged.
4123 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00004124 if (llvm::StringRef(S).endswith("nr"))
4125 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004126 }
Mike Stump1eb44332009-09-09 15:08:12 +00004127
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004128 if (PointeeTy->isCharType()) {
4129 // char pointer types should be encoded as '*' unless it is a
4130 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004131 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004132 S += '*';
4133 return;
4134 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004135 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004136 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4137 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4138 S += '#';
4139 return;
4140 }
4141 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4142 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4143 S += '@';
4144 return;
4145 }
4146 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004147 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004148 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004149 getLegacyIntegralTypeEncoding(PointeeTy);
4150
Mike Stump1eb44332009-09-09 15:08:12 +00004151 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004152 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004153 return;
4154 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004155
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004156 if (const ArrayType *AT =
4157 // Ignore type qualifiers etc.
4158 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004159 if (isa<IncompleteArrayType>(AT)) {
4160 // Incomplete arrays are encoded as a pointer to the array element.
4161 S += '^';
4162
Mike Stump1eb44332009-09-09 15:08:12 +00004163 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004164 false, ExpandStructures, FD);
4165 } else {
4166 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004167
Anders Carlsson559a8332009-02-22 01:38:57 +00004168 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
4169 S += llvm::utostr(CAT->getSize().getZExtValue());
4170 else {
4171 //Variable length arrays are encoded as a regular array with 0 elements.
4172 assert(isa<VariableArrayType>(AT) && "Unknown array type!");
4173 S += '0';
4174 }
Mike Stump1eb44332009-09-09 15:08:12 +00004175
4176 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004177 false, ExpandStructures, FD);
4178 S += ']';
4179 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004180 return;
4181 }
Mike Stump1eb44332009-09-09 15:08:12 +00004182
John McCall183700f2009-09-21 23:43:11 +00004183 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004184 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004185 return;
4186 }
Mike Stump1eb44332009-09-09 15:08:12 +00004187
Ted Kremenek6217b802009-07-29 21:53:49 +00004188 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004189 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004190 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004191 // Anonymous structures print as '?'
4192 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4193 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004194 if (ClassTemplateSpecializationDecl *Spec
4195 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4196 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4197 std::string TemplateArgsStr
4198 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004199 TemplateArgs.data(),
4200 TemplateArgs.size(),
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004201 (*this).PrintingPolicy);
4202
4203 S += TemplateArgsStr;
4204 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004205 } else {
4206 S += '?';
4207 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004208 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004209 S += '=';
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004210 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4211 FieldEnd = RDecl->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +00004212 Field != FieldEnd; ++Field) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004213 if (FD) {
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004214 S += '"';
Douglas Gregor44b43212008-12-11 16:49:14 +00004215 S += Field->getNameAsString();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004216 S += '"';
4217 }
Mike Stump1eb44332009-09-09 15:08:12 +00004218
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004219 // Special case bit-fields.
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004220 if (Field->isBitField()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004221 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004222 (*Field));
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004223 } else {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004224 QualType qt = Field->getType();
4225 getLegacyIntegralTypeEncoding(qt);
Mike Stump1eb44332009-09-09 15:08:12 +00004226 getObjCEncodingForTypeImpl(qt, S, false, true,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004227 FD);
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004228 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004229 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004230 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004231 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004232 return;
4233 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004234
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004235 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004236 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004237 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004238 else
4239 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004240 return;
4241 }
Mike Stump1eb44332009-09-09 15:08:12 +00004242
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004243 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004244 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004245 return;
4246 }
Mike Stump1eb44332009-09-09 15:08:12 +00004247
John McCallc12c5bb2010-05-15 11:32:37 +00004248 // Ignore protocol qualifiers when mangling at this level.
4249 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4250 T = OT->getBaseType();
4251
John McCall0953e762009-09-24 19:53:00 +00004252 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004253 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004254 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004255 S += '{';
4256 const IdentifierInfo *II = OI->getIdentifier();
4257 S += II->getName();
4258 S += '=';
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004259 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4260 DeepCollectObjCIvars(OI, true, Ivars);
4261 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4262 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4263 if (Field->isBitField())
4264 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004265 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004266 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004267 }
4268 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004269 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004270 }
Mike Stump1eb44332009-09-09 15:08:12 +00004271
John McCall183700f2009-09-21 23:43:11 +00004272 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004273 if (OPT->isObjCIdType()) {
4274 S += '@';
4275 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004276 }
Mike Stump1eb44332009-09-09 15:08:12 +00004277
Steve Naroff27d20a22009-10-28 22:03:49 +00004278 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4279 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4280 // Since this is a binary compatibility issue, need to consult with runtime
4281 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004282 S += '#';
4283 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004284 }
Mike Stump1eb44332009-09-09 15:08:12 +00004285
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004286 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004287 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004288 ExpandPointedToStructures,
4289 ExpandStructures, FD);
4290 if (FD || EncodingProperty) {
4291 // Note that we do extended encoding of protocol qualifer list
4292 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004293 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004294 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4295 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004296 S += '<';
4297 S += (*I)->getNameAsString();
4298 S += '>';
4299 }
4300 S += '"';
4301 }
4302 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004303 }
Mike Stump1eb44332009-09-09 15:08:12 +00004304
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004305 QualType PointeeTy = OPT->getPointeeType();
4306 if (!EncodingProperty &&
4307 isa<TypedefType>(PointeeTy.getTypePtr())) {
4308 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004309 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004310 // {...};
4311 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004312 getObjCEncodingForTypeImpl(PointeeTy, S,
4313 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004314 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004315 return;
4316 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004317
4318 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004319 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004320 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004321 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004322 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4323 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004324 S += '<';
4325 S += (*I)->getNameAsString();
4326 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004327 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004328 S += '"';
4329 }
4330 return;
4331 }
Mike Stump1eb44332009-09-09 15:08:12 +00004332
John McCall532ec7b2010-05-17 23:56:34 +00004333 // gcc just blithely ignores member pointers.
4334 // TODO: maybe there should be a mangling for these
4335 if (T->getAs<MemberPointerType>())
4336 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004337
4338 if (T->isVectorType()) {
4339 // This matches gcc's encoding, even though technically it is
4340 // insufficient.
4341 // FIXME. We should do a better job than gcc.
4342 return;
4343 }
4344
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004345 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004346}
4347
Mike Stump1eb44332009-09-09 15:08:12 +00004348void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004349 std::string& S) const {
4350 if (QT & Decl::OBJC_TQ_In)
4351 S += 'n';
4352 if (QT & Decl::OBJC_TQ_Inout)
4353 S += 'N';
4354 if (QT & Decl::OBJC_TQ_Out)
4355 S += 'o';
4356 if (QT & Decl::OBJC_TQ_Bycopy)
4357 S += 'O';
4358 if (QT & Decl::OBJC_TQ_Byref)
4359 S += 'R';
4360 if (QT & Decl::OBJC_TQ_Oneway)
4361 S += 'V';
4362}
4363
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004364void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004365 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004366
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004367 BuiltinVaListType = T;
4368}
4369
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004370void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004371 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00004372}
4373
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004374void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00004375 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004376}
4377
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004378void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004379 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004380}
4381
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004382void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004383 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004384}
4385
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004386void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004387 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004388 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004389
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004390 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004391}
4392
John McCall0bd6feb2009-12-02 08:04:21 +00004393/// \brief Retrieve the template name that corresponds to a non-empty
4394/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004395TemplateName
4396ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4397 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004398 unsigned size = End - Begin;
4399 assert(size > 1 && "set is not overloaded!");
4400
4401 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4402 size * sizeof(FunctionTemplateDecl*));
4403 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4404
4405 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004406 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004407 NamedDecl *D = *I;
4408 assert(isa<FunctionTemplateDecl>(D) ||
4409 (isa<UsingShadowDecl>(D) &&
4410 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4411 *Storage++ = D;
4412 }
4413
4414 return TemplateName(OT);
4415}
4416
Douglas Gregor7532dc62009-03-30 22:58:21 +00004417/// \brief Retrieve the template name that represents a qualified
4418/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004419TemplateName
4420ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4421 bool TemplateKeyword,
4422 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004423 assert(NNS && "Missing nested-name-specifier in qualified template name");
4424
Douglas Gregor789b1f62010-02-04 18:10:26 +00004425 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004426 llvm::FoldingSetNodeID ID;
4427 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4428
4429 void *InsertPos = 0;
4430 QualifiedTemplateName *QTN =
4431 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4432 if (!QTN) {
4433 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4434 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4435 }
4436
4437 return TemplateName(QTN);
4438}
4439
4440/// \brief Retrieve the template name that represents a dependent
4441/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004442TemplateName
4443ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4444 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004445 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004446 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004447
4448 llvm::FoldingSetNodeID ID;
4449 DependentTemplateName::Profile(ID, NNS, Name);
4450
4451 void *InsertPos = 0;
4452 DependentTemplateName *QTN =
4453 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4454
4455 if (QTN)
4456 return TemplateName(QTN);
4457
4458 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4459 if (CanonNNS == NNS) {
4460 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4461 } else {
4462 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4463 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004464 DependentTemplateName *CheckQTN =
4465 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4466 assert(!CheckQTN && "Dependent type name canonicalization broken");
4467 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004468 }
4469
4470 DependentTemplateNames.InsertNode(QTN, InsertPos);
4471 return TemplateName(QTN);
4472}
4473
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004474/// \brief Retrieve the template name that represents a dependent
4475/// template name such as \c MetaFun::template operator+.
4476TemplateName
4477ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004478 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004479 assert((!NNS || NNS->isDependent()) &&
4480 "Nested name specifier must be dependent");
4481
4482 llvm::FoldingSetNodeID ID;
4483 DependentTemplateName::Profile(ID, NNS, Operator);
4484
4485 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004486 DependentTemplateName *QTN
4487 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004488
4489 if (QTN)
4490 return TemplateName(QTN);
4491
4492 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4493 if (CanonNNS == NNS) {
4494 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4495 } else {
4496 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4497 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004498
4499 DependentTemplateName *CheckQTN
4500 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4501 assert(!CheckQTN && "Dependent template name canonicalization broken");
4502 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004503 }
4504
4505 DependentTemplateNames.InsertNode(QTN, InsertPos);
4506 return TemplateName(QTN);
4507}
4508
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004509TemplateName
4510ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4511 const TemplateArgument &ArgPack) const {
4512 ASTContext &Self = const_cast<ASTContext &>(*this);
4513 llvm::FoldingSetNodeID ID;
4514 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4515
4516 void *InsertPos = 0;
4517 SubstTemplateTemplateParmPackStorage *Subst
4518 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4519
4520 if (!Subst) {
4521 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4522 ArgPack.pack_size(),
4523 ArgPack.pack_begin());
4524 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4525 }
4526
4527 return TemplateName(Subst);
4528}
4529
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004530/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004531/// TargetInfo, produce the corresponding type. The unsigned @p Type
4532/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004533CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004534 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004535 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004536 case TargetInfo::SignedShort: return ShortTy;
4537 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4538 case TargetInfo::SignedInt: return IntTy;
4539 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4540 case TargetInfo::SignedLong: return LongTy;
4541 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4542 case TargetInfo::SignedLongLong: return LongLongTy;
4543 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4544 }
4545
4546 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004547 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004548}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004549
4550//===----------------------------------------------------------------------===//
4551// Type Predicates.
4552//===----------------------------------------------------------------------===//
4553
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004554/// isObjCNSObjectType - Return true if this is an NSObject object using
4555/// NSObject attribute on a c-style pointer type.
4556/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004557/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004558///
4559bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCallf4c73712011-01-19 06:33:43 +00004560 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004561 if (TypedefDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004562 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004563 return true;
4564 }
Mike Stump1eb44332009-09-09 15:08:12 +00004565 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004566}
4567
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004568/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4569/// garbage collection attribute.
4570///
John McCallae278a32011-01-12 00:34:59 +00004571Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4572 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4573 return Qualifiers::GCNone;
4574
4575 assert(getLangOptions().ObjC1);
4576 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4577
4578 // Default behaviour under objective-C's gc is for ObjC pointers
4579 // (or pointers to them) be treated as though they were declared
4580 // as __strong.
4581 if (GCAttrs == Qualifiers::GCNone) {
4582 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4583 return Qualifiers::Strong;
4584 else if (Ty->isPointerType())
4585 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4586 } else {
4587 // It's not valid to set GC attributes on anything that isn't a
4588 // pointer.
4589#ifndef NDEBUG
4590 QualType CT = Ty->getCanonicalTypeInternal();
4591 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4592 CT = AT->getElementType();
4593 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4594#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004595 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004596 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004597}
4598
Chris Lattner6ac46a42008-04-07 06:51:04 +00004599//===----------------------------------------------------------------------===//
4600// Type Compatibility Testing
4601//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004602
Mike Stump1eb44332009-09-09 15:08:12 +00004603/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004604/// compatible.
4605static bool areCompatVectorTypes(const VectorType *LHS,
4606 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004607 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004608 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004609 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004610}
4611
Douglas Gregor255210e2010-08-06 10:14:59 +00004612bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4613 QualType SecondVec) {
4614 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4615 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4616
4617 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4618 return true;
4619
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004620 // Treat Neon vector types and most AltiVec vector types as if they are the
4621 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00004622 const VectorType *First = FirstVec->getAs<VectorType>();
4623 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004624 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00004625 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004626 First->getVectorKind() != VectorType::AltiVecPixel &&
4627 First->getVectorKind() != VectorType::AltiVecBool &&
4628 Second->getVectorKind() != VectorType::AltiVecPixel &&
4629 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00004630 return true;
4631
4632 return false;
4633}
4634
Steve Naroff4084c302009-07-23 01:01:38 +00004635//===----------------------------------------------------------------------===//
4636// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4637//===----------------------------------------------------------------------===//
4638
4639/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4640/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00004641bool
4642ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4643 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00004644 if (lProto == rProto)
4645 return true;
4646 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4647 E = rProto->protocol_end(); PI != E; ++PI)
4648 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4649 return true;
4650 return false;
4651}
4652
Steve Naroff4084c302009-07-23 01:01:38 +00004653/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4654/// return true if lhs's protocols conform to rhs's protocol; false
4655/// otherwise.
4656bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4657 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4658 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4659 return false;
4660}
4661
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004662/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4663/// Class<p1, ...>.
4664bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4665 QualType rhs) {
4666 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4667 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4668 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4669
4670 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4671 E = lhsQID->qual_end(); I != E; ++I) {
4672 bool match = false;
4673 ObjCProtocolDecl *lhsProto = *I;
4674 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4675 E = rhsOPT->qual_end(); J != E; ++J) {
4676 ObjCProtocolDecl *rhsProto = *J;
4677 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4678 match = true;
4679 break;
4680 }
4681 }
4682 if (!match)
4683 return false;
4684 }
4685 return true;
4686}
4687
Steve Naroff4084c302009-07-23 01:01:38 +00004688/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4689/// ObjCQualifiedIDType.
4690bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4691 bool compare) {
4692 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004693 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004694 lhs->isObjCIdType() || lhs->isObjCClassType())
4695 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004696 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004697 rhs->isObjCIdType() || rhs->isObjCClassType())
4698 return true;
4699
4700 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004701 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004702
Steve Naroff4084c302009-07-23 01:01:38 +00004703 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004704
Steve Naroff4084c302009-07-23 01:01:38 +00004705 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004706 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004707 // make sure we check the class hierarchy.
4708 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4709 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4710 E = lhsQID->qual_end(); I != E; ++I) {
4711 // when comparing an id<P> on lhs with a static type on rhs,
4712 // see if static class implements all of id's protocols, directly or
4713 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004714 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004715 return false;
4716 }
4717 }
4718 // If there are no qualifiers and no interface, we have an 'id'.
4719 return true;
4720 }
Mike Stump1eb44332009-09-09 15:08:12 +00004721 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004722 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4723 E = lhsQID->qual_end(); I != E; ++I) {
4724 ObjCProtocolDecl *lhsProto = *I;
4725 bool match = false;
4726
4727 // when comparing an id<P> on lhs with a static type on rhs,
4728 // see if static class implements all of id's protocols, directly or
4729 // through its super class and categories.
4730 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4731 E = rhsOPT->qual_end(); J != E; ++J) {
4732 ObjCProtocolDecl *rhsProto = *J;
4733 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4734 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4735 match = true;
4736 break;
4737 }
4738 }
Mike Stump1eb44332009-09-09 15:08:12 +00004739 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004740 // make sure we check the class hierarchy.
4741 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4742 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4743 E = lhsQID->qual_end(); I != E; ++I) {
4744 // when comparing an id<P> on lhs with a static type on rhs,
4745 // see if static class implements all of id's protocols, directly or
4746 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004747 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004748 match = true;
4749 break;
4750 }
4751 }
4752 }
4753 if (!match)
4754 return false;
4755 }
Mike Stump1eb44332009-09-09 15:08:12 +00004756
Steve Naroff4084c302009-07-23 01:01:38 +00004757 return true;
4758 }
Mike Stump1eb44332009-09-09 15:08:12 +00004759
Steve Naroff4084c302009-07-23 01:01:38 +00004760 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4761 assert(rhsQID && "One of the LHS/RHS should be id<x>");
4762
Mike Stump1eb44332009-09-09 15:08:12 +00004763 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00004764 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004765 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004766 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4767 E = lhsOPT->qual_end(); I != E; ++I) {
4768 ObjCProtocolDecl *lhsProto = *I;
4769 bool match = false;
4770
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004771 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00004772 // see if static class implements all of id's protocols, directly or
4773 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004774 // First, lhs protocols in the qualifier list must be found, direct
4775 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00004776 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4777 E = rhsQID->qual_end(); J != E; ++J) {
4778 ObjCProtocolDecl *rhsProto = *J;
4779 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4780 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4781 match = true;
4782 break;
4783 }
4784 }
4785 if (!match)
4786 return false;
4787 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00004788
4789 // Static class's protocols, or its super class or category protocols
4790 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
4791 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4792 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4793 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
4794 // This is rather dubious but matches gcc's behavior. If lhs has
4795 // no type qualifier and its class has no static protocol(s)
4796 // assume that it is mismatch.
4797 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
4798 return false;
4799 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4800 LHSInheritedProtocols.begin(),
4801 E = LHSInheritedProtocols.end(); I != E; ++I) {
4802 bool match = false;
4803 ObjCProtocolDecl *lhsProto = (*I);
4804 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4805 E = rhsQID->qual_end(); J != E; ++J) {
4806 ObjCProtocolDecl *rhsProto = *J;
4807 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4808 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4809 match = true;
4810 break;
4811 }
4812 }
4813 if (!match)
4814 return false;
4815 }
4816 }
Steve Naroff4084c302009-07-23 01:01:38 +00004817 return true;
4818 }
4819 return false;
4820}
4821
Eli Friedman3d815e72008-08-22 00:56:42 +00004822/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004823/// compatible for assignment from RHS to LHS. This handles validation of any
4824/// protocol qualifiers on the LHS or RHS.
4825///
Steve Naroff14108da2009-07-10 23:34:53 +00004826bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4827 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00004828 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4829 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4830
Steve Naroffde2e22d2009-07-15 18:40:39 +00004831 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00004832 if (LHS->isObjCUnqualifiedIdOrClass() ||
4833 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00004834 return true;
4835
John McCallc12c5bb2010-05-15 11:32:37 +00004836 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00004837 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4838 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00004839 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004840
4841 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
4842 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
4843 QualType(RHSOPT,0));
4844
John McCallc12c5bb2010-05-15 11:32:37 +00004845 // If we have 2 user-defined types, fall into that path.
4846 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00004847 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00004848
Steve Naroff4084c302009-07-23 01:01:38 +00004849 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00004850}
4851
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004852/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4853/// for providing type-safty for objective-c pointers used to pass/return
4854/// arguments in block literals. When passed as arguments, passing 'A*' where
4855/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4856/// not OK. For the return type, the opposite is not OK.
4857bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4858 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00004859 const ObjCObjectPointerType *RHSOPT,
4860 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004861 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004862 return true;
4863
4864 if (LHSOPT->isObjCBuiltinType()) {
4865 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4866 }
4867
Fariborz Jahaniana9834482010-04-06 17:23:39 +00004868 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004869 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4870 QualType(RHSOPT,0),
4871 false);
4872
4873 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4874 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4875 if (LHS && RHS) { // We have 2 user-defined types.
4876 if (LHS != RHS) {
4877 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00004878 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004879 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00004880 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004881 }
4882 else
4883 return true;
4884 }
4885 return false;
4886}
4887
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004888/// getIntersectionOfProtocols - This routine finds the intersection of set
4889/// of protocols inherited from two distinct objective-c pointer objects.
4890/// It is used to build composite qualifier list of the composite type of
4891/// the conditional expression involving two objective-c pointer objects.
4892static
4893void getIntersectionOfProtocols(ASTContext &Context,
4894 const ObjCObjectPointerType *LHSOPT,
4895 const ObjCObjectPointerType *RHSOPT,
4896 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4897
John McCallc12c5bb2010-05-15 11:32:37 +00004898 const ObjCObjectType* LHS = LHSOPT->getObjectType();
4899 const ObjCObjectType* RHS = RHSOPT->getObjectType();
4900 assert(LHS->getInterface() && "LHS must have an interface base");
4901 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004902
4903 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4904 unsigned LHSNumProtocols = LHS->getNumProtocols();
4905 if (LHSNumProtocols > 0)
4906 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4907 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004908 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004909 Context.CollectInheritedProtocols(LHS->getInterface(),
4910 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004911 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4912 LHSInheritedProtocols.end());
4913 }
4914
4915 unsigned RHSNumProtocols = RHS->getNumProtocols();
4916 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00004917 ObjCProtocolDecl **RHSProtocols =
4918 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004919 for (unsigned i = 0; i < RHSNumProtocols; ++i)
4920 if (InheritedProtocolSet.count(RHSProtocols[i]))
4921 IntersectionOfProtocols.push_back(RHSProtocols[i]);
4922 }
4923 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004924 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00004925 Context.CollectInheritedProtocols(RHS->getInterface(),
4926 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00004927 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4928 RHSInheritedProtocols.begin(),
4929 E = RHSInheritedProtocols.end(); I != E; ++I)
4930 if (InheritedProtocolSet.count((*I)))
4931 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004932 }
4933}
4934
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004935/// areCommonBaseCompatible - Returns common base class of the two classes if
4936/// one found. Note that this is O'2 algorithm. But it will be called as the
4937/// last type comparison in a ?-exp of ObjC pointer types before a
4938/// warning is issued. So, its invokation is extremely rare.
4939QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00004940 const ObjCObjectPointerType *Lptr,
4941 const ObjCObjectPointerType *Rptr) {
4942 const ObjCObjectType *LHS = Lptr->getObjectType();
4943 const ObjCObjectType *RHS = Rptr->getObjectType();
4944 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4945 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4946 if (!LDecl || !RDecl)
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004947 return QualType();
4948
John McCallc12c5bb2010-05-15 11:32:37 +00004949 while ((LDecl = LDecl->getSuperClass())) {
4950 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004951 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00004952 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4953 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4954
4955 QualType Result = QualType(LHS, 0);
4956 if (!Protocols.empty())
4957 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4958 Result = getObjCObjectPointerType(Result);
4959 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00004960 }
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00004961 }
4962
4963 return QualType();
4964}
4965
John McCallc12c5bb2010-05-15 11:32:37 +00004966bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4967 const ObjCObjectType *RHS) {
4968 assert(LHS->getInterface() && "LHS is not an interface type");
4969 assert(RHS->getInterface() && "RHS is not an interface type");
4970
Chris Lattner6ac46a42008-04-07 06:51:04 +00004971 // Verify that the base decls are compatible: the RHS must be a subclass of
4972 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00004973 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00004974 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004975
Chris Lattner6ac46a42008-04-07 06:51:04 +00004976 // RHS must have a superset of the protocols in the LHS. If the LHS is not
4977 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004978 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004979 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004980
Chris Lattner6ac46a42008-04-07 06:51:04 +00004981 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it
4982 // isn't a superset.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00004983 if (RHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00004984 return true; // FIXME: should return false!
Mike Stump1eb44332009-09-09 15:08:12 +00004985
John McCallc12c5bb2010-05-15 11:32:37 +00004986 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4987 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004988 LHSPI != LHSPE; LHSPI++) {
4989 bool RHSImplementsProtocol = false;
4990
4991 // If the RHS doesn't implement the protocol on the left, the types
4992 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00004993 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4994 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00004995 RHSPI != RHSPE; RHSPI++) {
4996 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00004997 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00004998 break;
4999 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005000 }
5001 // FIXME: For better diagnostics, consider passing back the protocol name.
5002 if (!RHSImplementsProtocol)
5003 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005004 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005005 // The RHS implements all protocols listed on the LHS.
5006 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005007}
5008
Steve Naroff389bf462009-02-12 17:52:19 +00005009bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5010 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005011 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5012 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005013
Steve Naroff14108da2009-07-10 23:34:53 +00005014 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005015 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005016
5017 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5018 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005019}
5020
Douglas Gregor569c3162010-08-07 11:51:51 +00005021bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5022 return canAssignObjCInterfaces(
5023 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5024 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5025}
5026
Mike Stump1eb44332009-09-09 15:08:12 +00005027/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005028/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005029/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005030/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005031bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5032 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005033 if (getLangOptions().CPlusPlus)
5034 return hasSameType(LHS, RHS);
5035
Douglas Gregor447234d2010-07-29 15:18:02 +00005036 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005037}
5038
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005039bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5040 return !mergeTypes(LHS, RHS, true).isNull();
5041}
5042
Peter Collingbourne48466752010-10-24 18:30:18 +00005043/// mergeTransparentUnionType - if T is a transparent union type and a member
5044/// of T is compatible with SubType, return the merged type, else return
5045/// QualType()
5046QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5047 bool OfBlockPointer,
5048 bool Unqualified) {
5049 if (const RecordType *UT = T->getAsUnionType()) {
5050 RecordDecl *UD = UT->getDecl();
5051 if (UD->hasAttr<TransparentUnionAttr>()) {
5052 for (RecordDecl::field_iterator it = UD->field_begin(),
5053 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005054 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005055 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5056 if (!MT.isNull())
5057 return MT;
5058 }
5059 }
5060 }
5061
5062 return QualType();
5063}
5064
5065/// mergeFunctionArgumentTypes - merge two types which appear as function
5066/// argument types
5067QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5068 bool OfBlockPointer,
5069 bool Unqualified) {
5070 // GNU extension: two types are compatible if they appear as a function
5071 // argument, one of the types is a transparent union type and the other
5072 // type is compatible with a union member
5073 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5074 Unqualified);
5075 if (!lmerge.isNull())
5076 return lmerge;
5077
5078 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5079 Unqualified);
5080 if (!rmerge.isNull())
5081 return rmerge;
5082
5083 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5084}
5085
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005086QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005087 bool OfBlockPointer,
5088 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005089 const FunctionType *lbase = lhs->getAs<FunctionType>();
5090 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005091 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5092 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005093 bool allLTypes = true;
5094 bool allRTypes = true;
5095
5096 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005097 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005098 if (OfBlockPointer) {
5099 QualType RHS = rbase->getResultType();
5100 QualType LHS = lbase->getResultType();
5101 bool UnqualifiedResult = Unqualified;
5102 if (!UnqualifiedResult)
5103 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005104 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005105 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005106 else
John McCall8cc246c2010-12-15 01:06:38 +00005107 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5108 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005109 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005110
5111 if (Unqualified)
5112 retType = retType.getUnqualifiedType();
5113
5114 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5115 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5116 if (Unqualified) {
5117 LRetType = LRetType.getUnqualifiedType();
5118 RRetType = RRetType.getUnqualifiedType();
5119 }
5120
5121 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005122 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005123 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005124 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005125
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005126 // FIXME: double check this
5127 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5128 // rbase->getRegParmAttr() != 0 &&
5129 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005130 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5131 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005132
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005133 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005134 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005135 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005136
John McCall8cc246c2010-12-15 01:06:38 +00005137 // Regparm is part of the calling convention.
5138 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5139 return QualType();
5140
5141 // It's noreturn if either type is.
5142 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5143 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5144 if (NoReturn != lbaseInfo.getNoReturn())
5145 allLTypes = false;
5146 if (NoReturn != rbaseInfo.getNoReturn())
5147 allRTypes = false;
5148
5149 FunctionType::ExtInfo einfo(NoReturn,
5150 lbaseInfo.getRegParm(),
5151 lbaseInfo.getCC());
John McCalle23cf432010-12-14 08:05:40 +00005152
Eli Friedman3d815e72008-08-22 00:56:42 +00005153 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005154 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5155 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005156 unsigned lproto_nargs = lproto->getNumArgs();
5157 unsigned rproto_nargs = rproto->getNumArgs();
5158
5159 // Compatible functions must have the same number of arguments
5160 if (lproto_nargs != rproto_nargs)
5161 return QualType();
5162
5163 // Variadic and non-variadic functions aren't compatible
5164 if (lproto->isVariadic() != rproto->isVariadic())
5165 return QualType();
5166
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005167 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5168 return QualType();
5169
Eli Friedman3d815e72008-08-22 00:56:42 +00005170 // Check argument compatibility
5171 llvm::SmallVector<QualType, 10> types;
5172 for (unsigned i = 0; i < lproto_nargs; i++) {
5173 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5174 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005175 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5176 OfBlockPointer,
5177 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005178 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005179
5180 if (Unqualified)
5181 argtype = argtype.getUnqualifiedType();
5182
Eli Friedman3d815e72008-08-22 00:56:42 +00005183 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005184 if (Unqualified) {
5185 largtype = largtype.getUnqualifiedType();
5186 rargtype = rargtype.getUnqualifiedType();
5187 }
5188
Chris Lattner61710852008-10-05 17:34:18 +00005189 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5190 allLTypes = false;
5191 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5192 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005193 }
5194 if (allLTypes) return lhs;
5195 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005196
5197 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5198 EPI.ExtInfo = einfo;
5199 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005200 }
5201
5202 if (lproto) allRTypes = false;
5203 if (rproto) allLTypes = false;
5204
Douglas Gregor72564e72009-02-26 23:50:07 +00005205 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005206 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005207 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005208 if (proto->isVariadic()) return QualType();
5209 // Check that the types are compatible with the types that
5210 // would result from default argument promotions (C99 6.7.5.3p15).
5211 // The only types actually affected are promotable integer
5212 // types and floats, which would be passed as a different
5213 // type depending on whether the prototype is visible.
5214 unsigned proto_nargs = proto->getNumArgs();
5215 for (unsigned i = 0; i < proto_nargs; ++i) {
5216 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005217
5218 // Look at the promotion type of enum types, since that is the type used
5219 // to pass enum values.
5220 if (const EnumType *Enum = argTy->getAs<EnumType>())
5221 argTy = Enum->getDecl()->getPromotionType();
5222
Eli Friedman3d815e72008-08-22 00:56:42 +00005223 if (argTy->isPromotableIntegerType() ||
5224 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5225 return QualType();
5226 }
5227
5228 if (allLTypes) return lhs;
5229 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005230
5231 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5232 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005233 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005234 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005235 }
5236
5237 if (allLTypes) return lhs;
5238 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005239 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005240}
5241
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005242QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005243 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005244 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005245 // C++ [expr]: If an expression initially has the type "reference to T", the
5246 // type is adjusted to "T" prior to any further analysis, the expression
5247 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005248 // expression is an lvalue unless the reference is an rvalue reference and
5249 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005250 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5251 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005252
5253 if (Unqualified) {
5254 LHS = LHS.getUnqualifiedType();
5255 RHS = RHS.getUnqualifiedType();
5256 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005257
Eli Friedman3d815e72008-08-22 00:56:42 +00005258 QualType LHSCan = getCanonicalType(LHS),
5259 RHSCan = getCanonicalType(RHS);
5260
5261 // If two types are identical, they are compatible.
5262 if (LHSCan == RHSCan)
5263 return LHS;
5264
John McCall0953e762009-09-24 19:53:00 +00005265 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005266 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5267 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005268 if (LQuals != RQuals) {
5269 // If any of these qualifiers are different, we have a type
5270 // mismatch.
5271 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5272 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5273 return QualType();
5274
5275 // Exactly one GC qualifier difference is allowed: __strong is
5276 // okay if the other type has no GC qualifier but is an Objective
5277 // C object pointer (i.e. implicitly strong by default). We fix
5278 // this by pretending that the unqualified type was actually
5279 // qualified __strong.
5280 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5281 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5282 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5283
5284 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5285 return QualType();
5286
5287 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5288 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5289 }
5290 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5291 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5292 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005293 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005294 }
5295
5296 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005297
Eli Friedman852d63b2009-06-01 01:22:52 +00005298 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5299 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005300
Chris Lattner1adb8832008-01-14 05:45:46 +00005301 // We want to consider the two function types to be the same for these
5302 // comparisons, just force one to the other.
5303 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5304 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005305
5306 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005307 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5308 LHSClass = Type::ConstantArray;
5309 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5310 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005311
John McCallc12c5bb2010-05-15 11:32:37 +00005312 // ObjCInterfaces are just specialized ObjCObjects.
5313 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5314 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5315
Nate Begeman213541a2008-04-18 23:10:10 +00005316 // Canonicalize ExtVector -> Vector.
5317 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5318 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005319
Chris Lattnera36a61f2008-04-07 05:43:21 +00005320 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005321 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005322 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005323 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005324 // Compatibility is based on the underlying type, not the promotion
5325 // type.
John McCall183700f2009-09-21 23:43:11 +00005326 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005327 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5328 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005329 }
John McCall183700f2009-09-21 23:43:11 +00005330 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005331 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5332 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005333 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005334
Eli Friedman3d815e72008-08-22 00:56:42 +00005335 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005336 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005337
Steve Naroff4a746782008-01-09 22:43:08 +00005338 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005339 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005340#define TYPE(Class, Base)
5341#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005342#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005343#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5344#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5345#include "clang/AST/TypeNodes.def"
5346 assert(false && "Non-canonical and dependent types shouldn't get here");
5347 return QualType();
5348
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005349 case Type::LValueReference:
5350 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005351 case Type::MemberPointer:
5352 assert(false && "C++ should never be in mergeTypes");
5353 return QualType();
5354
John McCallc12c5bb2010-05-15 11:32:37 +00005355 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005356 case Type::IncompleteArray:
5357 case Type::VariableArray:
5358 case Type::FunctionProto:
5359 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00005360 assert(false && "Types are eliminated above");
5361 return QualType();
5362
Chris Lattner1adb8832008-01-14 05:45:46 +00005363 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005364 {
5365 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005366 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5367 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005368 if (Unqualified) {
5369 LHSPointee = LHSPointee.getUnqualifiedType();
5370 RHSPointee = RHSPointee.getUnqualifiedType();
5371 }
5372 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5373 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005374 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005375 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005376 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005377 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005378 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005379 return getPointerType(ResultType);
5380 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005381 case Type::BlockPointer:
5382 {
5383 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005384 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5385 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005386 if (Unqualified) {
5387 LHSPointee = LHSPointee.getUnqualifiedType();
5388 RHSPointee = RHSPointee.getUnqualifiedType();
5389 }
5390 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5391 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005392 if (ResultType.isNull()) return QualType();
5393 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5394 return LHS;
5395 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5396 return RHS;
5397 return getBlockPointerType(ResultType);
5398 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005399 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005400 {
5401 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5402 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5403 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5404 return QualType();
5405
5406 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5407 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005408 if (Unqualified) {
5409 LHSElem = LHSElem.getUnqualifiedType();
5410 RHSElem = RHSElem.getUnqualifiedType();
5411 }
5412
5413 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005414 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005415 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5416 return LHS;
5417 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5418 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005419 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5420 ArrayType::ArraySizeModifier(), 0);
5421 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5422 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005423 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5424 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005425 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5426 return LHS;
5427 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5428 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005429 if (LVAT) {
5430 // FIXME: This isn't correct! But tricky to implement because
5431 // the array's size has to be the size of LHS, but the type
5432 // has to be different.
5433 return LHS;
5434 }
5435 if (RVAT) {
5436 // FIXME: This isn't correct! But tricky to implement because
5437 // the array's size has to be the size of RHS, but the type
5438 // has to be different.
5439 return RHS;
5440 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005441 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5442 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005443 return getIncompleteArrayType(ResultType,
5444 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005445 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005446 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005447 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005448 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005449 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005450 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005451 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005452 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005453 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005454 case Type::Complex:
5455 // Distinct complex types are incompatible.
5456 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005457 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005458 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005459 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5460 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005461 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005462 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005463 case Type::ObjCObject: {
5464 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005465 // FIXME: This should be type compatibility, e.g. whether
5466 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005467 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5468 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5469 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005470 return LHS;
5471
Eli Friedman3d815e72008-08-22 00:56:42 +00005472 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005473 }
Steve Naroff14108da2009-07-10 23:34:53 +00005474 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005475 if (OfBlockPointer) {
5476 if (canAssignObjCInterfacesInBlockPointer(
5477 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005478 RHS->getAs<ObjCObjectPointerType>(),
5479 BlockReturnType))
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005480 return LHS;
5481 return QualType();
5482 }
John McCall183700f2009-09-21 23:43:11 +00005483 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5484 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005485 return LHS;
5486
Steve Naroffbc76dd02008-12-10 22:14:21 +00005487 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005488 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005489 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005490
5491 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005492}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005493
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005494/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5495/// 'RHS' attributes and returns the merged version; including for function
5496/// return types.
5497QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5498 QualType LHSCan = getCanonicalType(LHS),
5499 RHSCan = getCanonicalType(RHS);
5500 // If two types are identical, they are compatible.
5501 if (LHSCan == RHSCan)
5502 return LHS;
5503 if (RHSCan->isFunctionType()) {
5504 if (!LHSCan->isFunctionType())
5505 return QualType();
5506 QualType OldReturnType =
5507 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5508 QualType NewReturnType =
5509 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5510 QualType ResReturnType =
5511 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5512 if (ResReturnType.isNull())
5513 return QualType();
5514 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5515 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5516 // In either case, use OldReturnType to build the new function type.
5517 const FunctionType *F = LHS->getAs<FunctionType>();
5518 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00005519 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5520 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005521 QualType ResultType
5522 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005523 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005524 return ResultType;
5525 }
5526 }
5527 return QualType();
5528 }
5529
5530 // If the qualifiers are different, the types can still be merged.
5531 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5532 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5533 if (LQuals != RQuals) {
5534 // If any of these qualifiers are different, we have a type mismatch.
5535 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5536 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5537 return QualType();
5538
5539 // Exactly one GC qualifier difference is allowed: __strong is
5540 // okay if the other type has no GC qualifier but is an Objective
5541 // C object pointer (i.e. implicitly strong by default). We fix
5542 // this by pretending that the unqualified type was actually
5543 // qualified __strong.
5544 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5545 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5546 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5547
5548 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5549 return QualType();
5550
5551 if (GC_L == Qualifiers::Strong)
5552 return LHS;
5553 if (GC_R == Qualifiers::Strong)
5554 return RHS;
5555 return QualType();
5556 }
5557
5558 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5559 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5560 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5561 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5562 if (ResQT == LHSBaseQT)
5563 return LHS;
5564 if (ResQT == RHSBaseQT)
5565 return RHS;
5566 }
5567 return QualType();
5568}
5569
Chris Lattner5426bf62008-04-07 07:01:58 +00005570//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005571// Integer Predicates
5572//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005573
Jay Foad4ba2a172011-01-12 09:06:06 +00005574unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00005575 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005576 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005577 if (T->isBooleanType())
5578 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00005579 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005580 return (unsigned)getTypeSize(T);
5581}
5582
5583QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005584 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005585
5586 // Turn <4 x signed int> -> <4 x unsigned int>
5587 if (const VectorType *VTy = T->getAs<VectorType>())
5588 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00005589 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005590
5591 // For enums, we return the unsigned version of the base type.
5592 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005593 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005594
5595 const BuiltinType *BTy = T->getAs<BuiltinType>();
5596 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005597 switch (BTy->getKind()) {
5598 case BuiltinType::Char_S:
5599 case BuiltinType::SChar:
5600 return UnsignedCharTy;
5601 case BuiltinType::Short:
5602 return UnsignedShortTy;
5603 case BuiltinType::Int:
5604 return UnsignedIntTy;
5605 case BuiltinType::Long:
5606 return UnsignedLongTy;
5607 case BuiltinType::LongLong:
5608 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005609 case BuiltinType::Int128:
5610 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005611 default:
5612 assert(0 && "Unexpected signed integer type");
5613 return QualType();
5614 }
5615}
5616
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005617ASTMutationListener::~ASTMutationListener() { }
5618
Chris Lattner86df27b2009-06-14 00:45:47 +00005619
5620//===----------------------------------------------------------------------===//
5621// Builtin Type Computation
5622//===----------------------------------------------------------------------===//
5623
5624/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00005625/// pointer over the consumed characters. This returns the resultant type. If
5626/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5627/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5628/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00005629///
5630/// RequiresICE is filled in on return to indicate whether the value is required
5631/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00005632static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005633 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00005634 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00005635 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005636 // Modifiers.
5637 int HowLong = 0;
5638 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00005639 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005640
Chris Lattner33daae62010-10-01 22:42:38 +00005641 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00005642 bool Done = false;
5643 while (!Done) {
5644 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005645 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005646 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00005647 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005648 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005649 case 'S':
5650 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5651 assert(!Signed && "Can't use 'S' modifier multiple times!");
5652 Signed = true;
5653 break;
5654 case 'U':
5655 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5656 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5657 Unsigned = true;
5658 break;
5659 case 'L':
5660 assert(HowLong <= 2 && "Can't have LLLL modifier");
5661 ++HowLong;
5662 break;
5663 }
5664 }
5665
5666 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005667
Chris Lattner86df27b2009-06-14 00:45:47 +00005668 // Read the base type.
5669 switch (*Str++) {
5670 default: assert(0 && "Unknown builtin type letter!");
5671 case 'v':
5672 assert(HowLong == 0 && !Signed && !Unsigned &&
5673 "Bad modifiers used with 'v'!");
5674 Type = Context.VoidTy;
5675 break;
5676 case 'f':
5677 assert(HowLong == 0 && !Signed && !Unsigned &&
5678 "Bad modifiers used with 'f'!");
5679 Type = Context.FloatTy;
5680 break;
5681 case 'd':
5682 assert(HowLong < 2 && !Signed && !Unsigned &&
5683 "Bad modifiers used with 'd'!");
5684 if (HowLong)
5685 Type = Context.LongDoubleTy;
5686 else
5687 Type = Context.DoubleTy;
5688 break;
5689 case 's':
5690 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5691 if (Unsigned)
5692 Type = Context.UnsignedShortTy;
5693 else
5694 Type = Context.ShortTy;
5695 break;
5696 case 'i':
5697 if (HowLong == 3)
5698 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5699 else if (HowLong == 2)
5700 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5701 else if (HowLong == 1)
5702 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5703 else
5704 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5705 break;
5706 case 'c':
5707 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5708 if (Signed)
5709 Type = Context.SignedCharTy;
5710 else if (Unsigned)
5711 Type = Context.UnsignedCharTy;
5712 else
5713 Type = Context.CharTy;
5714 break;
5715 case 'b': // boolean
5716 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5717 Type = Context.BoolTy;
5718 break;
5719 case 'z': // size_t.
5720 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5721 Type = Context.getSizeType();
5722 break;
5723 case 'F':
5724 Type = Context.getCFConstantStringType();
5725 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00005726 case 'G':
5727 Type = Context.getObjCIdType();
5728 break;
5729 case 'H':
5730 Type = Context.getObjCSelType();
5731 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005732 case 'a':
5733 Type = Context.getBuiltinVaListType();
5734 assert(!Type.isNull() && "builtin va list type not initialized!");
5735 break;
5736 case 'A':
5737 // This is a "reference" to a va_list; however, what exactly
5738 // this means depends on how va_list is defined. There are two
5739 // different kinds of va_list: ones passed by value, and ones
5740 // passed by reference. An example of a by-value va_list is
5741 // x86, where va_list is a char*. An example of by-ref va_list
5742 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5743 // we want this argument to be a char*&; for x86-64, we want
5744 // it to be a __va_list_tag*.
5745 Type = Context.getBuiltinVaListType();
5746 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00005747 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00005748 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00005749 else
Chris Lattner86df27b2009-06-14 00:45:47 +00005750 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00005751 break;
5752 case 'V': {
5753 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00005754 unsigned NumElements = strtoul(Str, &End, 10);
5755 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00005756 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00005757
Chris Lattner14e0e742010-10-01 22:53:11 +00005758 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
5759 RequiresICE, false);
5760 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00005761
5762 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00005763 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00005764 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00005765 break;
5766 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00005767 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00005768 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
5769 false);
5770 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00005771 Type = Context.getComplexType(ElementType);
5772 break;
5773 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005774 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00005775 Type = Context.getFILEType();
5776 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005777 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00005778 return QualType();
5779 }
Mike Stumpfd612db2009-07-28 23:47:15 +00005780 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00005781 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00005782 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00005783 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00005784 else
5785 Type = Context.getjmp_bufType();
5786
Mike Stumpfd612db2009-07-28 23:47:15 +00005787 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00005788 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00005789 return QualType();
5790 }
5791 break;
Mike Stump782fa302009-07-28 02:25:19 +00005792 }
Mike Stump1eb44332009-09-09 15:08:12 +00005793
Chris Lattner33daae62010-10-01 22:42:38 +00005794 // If there are modifiers and if we're allowed to parse them, go for it.
5795 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00005796 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00005797 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00005798 default: Done = true; --Str; break;
5799 case '*':
5800 case '&': {
5801 // Both pointers and references can have their pointee types
5802 // qualified with an address space.
5803 char *End;
5804 unsigned AddrSpace = strtoul(Str, &End, 10);
5805 if (End != Str && AddrSpace != 0) {
5806 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5807 Str = End;
5808 }
5809 if (c == '*')
5810 Type = Context.getPointerType(Type);
5811 else
5812 Type = Context.getLValueReferenceType(Type);
5813 break;
5814 }
5815 // FIXME: There's no way to have a built-in with an rvalue ref arg.
5816 case 'C':
5817 Type = Type.withConst();
5818 break;
5819 case 'D':
5820 Type = Context.getVolatileType(Type);
5821 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005822 }
5823 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00005824
Chris Lattner14e0e742010-10-01 22:53:11 +00005825 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00005826 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00005827
Chris Lattner86df27b2009-06-14 00:45:47 +00005828 return Type;
5829}
5830
5831/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00005832QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00005833 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00005834 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00005835 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00005836
Chris Lattner86df27b2009-06-14 00:45:47 +00005837 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00005838
Chris Lattner14e0e742010-10-01 22:53:11 +00005839 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00005840 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00005841 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
5842 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005843 if (Error != GE_None)
5844 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00005845
5846 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
5847
Chris Lattner86df27b2009-06-14 00:45:47 +00005848 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00005849 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00005850 if (Error != GE_None)
5851 return QualType();
5852
Chris Lattner14e0e742010-10-01 22:53:11 +00005853 // If this argument is required to be an IntegerConstantExpression and the
5854 // caller cares, fill in the bitmask we return.
5855 if (RequiresICE && IntegerConstantArgs)
5856 *IntegerConstantArgs |= 1 << ArgTypes.size();
5857
Chris Lattner86df27b2009-06-14 00:45:47 +00005858 // Do array -> pointer decay. The builtin should use the decayed type.
5859 if (Ty->isArrayType())
5860 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00005861
Chris Lattner86df27b2009-06-14 00:45:47 +00005862 ArgTypes.push_back(Ty);
5863 }
5864
5865 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5866 "'.' should only occur at end of builtin type list!");
5867
John McCall00ccbef2010-12-21 00:44:39 +00005868 FunctionType::ExtInfo EI;
5869 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
5870
5871 bool Variadic = (TypeStr[0] == '.');
5872
5873 // We really shouldn't be making a no-proto type here, especially in C++.
5874 if (ArgTypes.empty() && Variadic)
5875 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00005876
John McCalle23cf432010-12-14 08:05:40 +00005877 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00005878 EPI.ExtInfo = EI;
5879 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00005880
5881 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00005882}
Eli Friedmana95d7572009-08-19 07:44:53 +00005883
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005884GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
5885 GVALinkage External = GVA_StrongExternal;
5886
5887 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005888 switch (L) {
5889 case NoLinkage:
5890 case InternalLinkage:
5891 case UniqueExternalLinkage:
5892 return GVA_Internal;
5893
5894 case ExternalLinkage:
5895 switch (FD->getTemplateSpecializationKind()) {
5896 case TSK_Undeclared:
5897 case TSK_ExplicitSpecialization:
5898 External = GVA_StrongExternal;
5899 break;
5900
5901 case TSK_ExplicitInstantiationDefinition:
5902 return GVA_ExplicitTemplateInstantiation;
5903
5904 case TSK_ExplicitInstantiationDeclaration:
5905 case TSK_ImplicitInstantiation:
5906 External = GVA_TemplateInstantiation;
5907 break;
5908 }
5909 }
5910
5911 if (!FD->isInlined())
5912 return External;
5913
5914 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
5915 // GNU or C99 inline semantics. Determine whether this symbol should be
5916 // externally visible.
5917 if (FD->isInlineDefinitionExternallyVisible())
5918 return External;
5919
5920 // C99 inline semantics, where the symbol is not externally visible.
5921 return GVA_C99Inline;
5922 }
5923
5924 // C++0x [temp.explicit]p9:
5925 // [ Note: The intent is that an inline function that is the subject of
5926 // an explicit instantiation declaration will still be implicitly
5927 // instantiated when used so that the body can be considered for
5928 // inlining, but that no out-of-line copy of the inline function would be
5929 // generated in the translation unit. -- end note ]
5930 if (FD->getTemplateSpecializationKind()
5931 == TSK_ExplicitInstantiationDeclaration)
5932 return GVA_C99Inline;
5933
5934 return GVA_CXXInline;
5935}
5936
5937GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
5938 // If this is a static data member, compute the kind of template
5939 // specialization. Otherwise, this variable is not part of a
5940 // template.
5941 TemplateSpecializationKind TSK = TSK_Undeclared;
5942 if (VD->isStaticDataMember())
5943 TSK = VD->getTemplateSpecializationKind();
5944
5945 Linkage L = VD->getLinkage();
5946 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
5947 VD->getType()->getLinkage() == UniqueExternalLinkage)
5948 L = UniqueExternalLinkage;
5949
5950 switch (L) {
5951 case NoLinkage:
5952 case InternalLinkage:
5953 case UniqueExternalLinkage:
5954 return GVA_Internal;
5955
5956 case ExternalLinkage:
5957 switch (TSK) {
5958 case TSK_Undeclared:
5959 case TSK_ExplicitSpecialization:
5960 return GVA_StrongExternal;
5961
5962 case TSK_ExplicitInstantiationDeclaration:
5963 llvm_unreachable("Variable should not be instantiated");
5964 // Fall through to treat this like any other instantiation.
5965
5966 case TSK_ExplicitInstantiationDefinition:
5967 return GVA_ExplicitTemplateInstantiation;
5968
5969 case TSK_ImplicitInstantiation:
5970 return GVA_TemplateInstantiation;
5971 }
5972 }
5973
5974 return GVA_StrongExternal;
5975}
5976
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00005977bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005978 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
5979 if (!VD->isFileVarDecl())
5980 return false;
5981 } else if (!isa<FunctionDecl>(D))
5982 return false;
5983
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00005984 // Weak references don't produce any output by themselves.
5985 if (D->hasAttr<WeakRefAttr>())
5986 return false;
5987
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00005988 // Aliases and used decls are required.
5989 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
5990 return true;
5991
5992 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5993 // Forward declarations aren't required.
5994 if (!FD->isThisDeclarationADefinition())
5995 return false;
5996
5997 // Constructors and destructors are required.
5998 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
5999 return true;
6000
6001 // The key function for a class is required.
6002 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6003 const CXXRecordDecl *RD = MD->getParent();
6004 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6005 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6006 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6007 return true;
6008 }
6009 }
6010
6011 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6012
6013 // static, static inline, always_inline, and extern inline functions can
6014 // always be deferred. Normal inline functions can be deferred in C99/C++.
6015 // Implicit template instantiations can also be deferred in C++.
6016 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6017 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6018 return false;
6019 return true;
6020 }
6021
6022 const VarDecl *VD = cast<VarDecl>(D);
6023 assert(VD->isFileVarDecl() && "Expected file scoped var");
6024
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006025 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6026 return false;
6027
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006028 // Structs that have non-trivial constructors or destructors are required.
6029
6030 // FIXME: Handle references.
6031 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6032 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00006033 if (RD->hasDefinition() &&
6034 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006035 return true;
6036 }
6037 }
6038
6039 GVALinkage L = GetGVALinkageForVariable(VD);
6040 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6041 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6042 return false;
6043 }
6044
6045 return true;
6046}
Charles Davis071cc7d2010-08-16 03:33:14 +00006047
Charles Davisee743f92010-11-09 18:04:24 +00006048CallingConv ASTContext::getDefaultMethodCallConv() {
6049 // Pass through to the C++ ABI object
6050 return ABI->getDefaultMethodCallConv();
6051}
6052
Jay Foad4ba2a172011-01-12 09:06:06 +00006053bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006054 // Pass through to the C++ ABI object
6055 return ABI->isNearlyEmpty(RD);
6056}
6057
Peter Collingbourne14110472011-01-13 18:57:25 +00006058MangleContext *ASTContext::createMangleContext() {
6059 switch (Target.getCXXABI()) {
6060 case CXXABI_ARM:
6061 case CXXABI_Itanium:
6062 return createItaniumMangleContext(*this, getDiagnostics());
6063 case CXXABI_Microsoft:
6064 return createMicrosoftMangleContext(*this, getDiagnostics());
6065 }
6066 assert(0 && "Unsupported ABI");
6067 return 0;
6068}
6069
Charles Davis071cc7d2010-08-16 03:33:14 +00006070CXXABI::~CXXABI() {}