blob: d5003be5dea2b21467fcb05bf3928f317eeb5063 [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"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000034#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000035
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
37
Douglas Gregor18274032010-07-03 00:47:00 +000038unsigned ASTContext::NumImplicitDefaultConstructors;
39unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000040unsigned ASTContext::NumImplicitCopyConstructors;
41unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000042unsigned ASTContext::NumImplicitCopyAssignmentOperators;
43unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000044unsigned ASTContext::NumImplicitDestructors;
45unsigned ASTContext::NumImplicitDestructorsDeclared;
46
Reid Spencer5f016e22007-07-11 17:01:13 +000047enum FloatingRank {
48 FloatRank, DoubleRank, LongDoubleRank
49};
50
Douglas Gregor3e1274f2010-06-16 21:09:37 +000051void
52ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
53 TemplateTemplateParmDecl *Parm) {
54 ID.AddInteger(Parm->getDepth());
55 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +000056 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000057
58 TemplateParameterList *Params = Parm->getTemplateParameters();
59 ID.AddInteger(Params->size());
60 for (TemplateParameterList::const_iterator P = Params->begin(),
61 PEnd = Params->end();
62 P != PEnd; ++P) {
63 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
64 ID.AddInteger(0);
65 ID.AddBoolean(TTP->isParameterPack());
66 continue;
67 }
68
69 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
70 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +000071 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000072 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +000073 if (NTTP->isExpandedParameterPack()) {
74 ID.AddBoolean(true);
75 ID.AddInteger(NTTP->getNumExpansionTypes());
76 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
77 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
78 } else
79 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +000080 continue;
81 }
82
83 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
84 ID.AddInteger(2);
85 Profile(ID, TTP);
86 }
87}
88
89TemplateTemplateParmDecl *
90ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000091 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000092 // Check if we already have a canonical template template parameter.
93 llvm::FoldingSetNodeID ID;
94 CanonicalTemplateTemplateParm::Profile(ID, TTP);
95 void *InsertPos = 0;
96 CanonicalTemplateTemplateParm *Canonical
97 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
98 if (Canonical)
99 return Canonical->getParam();
100
101 // Build a canonical template parameter list.
102 TemplateParameterList *Params = TTP->getTemplateParameters();
103 llvm::SmallVector<NamedDecl *, 4> CanonParams;
104 CanonParams.reserve(Params->size());
105 for (TemplateParameterList::const_iterator P = Params->begin(),
106 PEnd = Params->end();
107 P != PEnd; ++P) {
108 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
109 CanonParams.push_back(
110 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000111 SourceLocation(),
112 SourceLocation(),
113 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000114 TTP->getIndex(), 0, false,
115 TTP->isParameterPack()));
116 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000117 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
118 QualType T = getCanonicalType(NTTP->getType());
119 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
120 NonTypeTemplateParmDecl *Param;
121 if (NTTP->isExpandedParameterPack()) {
122 llvm::SmallVector<QualType, 2> ExpandedTypes;
123 llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
124 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
125 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
126 ExpandedTInfos.push_back(
127 getTrivialTypeSourceInfo(ExpandedTypes.back()));
128 }
129
130 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000131 SourceLocation(),
132 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000133 NTTP->getDepth(),
134 NTTP->getPosition(), 0,
135 T,
136 TInfo,
137 ExpandedTypes.data(),
138 ExpandedTypes.size(),
139 ExpandedTInfos.data());
140 } else {
141 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000142 SourceLocation(),
143 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000144 NTTP->getDepth(),
145 NTTP->getPosition(), 0,
146 T,
147 NTTP->isParameterPack(),
148 TInfo);
149 }
150 CanonParams.push_back(Param);
151
152 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000153 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
154 cast<TemplateTemplateParmDecl>(*P)));
155 }
156
157 TemplateTemplateParmDecl *CanonTTP
158 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
159 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000160 TTP->getPosition(),
161 TTP->isParameterPack(),
162 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000163 TemplateParameterList::Create(*this, SourceLocation(),
164 SourceLocation(),
165 CanonParams.data(),
166 CanonParams.size(),
167 SourceLocation()));
168
169 // Get the new insert position for the node we care about.
170 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
171 assert(Canonical == 0 && "Shouldn't be in the map!");
172 (void)Canonical;
173
174 // Create the canonical template template parameter entry.
175 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
176 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
177 return CanonTTP;
178}
179
Charles Davis071cc7d2010-08-16 03:33:14 +0000180CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000181 if (!LangOpts.CPlusPlus) return 0;
182
Charles Davis20cf7172010-08-19 02:18:14 +0000183 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000184 case CXXABI_ARM:
185 return CreateARMCXXABI(*this);
186 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000187 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000188 case CXXABI_Microsoft:
189 return CreateMicrosoftCXXABI(*this);
190 }
John McCallee79a4c2010-08-21 22:46:04 +0000191 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000192}
193
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000194static const LangAS::Map &getAddressSpaceMap(const TargetInfo &T,
195 const LangOptions &LOpts) {
196 if (LOpts.FakeAddressSpaceMap) {
197 // The fake address space map must have a distinct entry for each
198 // language-specific address space.
199 static const unsigned FakeAddrSpaceMap[] = {
200 1, // opencl_global
201 2, // opencl_local
202 3 // opencl_constant
203 };
204 return FakeAddrSpaceMap;
205 } else {
206 return T.getAddressSpaceMap();
207 }
208}
209
Chris Lattner61710852008-10-05 17:34:18 +0000210ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +0000211 const TargetInfo &t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000212 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000213 Builtin::Context &builtins,
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000214 unsigned size_reserve) :
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000215 FunctionProtoTypes(this_()),
John McCallef990012010-06-11 11:07:21 +0000216 TemplateSpecializationTypes(this_()),
217 DependentTemplateSpecializationTypes(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000218 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
219 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
Mike Stump782fa302009-07-28 02:25:19 +0000220 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
Mike Stump083c25e2009-10-22 00:49:09 +0000221 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
Peter Collingbourne14b6ba72011-02-09 21:04:32 +0000222 cudaConfigureCallDecl(0),
John McCallbf1a0282010-06-04 23:28:52 +0000223 NullTypeSourceInfo(QualType()),
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000224 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
225 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000226 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000227 BuiltinInfo(builtins),
228 DeclarationNames(*this),
Argyrios Kyrtzidis9a44b5f2010-10-28 09:29:35 +0000229 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000230 LastSDM(0, 0),
John McCall8178df32011-02-22 22:38:33 +0000231 UniqueBlockByRefTypeID(0) {
David Chisnall0f436562009-08-17 16:35:33 +0000232 ObjCIdRedefinitionType = QualType();
233 ObjCClassRedefinitionType = QualType();
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000234 ObjCSelRedefinitionType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000235 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000236 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000237 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000238}
239
Reid Spencer5f016e22007-07-11 17:01:13 +0000240ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000241 // Release the DenseMaps associated with DeclContext objects.
242 // FIXME: Is this the ideal solution?
243 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000244
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000245 // Call all of the deallocation functions.
246 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
247 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000248
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000249 // Release all of the memory associated with overridden C++ methods.
250 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
251 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
252 OM != OMEnd; ++OM)
253 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000254
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000255 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000256 // because they can contain DenseMaps.
257 for (llvm::DenseMap<const ObjCContainerDecl*,
258 const ASTRecordLayout*>::iterator
259 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
260 // Increment in loop to prevent using deallocated memory.
261 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
262 R->Destroy(*this);
263
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000264 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
265 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
266 // Increment in loop to prevent using deallocated memory.
267 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
268 R->Destroy(*this);
269 }
Douglas Gregor63200642010-08-30 16:49:28 +0000270
271 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
272 AEnd = DeclAttrs.end();
273 A != AEnd; ++A)
274 A->second->~AttrVec();
275}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000276
Douglas Gregor00545312010-05-23 18:26:36 +0000277void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
278 Deallocations.push_back(std::make_pair(Callback, Data));
279}
280
Mike Stump1eb44332009-09-09 15:08:12 +0000281void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000282ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
283 ExternalSource.reset(Source.take());
284}
285
Reid Spencer5f016e22007-07-11 17:01:13 +0000286void ASTContext::PrintStats() const {
287 fprintf(stderr, "*** AST Context Stats:\n");
288 fprintf(stderr, " %d types total.\n", (int)Types.size());
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000289
Douglas Gregordbe833d2009-05-26 14:40:08 +0000290 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000291#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000292#define ABSTRACT_TYPE(Name, Parent)
293#include "clang/AST/TypeNodes.def"
294 0 // Extra
295 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000296
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
298 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000299 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 }
301
Douglas Gregordbe833d2009-05-26 14:40:08 +0000302 unsigned Idx = 0;
303 unsigned TotalBytes = 0;
304#define TYPE(Name, Parent) \
305 if (counts[Idx]) \
306 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
307 TotalBytes += counts[Idx] * sizeof(Name##Type); \
308 ++Idx;
309#define ABSTRACT_TYPE(Name, Parent)
310#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Douglas Gregordbe833d2009-05-26 14:40:08 +0000312 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
Douglas Gregored8abf12010-07-08 06:14:04 +0000313
Douglas Gregor4923aa22010-07-02 20:37:36 +0000314 // Implicit special member functions.
Douglas Gregor18274032010-07-03 00:47:00 +0000315 fprintf(stderr, " %u/%u implicit default constructors created\n",
316 NumImplicitDefaultConstructorsDeclared,
317 NumImplicitDefaultConstructors);
Douglas Gregor22584312010-07-02 23:41:54 +0000318 fprintf(stderr, " %u/%u implicit copy constructors created\n",
319 NumImplicitCopyConstructorsDeclared,
320 NumImplicitCopyConstructors);
Douglas Gregora376d102010-07-02 21:50:04 +0000321 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
322 NumImplicitCopyAssignmentOperatorsDeclared,
323 NumImplicitCopyAssignmentOperators);
Douglas Gregor4923aa22010-07-02 20:37:36 +0000324 fprintf(stderr, " %u/%u implicit destructors created\n",
325 NumImplicitDestructorsDeclared, NumImplicitDestructors);
326
Douglas Gregor2cf26342009-04-09 22:27:44 +0000327 if (ExternalSource.get()) {
328 fprintf(stderr, "\n");
329 ExternalSource->PrintStats();
330 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000331
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000332 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000333}
334
335
John McCalle27ec8a2009-10-23 23:03:21 +0000336void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000337 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000338 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000339 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000340}
341
Reid Spencer5f016e22007-07-11 17:01:13 +0000342void ASTContext::InitBuiltinTypes() {
343 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 // C99 6.2.5p19.
346 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 // C99 6.2.5p2.
349 InitBuiltinType(BoolTy, BuiltinType::Bool);
350 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000351 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 InitBuiltinType(CharTy, BuiltinType::Char_S);
353 else
354 InitBuiltinType(CharTy, BuiltinType::Char_U);
355 // C99 6.2.5p4.
356 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
357 InitBuiltinType(ShortTy, BuiltinType::Short);
358 InitBuiltinType(IntTy, BuiltinType::Int);
359 InitBuiltinType(LongTy, BuiltinType::Long);
360 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 // C99 6.2.5p6.
363 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
364 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
365 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
366 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
367 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 // C99 6.2.5p10.
370 InitBuiltinType(FloatTy, BuiltinType::Float);
371 InitBuiltinType(DoubleTy, BuiltinType::Double);
372 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000373
Chris Lattner2df9ced2009-04-30 02:43:43 +0000374 // GNU extension, 128-bit integers.
375 InitBuiltinType(Int128Ty, BuiltinType::Int128);
376 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
377
Chris Lattner3f59c972010-12-25 23:25:43 +0000378 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000379 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000380 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
381 else // -fshort-wchar makes wchar_t be unsigned.
382 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
383 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000384 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000385
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000386 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
387 InitBuiltinType(Char16Ty, BuiltinType::Char16);
388 else // C99
389 Char16Ty = getFromTargetType(Target.getChar16Type());
390
391 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
392 InitBuiltinType(Char32Ty, BuiltinType::Char32);
393 else // C99
394 Char32Ty = getFromTargetType(Target.getChar32Type());
395
Douglas Gregor898574e2008-12-05 23:32:09 +0000396 // Placeholder type for type-dependent expressions whose type is
397 // completely unknown. No code should ever check a type against
398 // DependentTy and users should never see it; however, it is here to
399 // help diagnose failures to properly check for type-dependent
400 // expressions.
401 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000402
John McCall2a984ca2010-10-12 00:20:44 +0000403 // Placeholder type for functions.
404 InitBuiltinType(OverloadTy, BuiltinType::Overload);
405
John McCall864c0412011-04-26 20:42:42 +0000406 // Placeholder type for bound members.
407 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
408
John McCall1de4d4e2011-04-07 08:22:57 +0000409 // "any" type; useful for debugger-like clients.
410 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 // C99 6.2.5p11.
413 FloatComplexTy = getComplexType(FloatTy);
414 DoubleComplexTy = getComplexType(DoubleTy);
415 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000416
Steve Naroff7e219e42007-10-15 14:41:52 +0000417 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Steve Naroffde2e22d2009-07-15 18:40:39 +0000419 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
420 ObjCIdTypedefType = QualType();
421 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000422 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000424 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000425 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
426 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000427 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000428
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000429 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000431 // void * type
432 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000433
434 // nullptr type (C++0x 2.14.7)
435 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000436}
437
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000438Diagnostic &ASTContext::getDiagnostics() const {
439 return SourceMgr.getDiagnostics();
440}
441
Douglas Gregor63200642010-08-30 16:49:28 +0000442AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
443 AttrVec *&Result = DeclAttrs[D];
444 if (!Result) {
445 void *Mem = Allocate(sizeof(AttrVec));
446 Result = new (Mem) AttrVec;
447 }
448
449 return *Result;
450}
451
452/// \brief Erase the attributes corresponding to the given declaration.
453void ASTContext::eraseDeclAttrs(const Decl *D) {
454 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
455 if (Pos != DeclAttrs.end()) {
456 Pos->second->~AttrVec();
457 DeclAttrs.erase(Pos);
458 }
459}
460
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000461MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000462ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000463 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000464 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000465 = InstantiatedFromStaticDataMember.find(Var);
466 if (Pos == InstantiatedFromStaticDataMember.end())
467 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Douglas Gregor7caa6822009-07-24 20:34:43 +0000469 return Pos->second;
470}
471
Mike Stump1eb44332009-09-09 15:08:12 +0000472void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000473ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000474 TemplateSpecializationKind TSK,
475 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000476 assert(Inst->isStaticDataMember() && "Not a static data member");
477 assert(Tmpl->isStaticDataMember() && "Not a static data member");
478 assert(!InstantiatedFromStaticDataMember[Inst] &&
479 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000480 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000481 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000482}
483
John McCall7ba107a2009-11-18 02:36:19 +0000484NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000485ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000486 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000487 = InstantiatedFromUsingDecl.find(UUD);
488 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000489 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Anders Carlsson0d8df782009-08-29 19:37:28 +0000491 return Pos->second;
492}
493
494void
John McCalled976492009-12-04 22:46:56 +0000495ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
496 assert((isa<UsingDecl>(Pattern) ||
497 isa<UnresolvedUsingValueDecl>(Pattern) ||
498 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
499 "pattern decl is not a using decl");
500 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
501 InstantiatedFromUsingDecl[Inst] = Pattern;
502}
503
504UsingShadowDecl *
505ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
506 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
507 = InstantiatedFromUsingShadowDecl.find(Inst);
508 if (Pos == InstantiatedFromUsingShadowDecl.end())
509 return 0;
510
511 return Pos->second;
512}
513
514void
515ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
516 UsingShadowDecl *Pattern) {
517 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
518 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000519}
520
Anders Carlssond8b285f2009-09-01 04:26:58 +0000521FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
522 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
523 = InstantiatedFromUnnamedFieldDecl.find(Field);
524 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
525 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Anders Carlssond8b285f2009-09-01 04:26:58 +0000527 return Pos->second;
528}
529
530void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
531 FieldDecl *Tmpl) {
532 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
533 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
534 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
535 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Anders Carlssond8b285f2009-09-01 04:26:58 +0000537 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
538}
539
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000540bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
541 const FieldDecl *LastFD) const {
542 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
543 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0);
544
545}
546
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000547bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
548 const FieldDecl *LastFD) const {
549 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Fariborz Jahaniancc0f9f12011-05-03 22:07:14 +0000550 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0 &&
551 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000552
553}
554
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000555bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
556 const FieldDecl *LastFD) const {
557 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
558 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() &&
559 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
560}
561
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000562bool ASTContext::NoneBitfieldFollowsBitfield(const FieldDecl *FD,
563 const FieldDecl *LastFD) const {
564 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
565 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
566}
567
568bool ASTContext::BitfieldFollowsNoneBitfield(const FieldDecl *FD,
569 const FieldDecl *LastFD) const {
570 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
571 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
572}
573
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000574ASTContext::overridden_cxx_method_iterator
575ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
576 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
577 = OverriddenMethods.find(Method);
578 if (Pos == OverriddenMethods.end())
579 return 0;
580
581 return Pos->second.begin();
582}
583
584ASTContext::overridden_cxx_method_iterator
585ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
586 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
587 = OverriddenMethods.find(Method);
588 if (Pos == OverriddenMethods.end())
589 return 0;
590
591 return Pos->second.end();
592}
593
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000594unsigned
595ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
596 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
597 = OverriddenMethods.find(Method);
598 if (Pos == OverriddenMethods.end())
599 return 0;
600
601 return Pos->second.size();
602}
603
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000604void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
605 const CXXMethodDecl *Overridden) {
606 OverriddenMethods[Method].push_back(Overridden);
607}
608
Chris Lattner464175b2007-07-18 17:52:12 +0000609//===----------------------------------------------------------------------===//
610// Type Sizing and Analysis
611//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000612
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000613/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
614/// scalar floating point type.
615const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000616 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000617 assert(BT && "Not a floating point type!");
618 switch (BT->getKind()) {
619 default: assert(0 && "Not a floating point type!");
620 case BuiltinType::Float: return Target.getFloatFormat();
621 case BuiltinType::Double: return Target.getDoubleFormat();
622 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
623 }
624}
625
Ken Dyck8b752f12010-01-27 17:10:57 +0000626/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000627/// specified decl. Note that bitfields do not have a valid alignment, so
628/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000629/// If @p RefAsPointee, references are treated like their underlying type
630/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000631CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000632 unsigned Align = Target.getCharWidth();
633
John McCall4081a5c2010-10-08 18:24:19 +0000634 bool UseAlignAttrOnly = false;
635 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
636 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000637
John McCall4081a5c2010-10-08 18:24:19 +0000638 // __attribute__((aligned)) can increase or decrease alignment
639 // *except* on a struct or struct member, where it only increases
640 // alignment unless 'packed' is also specified.
641 //
642 // It is an error for [[align]] to decrease alignment, so we can
643 // ignore that possibility; Sema should diagnose it.
644 if (isa<FieldDecl>(D)) {
645 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
646 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
647 } else {
648 UseAlignAttrOnly = true;
649 }
650 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000651 else if (isa<FieldDecl>(D))
652 UseAlignAttrOnly =
653 D->hasAttr<PackedAttr>() ||
654 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000655
John McCallba4f5d52011-01-20 07:57:12 +0000656 // If we're using the align attribute only, just ignore everything
657 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000658 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000659 // do nothing
660
John McCall4081a5c2010-10-08 18:24:19 +0000661 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000662 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000663 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000664 if (RefAsPointee)
665 T = RT->getPointeeType();
666 else
667 T = getPointerType(RT->getPointeeType());
668 }
669 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000670 // Adjust alignments of declarations with array type by the
671 // large-array alignment on the target.
Rafael Espindola6deecb02010-06-04 23:15:27 +0000672 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000673 const ArrayType *arrayType;
674 if (MinWidth && (arrayType = getAsArrayType(T))) {
675 if (isa<VariableArrayType>(arrayType))
676 Align = std::max(Align, Target.getLargeArrayAlign());
677 else if (isa<ConstantArrayType>(arrayType) &&
678 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
679 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000680
John McCall3b657512011-01-19 10:06:00 +0000681 // Walk through any array types while we're at it.
682 T = getBaseElementType(arrayType);
683 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000684 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
685 }
John McCallba4f5d52011-01-20 07:57:12 +0000686
687 // Fields can be subject to extra alignment constraints, like if
688 // the field is packed, the struct is packed, or the struct has a
689 // a max-field-alignment constraint (#pragma pack). So calculate
690 // the actual alignment of the field within the struct, and then
691 // (as we're expected to) constrain that by the alignment of the type.
692 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
693 // So calculate the alignment of the field.
694 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
695
696 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000697 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000698
699 // Use the GCD of that and the offset within the record.
700 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
701 if (offset > 0) {
702 // Alignment is always a power of 2, so the GCD will be a power of 2,
703 // which means we get to do this crazy thing instead of Euclid's.
704 uint64_t lowBitOfOffset = offset & (~offset + 1);
705 if (lowBitOfOffset < fieldAlign)
706 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
707 }
708
709 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000710 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000711 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000712
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000713 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000714}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000715
John McCallea1471e2010-05-20 01:18:31 +0000716std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000717ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000718 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000719 return std::make_pair(toCharUnitsFromBits(Info.first),
720 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000721}
722
723std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000724ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000725 return getTypeInfoInChars(T.getTypePtr());
726}
727
Chris Lattnera7674d82007-07-13 22:13:22 +0000728/// getTypeSize - Return the size of the specified type, in bits. This method
729/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000730///
731/// FIXME: Pointers into different addr spaces could have different sizes and
732/// alignment requirements: getPointerInfo should take an AddrSpace, this
733/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000734std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000735ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000736 uint64_t Width=0;
737 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000738 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000739#define TYPE(Class, Base)
740#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000741#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000742#define DEPENDENT_TYPE(Class, Base) case Type::Class:
743#include "clang/AST/TypeNodes.def"
Douglas Gregor18857642009-04-30 17:32:17 +0000744 assert(false && "Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000745 break;
746
Chris Lattner692233e2007-07-13 22:27:08 +0000747 case Type::FunctionNoProto:
748 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000749 // GCC extension: alignof(function) = 32 bits
750 Width = 0;
751 Align = 32;
752 break;
753
Douglas Gregor72564e72009-02-26 23:50:07 +0000754 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000755 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000756 Width = 0;
757 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
758 break;
759
Steve Narofffb22d962007-08-30 01:06:46 +0000760 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000761 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Chris Lattner98be4942008-03-05 18:54:05 +0000763 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000764 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000765 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000766 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000767 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000768 }
Nate Begeman213541a2008-04-18 23:10:10 +0000769 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000770 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000771 const VectorType *VT = cast<VectorType>(T);
772 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
773 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000774 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000775 // If the alignment is not a power of 2, round up to the next power of 2.
776 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000777 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000778 Align = llvm::NextPowerOf2(Align);
779 Width = llvm::RoundUpToAlignment(Width, Align);
780 }
Chris Lattner030d8842007-07-19 22:06:24 +0000781 break;
782 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000783
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000784 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000785 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000786 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000787 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000788 // GCC extension: alignof(void) = 8 bits.
789 Width = 0;
790 Align = 8;
791 break;
792
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000793 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000794 Width = Target.getBoolWidth();
795 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000796 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000797 case BuiltinType::Char_S:
798 case BuiltinType::Char_U:
799 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000800 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000801 Width = Target.getCharWidth();
802 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000803 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000804 case BuiltinType::WChar_S:
805 case BuiltinType::WChar_U:
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000806 Width = Target.getWCharWidth();
807 Align = Target.getWCharAlign();
808 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000809 case BuiltinType::Char16:
810 Width = Target.getChar16Width();
811 Align = Target.getChar16Align();
812 break;
813 case BuiltinType::Char32:
814 Width = Target.getChar32Width();
815 Align = Target.getChar32Align();
816 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000817 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000818 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000819 Width = Target.getShortWidth();
820 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000821 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000822 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000823 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000824 Width = Target.getIntWidth();
825 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000826 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000827 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000828 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000829 Width = Target.getLongWidth();
830 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000831 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000832 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000833 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000834 Width = Target.getLongLongWidth();
835 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000836 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000837 case BuiltinType::Int128:
838 case BuiltinType::UInt128:
839 Width = 128;
840 Align = 128; // int128_t is 128-bit aligned on all targets.
841 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000842 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000843 Width = Target.getFloatWidth();
844 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000845 break;
846 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000847 Width = Target.getDoubleWidth();
848 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000849 break;
850 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000851 Width = Target.getLongDoubleWidth();
852 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000853 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000854 case BuiltinType::NullPtr:
855 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
856 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000857 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000858 case BuiltinType::ObjCId:
859 case BuiltinType::ObjCClass:
860 case BuiltinType::ObjCSel:
861 Width = Target.getPointerWidth(0);
862 Align = Target.getPointerAlign(0);
863 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000864 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000865 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000866 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000867 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000868 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000869 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000870 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000871 unsigned AS = getTargetAddressSpace(
872 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff485eeff2008-09-24 15:05:44 +0000873 Width = Target.getPointerWidth(AS);
874 Align = Target.getPointerAlign(AS);
875 break;
876 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000877 case Type::LValueReference:
878 case Type::RValueReference: {
879 // alignof and sizeof should never enter this code path here, so we go
880 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000881 unsigned AS = getTargetAddressSpace(
882 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl5d484e82009-11-23 17:18:46 +0000883 Width = Target.getPointerWidth(AS);
884 Align = Target.getPointerAlign(AS);
885 break;
886 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000887 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000888 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner5426bf62008-04-07 07:01:58 +0000889 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000890 Align = Target.getPointerAlign(AS);
891 break;
892 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000893 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000894 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000895 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000896 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000897 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000898 Align = PtrDiffInfo.second;
899 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000900 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000901 case Type::Complex: {
902 // Complex types have the same alignment as their elements, but twice the
903 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000904 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000905 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000906 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000907 Align = EltInfo.second;
908 break;
909 }
John McCallc12c5bb2010-05-15 11:32:37 +0000910 case Type::ObjCObject:
911 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000912 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000913 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000914 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000915 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000916 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +0000917 break;
918 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000919 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000920 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000921 const TagType *TT = cast<TagType>(T);
922
923 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +0000924 Width = 8;
925 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +0000926 break;
927 }
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Daniel Dunbar1d751182008-11-08 05:48:37 +0000929 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000930 return getTypeInfo(ET->getDecl()->getIntegerType());
931
Daniel Dunbar1d751182008-11-08 05:48:37 +0000932 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000933 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000934 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000935 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000936 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000937 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000938
Chris Lattner9fcfe922009-10-22 05:17:15 +0000939 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000940 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
941 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000942
Richard Smith34b41d92011-02-20 03:19:35 +0000943 case Type::Auto: {
944 const AutoType *A = cast<AutoType>(T);
945 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +0000946 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +0000947 }
948
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000949 case Type::Paren:
950 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
951
Douglas Gregor18857642009-04-30 17:32:17 +0000952 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +0000953 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000954 std::pair<uint64_t, unsigned> Info
955 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +0000956 // If the typedef has an aligned attribute on it, it overrides any computed
957 // alignment we have. This violates the GCC documentation (which says that
958 // attribute(aligned) can only round up) but matches its implementation.
959 if (unsigned AttrAlign = Typedef->getMaxAlignment())
960 Align = AttrAlign;
961 else
962 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +0000963 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000964 break;
Chris Lattner71763312008-04-06 22:05:18 +0000965 }
Douglas Gregor18857642009-04-30 17:32:17 +0000966
967 case Type::TypeOfExpr:
968 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
969 .getTypePtr());
970
971 case Type::TypeOf:
972 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
973
Anders Carlsson395b4752009-06-24 19:06:50 +0000974 case Type::Decltype:
975 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
976 .getTypePtr());
977
Sean Huntca63c202011-05-24 22:41:36 +0000978 case Type::UnaryTransform:
979 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
980
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000981 case Type::Elaborated:
982 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000983
John McCall9d156a72011-01-06 01:58:22 +0000984 case Type::Attributed:
985 return getTypeInfo(
986 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
987
Richard Smith3e4c6c42011-05-05 21:57:07 +0000988 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +0000989 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +0000990 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +0000991 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
992 // A type alias template specialization may refer to a typedef with the
993 // aligned attribute on it.
994 if (TST->isTypeAlias())
995 return getTypeInfo(TST->getAliasedType().getTypePtr());
996 else
997 return getTypeInfo(getCanonicalType(T));
998 }
999
Douglas Gregor18857642009-04-30 17:32:17 +00001000 }
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Chris Lattner464175b2007-07-18 17:52:12 +00001002 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001003 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001004}
1005
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001006/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1007CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1008 return CharUnits::fromQuantity(BitSize / getCharWidth());
1009}
1010
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001011/// toBits - Convert a size in characters to a size in characters.
1012int64_t ASTContext::toBits(CharUnits CharSize) const {
1013 return CharSize.getQuantity() * getCharWidth();
1014}
1015
Ken Dyckbdc601b2009-12-22 14:23:30 +00001016/// getTypeSizeInChars - Return the size of the specified type, in characters.
1017/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001018CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001019 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001020}
Jay Foad4ba2a172011-01-12 09:06:06 +00001021CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001022 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001023}
1024
Ken Dyck16e20cc2010-01-26 17:25:18 +00001025/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001026/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001027CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001028 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001029}
Jay Foad4ba2a172011-01-12 09:06:06 +00001030CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001031 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001032}
1033
Chris Lattner34ebde42009-01-27 18:08:34 +00001034/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1035/// type for the current target in bits. This can be different than the ABI
1036/// alignment in cases where it is beneficial for performance to overalign
1037/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001038unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001039 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001040
1041 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001042 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001043 T = CT->getElementType().getTypePtr();
1044 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1045 T->isSpecificBuiltinType(BuiltinType::LongLong))
1046 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1047
Chris Lattner34ebde42009-01-27 18:08:34 +00001048 return ABIAlign;
1049}
1050
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001051/// ShallowCollectObjCIvars -
1052/// Collect all ivars, including those synthesized, in the current class.
1053///
1054void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
Jay Foad4ba2a172011-01-12 09:06:06 +00001055 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001056 // FIXME. This need be removed but there are two many places which
1057 // assume const-ness of ObjCInterfaceDecl
1058 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1059 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1060 Iv= Iv->getNextIvar())
1061 Ivars.push_back(Iv);
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001062}
1063
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001064/// DeepCollectObjCIvars -
1065/// This routine first collects all declared, but not synthesized, ivars in
1066/// super class and then collects all ivars, including those synthesized for
1067/// current class. This routine is used for implementation of current class
1068/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001069///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001070void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1071 bool leafClass,
Jay Foad4ba2a172011-01-12 09:06:06 +00001072 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001073 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1074 DeepCollectObjCIvars(SuperClass, false, Ivars);
1075 if (!leafClass) {
1076 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1077 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001078 Ivars.push_back(*I);
1079 }
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001080 else
1081 ShallowCollectObjCIvars(OI, Ivars);
Fariborz Jahanian98200742009-05-12 18:14:29 +00001082}
1083
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001084/// CollectInheritedProtocols - Collect all protocols in current class and
1085/// those inherited by it.
1086void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001087 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001088 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001089 // We can use protocol_iterator here instead of
1090 // all_referenced_protocol_iterator since we are walking all categories.
1091 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1092 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001093 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001094 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001095 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001096 PE = Proto->protocol_end(); P != PE; ++P) {
1097 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001098 CollectInheritedProtocols(*P, Protocols);
1099 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001100 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001101
1102 // Categories of this Interface.
1103 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1104 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1105 CollectInheritedProtocols(CDeclChain, Protocols);
1106 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1107 while (SD) {
1108 CollectInheritedProtocols(SD, Protocols);
1109 SD = SD->getSuperClass();
1110 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001111 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001112 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001113 PE = OC->protocol_end(); P != PE; ++P) {
1114 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001115 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001116 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1117 PE = Proto->protocol_end(); P != PE; ++P)
1118 CollectInheritedProtocols(*P, Protocols);
1119 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001120 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001121 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1122 PE = OP->protocol_end(); P != PE; ++P) {
1123 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001124 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001125 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1126 PE = Proto->protocol_end(); P != PE; ++P)
1127 CollectInheritedProtocols(*P, Protocols);
1128 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001129 }
1130}
1131
Jay Foad4ba2a172011-01-12 09:06:06 +00001132unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001133 unsigned count = 0;
1134 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001135 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1136 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001137 count += CDecl->ivar_size();
1138
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001139 // Count ivar defined in this class's implementation. This
1140 // includes synthesized ivars.
1141 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001142 count += ImplDecl->ivar_size();
1143
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001144 return count;
1145}
1146
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001147/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1148ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1149 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1150 I = ObjCImpls.find(D);
1151 if (I != ObjCImpls.end())
1152 return cast<ObjCImplementationDecl>(I->second);
1153 return 0;
1154}
1155/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1156ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1157 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1158 I = ObjCImpls.find(D);
1159 if (I != ObjCImpls.end())
1160 return cast<ObjCCategoryImplDecl>(I->second);
1161 return 0;
1162}
1163
1164/// \brief Set the implementation of ObjCInterfaceDecl.
1165void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1166 ObjCImplementationDecl *ImplD) {
1167 assert(IFaceD && ImplD && "Passed null params");
1168 ObjCImpls[IFaceD] = ImplD;
1169}
1170/// \brief Set the implementation of ObjCCategoryDecl.
1171void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1172 ObjCCategoryImplDecl *ImplD) {
1173 assert(CatD && ImplD && "Passed null params");
1174 ObjCImpls[CatD] = ImplD;
1175}
1176
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001177/// \brief Get the copy initialization expression of VarDecl,or NULL if
1178/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001179Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001180 assert(VD && "Passed null params");
1181 assert(VD->hasAttr<BlocksAttr>() &&
1182 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001183 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001184 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001185 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1186}
1187
1188/// \brief Set the copy inialization expression of a block var decl.
1189void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1190 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001191 assert(VD->hasAttr<BlocksAttr>() &&
1192 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001193 BlockVarCopyInits[VD] = Init;
1194}
1195
John McCalla93c9342009-12-07 02:54:59 +00001196/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001197///
John McCalla93c9342009-12-07 02:54:59 +00001198/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001199/// the TypeLoc wrappers.
1200///
1201/// \param T the type that will be the basis for type source info. This type
1202/// should refer to how the declarator was written in source code, not to
1203/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001204TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001205 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001206 if (!DataSize)
1207 DataSize = TypeLoc::getFullDataSizeForType(T);
1208 else
1209 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001210 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001211
John McCalla93c9342009-12-07 02:54:59 +00001212 TypeSourceInfo *TInfo =
1213 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1214 new (TInfo) TypeSourceInfo(T);
1215 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001216}
1217
John McCalla93c9342009-12-07 02:54:59 +00001218TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001219 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001220 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001221 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001222 return DI;
1223}
1224
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001225const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001226ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001227 return getObjCLayout(D, 0);
1228}
1229
1230const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001231ASTContext::getASTObjCImplementationLayout(
1232 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001233 return getObjCLayout(D->getClassInterface(), D);
1234}
1235
Chris Lattnera7674d82007-07-13 22:13:22 +00001236//===----------------------------------------------------------------------===//
1237// Type creation/memoization methods
1238//===----------------------------------------------------------------------===//
1239
Jay Foad4ba2a172011-01-12 09:06:06 +00001240QualType
John McCall3b657512011-01-19 10:06:00 +00001241ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1242 unsigned fastQuals = quals.getFastQualifiers();
1243 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001244
1245 // Check if we've already instantiated this type.
1246 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001247 ExtQuals::Profile(ID, baseType, quals);
1248 void *insertPos = 0;
1249 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1250 assert(eq->getQualifiers() == quals);
1251 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001252 }
1253
John McCall3b657512011-01-19 10:06:00 +00001254 // If the base type is not canonical, make the appropriate canonical type.
1255 QualType canon;
1256 if (!baseType->isCanonicalUnqualified()) {
1257 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1258 canonSplit.second.addConsistentQualifiers(quals);
1259 canon = getExtQualType(canonSplit.first, canonSplit.second);
1260
1261 // Re-find the insert position.
1262 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1263 }
1264
1265 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1266 ExtQualNodes.InsertNode(eq, insertPos);
1267 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001268}
1269
Jay Foad4ba2a172011-01-12 09:06:06 +00001270QualType
1271ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001272 QualType CanT = getCanonicalType(T);
1273 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001274 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001275
John McCall0953e762009-09-24 19:53:00 +00001276 // If we are composing extended qualifiers together, merge together
1277 // into one ExtQuals node.
1278 QualifierCollector Quals;
1279 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001280
John McCall0953e762009-09-24 19:53:00 +00001281 // If this type already has an address space specified, it cannot get
1282 // another one.
1283 assert(!Quals.hasAddressSpace() &&
1284 "Type cannot be in multiple addr spaces!");
1285 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001286
John McCall0953e762009-09-24 19:53:00 +00001287 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001288}
1289
Chris Lattnerb7d25532009-02-18 22:53:11 +00001290QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001291 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001292 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001293 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001294 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001295
John McCall7f040a92010-12-24 02:08:15 +00001296 if (const PointerType *ptr = T->getAs<PointerType>()) {
1297 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001298 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001299 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1300 return getPointerType(ResultType);
1301 }
1302 }
Mike Stump1eb44332009-09-09 15:08:12 +00001303
John McCall0953e762009-09-24 19:53:00 +00001304 // If we are composing extended qualifiers together, merge together
1305 // into one ExtQuals node.
1306 QualifierCollector Quals;
1307 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001308
John McCall0953e762009-09-24 19:53:00 +00001309 // If this type already has an ObjCGC specified, it cannot get
1310 // another one.
1311 assert(!Quals.hasObjCGCAttr() &&
1312 "Type cannot have multiple ObjCGCs!");
1313 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001314
John McCall0953e762009-09-24 19:53:00 +00001315 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001316}
Chris Lattnera7674d82007-07-13 22:13:22 +00001317
John McCalle6a365d2010-12-19 02:44:49 +00001318const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1319 FunctionType::ExtInfo Info) {
1320 if (T->getExtInfo() == Info)
1321 return T;
1322
1323 QualType Result;
1324 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1325 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1326 } else {
1327 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1328 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1329 EPI.ExtInfo = Info;
1330 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1331 FPT->getNumArgs(), EPI);
1332 }
1333
1334 return cast<FunctionType>(Result.getTypePtr());
1335}
1336
Reid Spencer5f016e22007-07-11 17:01:13 +00001337/// getComplexType - Return the uniqued reference to the type for a complex
1338/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001339QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 // Unique pointers, to guarantee there is only one pointer of a particular
1341 // structure.
1342 llvm::FoldingSetNodeID ID;
1343 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Reid Spencer5f016e22007-07-11 17:01:13 +00001345 void *InsertPos = 0;
1346 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1347 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 // If the pointee type isn't canonical, this won't be a canonical type either,
1350 // so fill in the canonical type field.
1351 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001352 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001353 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Reid Spencer5f016e22007-07-11 17:01:13 +00001355 // Get the new insert position for the node we care about.
1356 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001357 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001358 }
John McCall6b304a02009-09-24 23:30:46 +00001359 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 Types.push_back(New);
1361 ComplexTypes.InsertNode(New, InsertPos);
1362 return QualType(New, 0);
1363}
1364
Reid Spencer5f016e22007-07-11 17:01:13 +00001365/// getPointerType - Return the uniqued reference to the type for a pointer to
1366/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001367QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001368 // Unique pointers, to guarantee there is only one pointer of a particular
1369 // structure.
1370 llvm::FoldingSetNodeID ID;
1371 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 void *InsertPos = 0;
1374 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1375 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Reid Spencer5f016e22007-07-11 17:01:13 +00001377 // If the pointee type isn't canonical, this won't be a canonical type either,
1378 // so fill in the canonical type field.
1379 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001380 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001381 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001382
Reid Spencer5f016e22007-07-11 17:01:13 +00001383 // Get the new insert position for the node we care about.
1384 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001385 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001386 }
John McCall6b304a02009-09-24 23:30:46 +00001387 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 Types.push_back(New);
1389 PointerTypes.InsertNode(New, InsertPos);
1390 return QualType(New, 0);
1391}
1392
Mike Stump1eb44332009-09-09 15:08:12 +00001393/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001394/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001395QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001396 assert(T->isFunctionType() && "block of function types only");
1397 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001398 // structure.
1399 llvm::FoldingSetNodeID ID;
1400 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Steve Naroff5618bd42008-08-27 16:04:49 +00001402 void *InsertPos = 0;
1403 if (BlockPointerType *PT =
1404 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1405 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001406
1407 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001408 // type either so fill in the canonical type field.
1409 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001410 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001411 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Steve Naroff5618bd42008-08-27 16:04:49 +00001413 // Get the new insert position for the node we care about.
1414 BlockPointerType *NewIP =
1415 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001416 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001417 }
John McCall6b304a02009-09-24 23:30:46 +00001418 BlockPointerType *New
1419 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001420 Types.push_back(New);
1421 BlockPointerTypes.InsertNode(New, InsertPos);
1422 return QualType(New, 0);
1423}
1424
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001425/// getLValueReferenceType - Return the uniqued reference to the type for an
1426/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001427QualType
1428ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001429 assert(getCanonicalType(T) != OverloadTy &&
1430 "Unresolved overloaded function type");
1431
Reid Spencer5f016e22007-07-11 17:01:13 +00001432 // Unique pointers, to guarantee there is only one pointer of a particular
1433 // structure.
1434 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001435 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001436
1437 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001438 if (LValueReferenceType *RT =
1439 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001440 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001441
John McCall54e14c42009-10-22 22:37:11 +00001442 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1443
Reid Spencer5f016e22007-07-11 17:01:13 +00001444 // If the referencee type isn't canonical, this won't be a canonical type
1445 // either, so fill in the canonical type field.
1446 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001447 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1448 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1449 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001450
Reid Spencer5f016e22007-07-11 17:01:13 +00001451 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001452 LValueReferenceType *NewIP =
1453 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001454 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001455 }
1456
John McCall6b304a02009-09-24 23:30:46 +00001457 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001458 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1459 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001461 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001462
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001463 return QualType(New, 0);
1464}
1465
1466/// getRValueReferenceType - Return the uniqued reference to the type for an
1467/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001468QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001469 // Unique pointers, to guarantee there is only one pointer of a particular
1470 // structure.
1471 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001472 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001473
1474 void *InsertPos = 0;
1475 if (RValueReferenceType *RT =
1476 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1477 return QualType(RT, 0);
1478
John McCall54e14c42009-10-22 22:37:11 +00001479 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1480
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001481 // If the referencee type isn't canonical, this won't be a canonical type
1482 // either, so fill in the canonical type field.
1483 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001484 if (InnerRef || !T.isCanonical()) {
1485 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1486 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001487
1488 // Get the new insert position for the node we care about.
1489 RValueReferenceType *NewIP =
1490 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001491 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001492 }
1493
John McCall6b304a02009-09-24 23:30:46 +00001494 RValueReferenceType *New
1495 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001496 Types.push_back(New);
1497 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001498 return QualType(New, 0);
1499}
1500
Sebastian Redlf30208a2009-01-24 21:16:55 +00001501/// getMemberPointerType - Return the uniqued reference to the type for a
1502/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001503QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001504 // Unique pointers, to guarantee there is only one pointer of a particular
1505 // structure.
1506 llvm::FoldingSetNodeID ID;
1507 MemberPointerType::Profile(ID, T, Cls);
1508
1509 void *InsertPos = 0;
1510 if (MemberPointerType *PT =
1511 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1512 return QualType(PT, 0);
1513
1514 // If the pointee or class type isn't canonical, this won't be a canonical
1515 // type either, so fill in the canonical type field.
1516 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001517 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001518 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1519
1520 // Get the new insert position for the node we care about.
1521 MemberPointerType *NewIP =
1522 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001523 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001524 }
John McCall6b304a02009-09-24 23:30:46 +00001525 MemberPointerType *New
1526 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001527 Types.push_back(New);
1528 MemberPointerTypes.InsertNode(New, InsertPos);
1529 return QualType(New, 0);
1530}
1531
Mike Stump1eb44332009-09-09 15:08:12 +00001532/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001533/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001534QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001535 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001536 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001537 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001538 assert((EltTy->isDependentType() ||
1539 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001540 "Constant array of VLAs is illegal!");
1541
Chris Lattner38aeec72009-05-13 04:12:56 +00001542 // Convert the array size into a canonical width matching the pointer size for
1543 // the target.
1544 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001545 ArySize =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001546 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Reid Spencer5f016e22007-07-11 17:01:13 +00001548 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001549 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001552 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001553 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001554 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001555
John McCall3b657512011-01-19 10:06:00 +00001556 // If the element type isn't canonical or has qualifiers, this won't
1557 // be a canonical type either, so fill in the canonical type field.
1558 QualType Canon;
1559 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1560 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1561 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001562 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001563 Canon = getQualifiedType(Canon, canonSplit.second);
1564
Reid Spencer5f016e22007-07-11 17:01:13 +00001565 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001566 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001567 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001568 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001569 }
Mike Stump1eb44332009-09-09 15:08:12 +00001570
John McCall6b304a02009-09-24 23:30:46 +00001571 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001572 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001573 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 Types.push_back(New);
1575 return QualType(New, 0);
1576}
1577
John McCallce889032011-01-18 08:40:38 +00001578/// getVariableArrayDecayedType - Turns the given type, which may be
1579/// variably-modified, into the corresponding type with all the known
1580/// sizes replaced with [*].
1581QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1582 // Vastly most common case.
1583 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001584
John McCallce889032011-01-18 08:40:38 +00001585 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001586
John McCallce889032011-01-18 08:40:38 +00001587 SplitQualType split = type.getSplitDesugaredType();
1588 const Type *ty = split.first;
1589 switch (ty->getTypeClass()) {
1590#define TYPE(Class, Base)
1591#define ABSTRACT_TYPE(Class, Base)
1592#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1593#include "clang/AST/TypeNodes.def"
1594 llvm_unreachable("didn't desugar past all non-canonical types?");
1595
1596 // These types should never be variably-modified.
1597 case Type::Builtin:
1598 case Type::Complex:
1599 case Type::Vector:
1600 case Type::ExtVector:
1601 case Type::DependentSizedExtVector:
1602 case Type::ObjCObject:
1603 case Type::ObjCInterface:
1604 case Type::ObjCObjectPointer:
1605 case Type::Record:
1606 case Type::Enum:
1607 case Type::UnresolvedUsing:
1608 case Type::TypeOfExpr:
1609 case Type::TypeOf:
1610 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001611 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001612 case Type::DependentName:
1613 case Type::InjectedClassName:
1614 case Type::TemplateSpecialization:
1615 case Type::DependentTemplateSpecialization:
1616 case Type::TemplateTypeParm:
1617 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001618 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001619 case Type::PackExpansion:
1620 llvm_unreachable("type should never be variably-modified");
1621
1622 // These types can be variably-modified but should never need to
1623 // further decay.
1624 case Type::FunctionNoProto:
1625 case Type::FunctionProto:
1626 case Type::BlockPointer:
1627 case Type::MemberPointer:
1628 return type;
1629
1630 // These types can be variably-modified. All these modifications
1631 // preserve structure except as noted by comments.
1632 // TODO: if we ever care about optimizing VLAs, there are no-op
1633 // optimizations available here.
1634 case Type::Pointer:
1635 result = getPointerType(getVariableArrayDecayedType(
1636 cast<PointerType>(ty)->getPointeeType()));
1637 break;
1638
1639 case Type::LValueReference: {
1640 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1641 result = getLValueReferenceType(
1642 getVariableArrayDecayedType(lv->getPointeeType()),
1643 lv->isSpelledAsLValue());
1644 break;
1645 }
1646
1647 case Type::RValueReference: {
1648 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1649 result = getRValueReferenceType(
1650 getVariableArrayDecayedType(lv->getPointeeType()));
1651 break;
1652 }
1653
1654 case Type::ConstantArray: {
1655 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1656 result = getConstantArrayType(
1657 getVariableArrayDecayedType(cat->getElementType()),
1658 cat->getSize(),
1659 cat->getSizeModifier(),
1660 cat->getIndexTypeCVRQualifiers());
1661 break;
1662 }
1663
1664 case Type::DependentSizedArray: {
1665 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1666 result = getDependentSizedArrayType(
1667 getVariableArrayDecayedType(dat->getElementType()),
1668 dat->getSizeExpr(),
1669 dat->getSizeModifier(),
1670 dat->getIndexTypeCVRQualifiers(),
1671 dat->getBracketsRange());
1672 break;
1673 }
1674
1675 // Turn incomplete types into [*] types.
1676 case Type::IncompleteArray: {
1677 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1678 result = getVariableArrayType(
1679 getVariableArrayDecayedType(iat->getElementType()),
1680 /*size*/ 0,
1681 ArrayType::Normal,
1682 iat->getIndexTypeCVRQualifiers(),
1683 SourceRange());
1684 break;
1685 }
1686
1687 // Turn VLA types into [*] types.
1688 case Type::VariableArray: {
1689 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1690 result = getVariableArrayType(
1691 getVariableArrayDecayedType(vat->getElementType()),
1692 /*size*/ 0,
1693 ArrayType::Star,
1694 vat->getIndexTypeCVRQualifiers(),
1695 vat->getBracketsRange());
1696 break;
1697 }
1698 }
1699
1700 // Apply the top-level qualifiers from the original.
1701 return getQualifiedType(result, split.second);
1702}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001703
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001704/// getVariableArrayType - Returns a non-unique reference to the type for a
1705/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001706QualType ASTContext::getVariableArrayType(QualType EltTy,
1707 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001708 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001709 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001710 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001711 // Since we don't unique expressions, it isn't possible to unique VLA's
1712 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001713 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001714
John McCall3b657512011-01-19 10:06:00 +00001715 // Be sure to pull qualifiers off the element type.
1716 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1717 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1718 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001719 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001720 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001721 }
1722
John McCall6b304a02009-09-24 23:30:46 +00001723 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001724 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001725
1726 VariableArrayTypes.push_back(New);
1727 Types.push_back(New);
1728 return QualType(New, 0);
1729}
1730
Douglas Gregor898574e2008-12-05 23:32:09 +00001731/// getDependentSizedArrayType - Returns a non-unique reference to
1732/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001733/// type.
John McCall3b657512011-01-19 10:06:00 +00001734QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1735 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001736 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001737 unsigned elementTypeQuals,
1738 SourceRange brackets) const {
1739 assert((!numElements || numElements->isTypeDependent() ||
1740 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001741 "Size must be type- or value-dependent!");
1742
John McCall3b657512011-01-19 10:06:00 +00001743 // Dependently-sized array types that do not have a specified number
1744 // of elements will have their sizes deduced from a dependent
1745 // initializer. We do no canonicalization here at all, which is okay
1746 // because they can't be used in most locations.
1747 if (!numElements) {
1748 DependentSizedArrayType *newType
1749 = new (*this, TypeAlignment)
1750 DependentSizedArrayType(*this, elementType, QualType(),
1751 numElements, ASM, elementTypeQuals,
1752 brackets);
1753 Types.push_back(newType);
1754 return QualType(newType, 0);
1755 }
1756
1757 // Otherwise, we actually build a new type every time, but we
1758 // also build a canonical type.
1759
1760 SplitQualType canonElementType = getCanonicalType(elementType).split();
1761
1762 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001763 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001764 DependentSizedArrayType::Profile(ID, *this,
1765 QualType(canonElementType.first, 0),
1766 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001767
John McCall3b657512011-01-19 10:06:00 +00001768 // Look for an existing type with these properties.
1769 DependentSizedArrayType *canonTy =
1770 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001771
John McCall3b657512011-01-19 10:06:00 +00001772 // If we don't have one, build one.
1773 if (!canonTy) {
1774 canonTy = new (*this, TypeAlignment)
1775 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1776 QualType(), numElements, ASM, elementTypeQuals,
1777 brackets);
1778 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1779 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001780 }
1781
John McCall3b657512011-01-19 10:06:00 +00001782 // Apply qualifiers from the element type to the array.
1783 QualType canon = getQualifiedType(QualType(canonTy,0),
1784 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001785
John McCall3b657512011-01-19 10:06:00 +00001786 // If we didn't need extra canonicalization for the element type,
1787 // then just use that as our result.
1788 if (QualType(canonElementType.first, 0) == elementType)
1789 return canon;
1790
1791 // Otherwise, we need to build a type which follows the spelling
1792 // of the element type.
1793 DependentSizedArrayType *sugaredType
1794 = new (*this, TypeAlignment)
1795 DependentSizedArrayType(*this, elementType, canon, numElements,
1796 ASM, elementTypeQuals, brackets);
1797 Types.push_back(sugaredType);
1798 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001799}
1800
John McCall3b657512011-01-19 10:06:00 +00001801QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001802 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001803 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001804 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001805 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001806
John McCall3b657512011-01-19 10:06:00 +00001807 void *insertPos = 0;
1808 if (IncompleteArrayType *iat =
1809 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1810 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001811
1812 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001813 // either, so fill in the canonical type field. We also have to pull
1814 // qualifiers off the element type.
1815 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001816
John McCall3b657512011-01-19 10:06:00 +00001817 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1818 SplitQualType canonSplit = getCanonicalType(elementType).split();
1819 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1820 ASM, elementTypeQuals);
1821 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001822
1823 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001824 IncompleteArrayType *existing =
1825 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1826 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001827 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001828
John McCall3b657512011-01-19 10:06:00 +00001829 IncompleteArrayType *newType = new (*this, TypeAlignment)
1830 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001831
John McCall3b657512011-01-19 10:06:00 +00001832 IncompleteArrayTypes.InsertNode(newType, insertPos);
1833 Types.push_back(newType);
1834 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001835}
1836
Steve Naroff73322922007-07-18 18:00:27 +00001837/// getVectorType - Return the unique reference to a vector type of
1838/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001839QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001840 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001841 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001842
Reid Spencer5f016e22007-07-11 17:01:13 +00001843 // Check if we've already instantiated a vector of this type.
1844 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001845 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001846
Reid Spencer5f016e22007-07-11 17:01:13 +00001847 void *InsertPos = 0;
1848 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1849 return QualType(VTP, 0);
1850
1851 // If the element type isn't canonical, this won't be a canonical type either,
1852 // so fill in the canonical type field.
1853 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001854 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001855 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Reid Spencer5f016e22007-07-11 17:01:13 +00001857 // Get the new insert position for the node we care about.
1858 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001859 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001860 }
John McCall6b304a02009-09-24 23:30:46 +00001861 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001862 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001863 VectorTypes.InsertNode(New, InsertPos);
1864 Types.push_back(New);
1865 return QualType(New, 0);
1866}
1867
Nate Begeman213541a2008-04-18 23:10:10 +00001868/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001869/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001870QualType
1871ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
John McCall3b657512011-01-19 10:06:00 +00001872 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Steve Naroff73322922007-07-18 18:00:27 +00001874 // Check if we've already instantiated a vector of this type.
1875 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001876 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001877 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001878 void *InsertPos = 0;
1879 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1880 return QualType(VTP, 0);
1881
1882 // If the element type isn't canonical, this won't be a canonical type either,
1883 // so fill in the canonical type field.
1884 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001885 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001886 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Steve Naroff73322922007-07-18 18:00:27 +00001888 // Get the new insert position for the node we care about.
1889 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001890 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001891 }
John McCall6b304a02009-09-24 23:30:46 +00001892 ExtVectorType *New = new (*this, TypeAlignment)
1893 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001894 VectorTypes.InsertNode(New, InsertPos);
1895 Types.push_back(New);
1896 return QualType(New, 0);
1897}
1898
Jay Foad4ba2a172011-01-12 09:06:06 +00001899QualType
1900ASTContext::getDependentSizedExtVectorType(QualType vecType,
1901 Expr *SizeExpr,
1902 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001903 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001904 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001905 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001907 void *InsertPos = 0;
1908 DependentSizedExtVectorType *Canon
1909 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1910 DependentSizedExtVectorType *New;
1911 if (Canon) {
1912 // We already have a canonical version of this array type; use it as
1913 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001914 New = new (*this, TypeAlignment)
1915 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1916 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001917 } else {
1918 QualType CanonVecTy = getCanonicalType(vecType);
1919 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001920 New = new (*this, TypeAlignment)
1921 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1922 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001923
1924 DependentSizedExtVectorType *CanonCheck
1925 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1926 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1927 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001928 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1929 } else {
1930 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1931 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001932 New = new (*this, TypeAlignment)
1933 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001934 }
1935 }
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001937 Types.push_back(New);
1938 return QualType(New, 0);
1939}
1940
Douglas Gregor72564e72009-02-26 23:50:07 +00001941/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001942///
Jay Foad4ba2a172011-01-12 09:06:06 +00001943QualType
1944ASTContext::getFunctionNoProtoType(QualType ResultTy,
1945 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00001946 const CallingConv DefaultCC = Info.getCC();
1947 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1948 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00001949 // Unique functions, to guarantee there is only one function of a particular
1950 // structure.
1951 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001952 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Reid Spencer5f016e22007-07-11 17:01:13 +00001954 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001955 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001956 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001957 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001960 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001961 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001962 Canonical =
1963 getFunctionNoProtoType(getCanonicalType(ResultTy),
1964 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Reid Spencer5f016e22007-07-11 17:01:13 +00001966 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001967 FunctionNoProtoType *NewIP =
1968 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001969 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001970 }
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Roman Divackycfe9af22011-03-01 17:40:53 +00001972 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00001973 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00001974 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00001975 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001976 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001977 return QualType(New, 0);
1978}
1979
1980/// getFunctionType - Return a normal function type with a typed argument
1981/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00001982QualType
1983ASTContext::getFunctionType(QualType ResultTy,
1984 const QualType *ArgArray, unsigned NumArgs,
1985 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001986 // Unique functions, to guarantee there is only one function of a particular
1987 // structure.
1988 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001989 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00001990
1991 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001992 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001993 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001994 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001995
1996 // Determine whether the type being created is already canonical or not.
Sebastian Redl8b5b4092011-03-06 10:52:04 +00001997 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001998 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00001999 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002000 isCanonical = false;
2001
Roman Divackycfe9af22011-03-01 17:40:53 +00002002 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2003 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2004 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002005
Reid Spencer5f016e22007-07-11 17:01:13 +00002006 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002007 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002008 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002009 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002010 llvm::SmallVector<QualType, 16> CanonicalArgs;
2011 CanonicalArgs.reserve(NumArgs);
2012 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002013 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002014
John McCalle23cf432010-12-14 08:05:40 +00002015 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002016 CanonicalEPI.ExceptionSpecType = EST_None;
2017 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002018 CanonicalEPI.ExtInfo
2019 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2020
Chris Lattnerf52ab252008-04-06 22:59:24 +00002021 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002022 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002023 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002024
Reid Spencer5f016e22007-07-11 17:01:13 +00002025 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002026 FunctionProtoType *NewIP =
2027 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002028 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002029 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002030
Douglas Gregor72564e72009-02-26 23:50:07 +00002031 // FunctionProtoType objects are allocated with extra bytes after them
Sebastian Redl465226e2009-05-27 22:11:52 +00002032 // for two variable size arrays (for parameter and exception types) at the
Sebastian Redl60618fa2011-03-12 11:50:43 +00002033 // end of them. Instead of the exception types, there could be a noexcept
2034 // expression and a context pointer.
John McCalle23cf432010-12-14 08:05:40 +00002035 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002036 NumArgs * sizeof(QualType);
2037 if (EPI.ExceptionSpecType == EST_Dynamic)
2038 Size += EPI.NumExceptions * sizeof(QualType);
2039 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002040 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002041 }
John McCalle23cf432010-12-14 08:05:40 +00002042 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002043 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2044 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002045 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002046 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002047 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002048 return QualType(FTP, 0);
2049}
2050
John McCall3cb0ebd2010-03-10 03:28:59 +00002051#ifndef NDEBUG
2052static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2053 if (!isa<CXXRecordDecl>(D)) return false;
2054 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2055 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2056 return true;
2057 if (RD->getDescribedClassTemplate() &&
2058 !isa<ClassTemplateSpecializationDecl>(RD))
2059 return true;
2060 return false;
2061}
2062#endif
2063
2064/// getInjectedClassNameType - Return the unique reference to the
2065/// injected class name type for the specified templated declaration.
2066QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002067 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002068 assert(NeedsInjectedClassNameType(Decl));
2069 if (Decl->TypeForDecl) {
2070 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00002071 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002072 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2073 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2074 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2075 } else {
John McCallf4c73712011-01-19 06:33:43 +00002076 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002077 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002078 Decl->TypeForDecl = newType;
2079 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002080 }
2081 return QualType(Decl->TypeForDecl, 0);
2082}
2083
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002084/// getTypeDeclType - Return the unique reference to the type for the
2085/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002086QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002087 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002088 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Richard Smith162e1c12011-04-15 14:24:37 +00002090 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002091 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002092
John McCallbecb8d52010-03-10 06:48:02 +00002093 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2094 "Template type parameter types are always available.");
2095
John McCall19c85762010-02-16 03:57:14 +00002096 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002097 assert(!Record->getPreviousDeclaration() &&
2098 "struct/union has previous declaration");
2099 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002100 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002101 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002102 assert(!Enum->getPreviousDeclaration() &&
2103 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002104 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002105 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002106 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002107 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2108 Decl->TypeForDecl = newType;
2109 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002110 } else
John McCallbecb8d52010-03-10 06:48:02 +00002111 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002112
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002113 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002114}
2115
Reid Spencer5f016e22007-07-11 17:01:13 +00002116/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002117/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002118QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002119ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2120 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002123 if (Canonical.isNull())
2124 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002125 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002126 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002127 Decl->TypeForDecl = newType;
2128 Types.push_back(newType);
2129 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002130}
2131
Jay Foad4ba2a172011-01-12 09:06:06 +00002132QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002133 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2134
2135 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2136 if (PrevDecl->TypeForDecl)
2137 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2138
John McCallf4c73712011-01-19 06:33:43 +00002139 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2140 Decl->TypeForDecl = newType;
2141 Types.push_back(newType);
2142 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002143}
2144
Jay Foad4ba2a172011-01-12 09:06:06 +00002145QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002146 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2147
2148 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2149 if (PrevDecl->TypeForDecl)
2150 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2151
John McCallf4c73712011-01-19 06:33:43 +00002152 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2153 Decl->TypeForDecl = newType;
2154 Types.push_back(newType);
2155 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002156}
2157
John McCall9d156a72011-01-06 01:58:22 +00002158QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2159 QualType modifiedType,
2160 QualType equivalentType) {
2161 llvm::FoldingSetNodeID id;
2162 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2163
2164 void *insertPos = 0;
2165 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2166 if (type) return QualType(type, 0);
2167
2168 QualType canon = getCanonicalType(equivalentType);
2169 type = new (*this, TypeAlignment)
2170 AttributedType(canon, attrKind, modifiedType, equivalentType);
2171
2172 Types.push_back(type);
2173 AttributedTypes.InsertNode(type, insertPos);
2174
2175 return QualType(type, 0);
2176}
2177
2178
John McCall49a832b2009-10-18 09:09:24 +00002179/// \brief Retrieve a substitution-result type.
2180QualType
2181ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002182 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002183 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002184 && "replacement types must always be canonical");
2185
2186 llvm::FoldingSetNodeID ID;
2187 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2188 void *InsertPos = 0;
2189 SubstTemplateTypeParmType *SubstParm
2190 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2191
2192 if (!SubstParm) {
2193 SubstParm = new (*this, TypeAlignment)
2194 SubstTemplateTypeParmType(Parm, Replacement);
2195 Types.push_back(SubstParm);
2196 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2197 }
2198
2199 return QualType(SubstParm, 0);
2200}
2201
Douglas Gregorc3069d62011-01-14 02:55:32 +00002202/// \brief Retrieve a
2203QualType ASTContext::getSubstTemplateTypeParmPackType(
2204 const TemplateTypeParmType *Parm,
2205 const TemplateArgument &ArgPack) {
2206#ifndef NDEBUG
2207 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2208 PEnd = ArgPack.pack_end();
2209 P != PEnd; ++P) {
2210 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2211 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2212 }
2213#endif
2214
2215 llvm::FoldingSetNodeID ID;
2216 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2217 void *InsertPos = 0;
2218 if (SubstTemplateTypeParmPackType *SubstParm
2219 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2220 return QualType(SubstParm, 0);
2221
2222 QualType Canon;
2223 if (!Parm->isCanonicalUnqualified()) {
2224 Canon = getCanonicalType(QualType(Parm, 0));
2225 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2226 ArgPack);
2227 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2228 }
2229
2230 SubstTemplateTypeParmPackType *SubstParm
2231 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2232 ArgPack);
2233 Types.push_back(SubstParm);
2234 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2235 return QualType(SubstParm, 0);
2236}
2237
Douglas Gregorfab9d672009-02-05 23:33:38 +00002238/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002239/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002240/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002241QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002242 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002243 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002244 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002245 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002246 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002247 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002248 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2249
2250 if (TypeParm)
2251 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002253 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002254 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002255 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002256
2257 TemplateTypeParmType *TypeCheck
2258 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2259 assert(!TypeCheck && "Template type parameter canonical type broken");
2260 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002261 } else
John McCall6b304a02009-09-24 23:30:46 +00002262 TypeParm = new (*this, TypeAlignment)
2263 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002264
2265 Types.push_back(TypeParm);
2266 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2267
2268 return QualType(TypeParm, 0);
2269}
2270
John McCall3cb0ebd2010-03-10 03:28:59 +00002271TypeSourceInfo *
2272ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2273 SourceLocation NameLoc,
2274 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002275 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002276 assert(!Name.getAsDependentTemplateName() &&
2277 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002278 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002279
2280 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2281 TemplateSpecializationTypeLoc TL
2282 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2283 TL.setTemplateNameLoc(NameLoc);
2284 TL.setLAngleLoc(Args.getLAngleLoc());
2285 TL.setRAngleLoc(Args.getRAngleLoc());
2286 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2287 TL.setArgLocInfo(i, Args[i].getLocInfo());
2288 return DI;
2289}
2290
Mike Stump1eb44332009-09-09 15:08:12 +00002291QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002292ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002293 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002294 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002295 assert(!Template.getAsDependentTemplateName() &&
2296 "No dependent template names here!");
2297
John McCalld5532b62009-11-23 01:53:49 +00002298 unsigned NumArgs = Args.size();
2299
John McCall833ca992009-10-29 08:12:44 +00002300 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2301 ArgVec.reserve(NumArgs);
2302 for (unsigned i = 0; i != NumArgs; ++i)
2303 ArgVec.push_back(Args[i].getArgument());
2304
John McCall31f17ec2010-04-27 00:57:59 +00002305 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002306 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002307}
2308
2309QualType
2310ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002311 const TemplateArgument *Args,
2312 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002313 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002314 assert(!Template.getAsDependentTemplateName() &&
2315 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002316 // Look through qualified template names.
2317 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2318 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002319
Richard Smith3e4c6c42011-05-05 21:57:07 +00002320 bool isTypeAlias =
2321 Template.getAsTemplateDecl() &&
2322 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2323
2324 QualType CanonType;
2325 if (!Underlying.isNull())
2326 CanonType = getCanonicalType(Underlying);
2327 else {
2328 assert(!isTypeAlias &&
2329 "Underlying type for template alias must be computed by caller");
2330 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2331 NumArgs);
2332 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002333
Douglas Gregor1275ae02009-07-28 23:00:59 +00002334 // Allocate the (non-canonical) template specialization type, but don't
2335 // try to unique it: these types typically have location information that
2336 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002337 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2338 sizeof(TemplateArgument) * NumArgs +
2339 (isTypeAlias ? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002340 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002341 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002342 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002343 Args, NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002344 CanonType,
2345 isTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002346
Douglas Gregor55f6b142009-02-09 18:46:07 +00002347 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002348 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002349}
2350
Mike Stump1eb44332009-09-09 15:08:12 +00002351QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002352ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2353 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002354 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002355 assert(!Template.getAsDependentTemplateName() &&
2356 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002357 assert((!Template.getAsTemplateDecl() ||
2358 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2359 "Underlying type for template alias must be computed by caller");
2360
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002361 // Look through qualified template names.
2362 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2363 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002364
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002365 // Build the canonical template specialization type.
2366 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2367 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2368 CanonArgs.reserve(NumArgs);
2369 for (unsigned I = 0; I != NumArgs; ++I)
2370 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2371
2372 // Determine whether this canonical template specialization type already
2373 // exists.
2374 llvm::FoldingSetNodeID ID;
2375 TemplateSpecializationType::Profile(ID, CanonTemplate,
2376 CanonArgs.data(), NumArgs, *this);
2377
2378 void *InsertPos = 0;
2379 TemplateSpecializationType *Spec
2380 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2381
2382 if (!Spec) {
2383 // Allocate a new canonical template specialization type.
2384 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2385 sizeof(TemplateArgument) * NumArgs),
2386 TypeAlignment);
2387 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2388 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002389 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002390 Types.push_back(Spec);
2391 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2392 }
2393
2394 assert(Spec->isDependentType() &&
2395 "Non-dependent template-id type must have a canonical type");
2396 return QualType(Spec, 0);
2397}
2398
2399QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002400ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2401 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002402 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002403 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002404 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002405
2406 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002407 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002408 if (T)
2409 return QualType(T, 0);
2410
Douglas Gregor789b1f62010-02-04 18:10:26 +00002411 QualType Canon = NamedType;
2412 if (!Canon.isCanonical()) {
2413 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002414 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2415 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002416 (void)CheckT;
2417 }
2418
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002419 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002420 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002421 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002422 return QualType(T, 0);
2423}
2424
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002425QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002426ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002427 llvm::FoldingSetNodeID ID;
2428 ParenType::Profile(ID, InnerType);
2429
2430 void *InsertPos = 0;
2431 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2432 if (T)
2433 return QualType(T, 0);
2434
2435 QualType Canon = InnerType;
2436 if (!Canon.isCanonical()) {
2437 Canon = getCanonicalType(InnerType);
2438 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2439 assert(!CheckT && "Paren canonical type broken");
2440 (void)CheckT;
2441 }
2442
2443 T = new (*this) ParenType(InnerType, Canon);
2444 Types.push_back(T);
2445 ParenTypes.InsertNode(T, InsertPos);
2446 return QualType(T, 0);
2447}
2448
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002449QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2450 NestedNameSpecifier *NNS,
2451 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002452 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002453 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2454
2455 if (Canon.isNull()) {
2456 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002457 ElaboratedTypeKeyword CanonKeyword = Keyword;
2458 if (Keyword == ETK_None)
2459 CanonKeyword = ETK_Typename;
2460
2461 if (CanonNNS != NNS || CanonKeyword != Keyword)
2462 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002463 }
2464
2465 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002466 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002467
2468 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002469 DependentNameType *T
2470 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002471 if (T)
2472 return QualType(T, 0);
2473
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002474 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002475 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002476 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002477 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002478}
2479
Mike Stump1eb44332009-09-09 15:08:12 +00002480QualType
John McCall33500952010-06-11 00:33:02 +00002481ASTContext::getDependentTemplateSpecializationType(
2482 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002483 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002484 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002485 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002486 // TODO: avoid this copy
2487 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2488 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2489 ArgCopy.push_back(Args[I].getArgument());
2490 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2491 ArgCopy.size(),
2492 ArgCopy.data());
2493}
2494
2495QualType
2496ASTContext::getDependentTemplateSpecializationType(
2497 ElaboratedTypeKeyword Keyword,
2498 NestedNameSpecifier *NNS,
2499 const IdentifierInfo *Name,
2500 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002501 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002502 assert((!NNS || NNS->isDependent()) &&
2503 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002504
Douglas Gregor789b1f62010-02-04 18:10:26 +00002505 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002506 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2507 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002508
2509 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002510 DependentTemplateSpecializationType *T
2511 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002512 if (T)
2513 return QualType(T, 0);
2514
John McCall33500952010-06-11 00:33:02 +00002515 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002516
John McCall33500952010-06-11 00:33:02 +00002517 ElaboratedTypeKeyword CanonKeyword = Keyword;
2518 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2519
2520 bool AnyNonCanonArgs = false;
2521 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2522 for (unsigned I = 0; I != NumArgs; ++I) {
2523 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2524 if (!CanonArgs[I].structurallyEquals(Args[I]))
2525 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002526 }
2527
John McCall33500952010-06-11 00:33:02 +00002528 QualType Canon;
2529 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2530 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2531 Name, NumArgs,
2532 CanonArgs.data());
2533
2534 // Find the insert position again.
2535 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2536 }
2537
2538 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2539 sizeof(TemplateArgument) * NumArgs),
2540 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002541 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002542 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002543 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002544 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002545 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002546}
2547
Douglas Gregorcded4f62011-01-14 17:04:44 +00002548QualType ASTContext::getPackExpansionType(QualType Pattern,
2549 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002550 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002551 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002552
2553 assert(Pattern->containsUnexpandedParameterPack() &&
2554 "Pack expansions must expand one or more parameter packs");
2555 void *InsertPos = 0;
2556 PackExpansionType *T
2557 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2558 if (T)
2559 return QualType(T, 0);
2560
2561 QualType Canon;
2562 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002563 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002564
2565 // Find the insert position again.
2566 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2567 }
2568
Douglas Gregorcded4f62011-01-14 17:04:44 +00002569 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002570 Types.push_back(T);
2571 PackExpansionTypes.InsertNode(T, InsertPos);
2572 return QualType(T, 0);
2573}
2574
Chris Lattner88cb27a2008-04-07 04:56:42 +00002575/// CmpProtocolNames - Comparison predicate for sorting protocols
2576/// alphabetically.
2577static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2578 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002579 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002580}
2581
John McCallc12c5bb2010-05-15 11:32:37 +00002582static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002583 unsigned NumProtocols) {
2584 if (NumProtocols == 0) return true;
2585
2586 for (unsigned i = 1; i != NumProtocols; ++i)
2587 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2588 return false;
2589 return true;
2590}
2591
2592static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002593 unsigned &NumProtocols) {
2594 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002595
Chris Lattner88cb27a2008-04-07 04:56:42 +00002596 // Sort protocols, keyed by name.
2597 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2598
2599 // Remove duplicates.
2600 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2601 NumProtocols = ProtocolsEnd-Protocols;
2602}
2603
John McCallc12c5bb2010-05-15 11:32:37 +00002604QualType ASTContext::getObjCObjectType(QualType BaseType,
2605 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002606 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002607 // If the base type is an interface and there aren't any protocols
2608 // to add, then the interface type will do just fine.
2609 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2610 return BaseType;
2611
2612 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002613 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002614 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002615 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002616 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2617 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002618
John McCallc12c5bb2010-05-15 11:32:37 +00002619 // Build the canonical type, which has the canonical base type and
2620 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002621 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002622 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2623 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2624 if (!ProtocolsSorted) {
Benjamin Kramer02379412010-04-27 17:12:11 +00002625 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2626 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002627 unsigned UniqueCount = NumProtocols;
2628
John McCall54e14c42009-10-22 22:37:11 +00002629 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002630 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2631 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002632 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002633 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2634 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002635 }
2636
2637 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002638 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2639 }
2640
2641 unsigned Size = sizeof(ObjCObjectTypeImpl);
2642 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2643 void *Mem = Allocate(Size, TypeAlignment);
2644 ObjCObjectTypeImpl *T =
2645 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2646
2647 Types.push_back(T);
2648 ObjCObjectTypes.InsertNode(T, InsertPos);
2649 return QualType(T, 0);
2650}
2651
2652/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2653/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002654QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002655 llvm::FoldingSetNodeID ID;
2656 ObjCObjectPointerType::Profile(ID, ObjectT);
2657
2658 void *InsertPos = 0;
2659 if (ObjCObjectPointerType *QT =
2660 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2661 return QualType(QT, 0);
2662
2663 // Find the canonical object type.
2664 QualType Canonical;
2665 if (!ObjectT.isCanonical()) {
2666 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2667
2668 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002669 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2670 }
2671
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002672 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002673 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2674 ObjCObjectPointerType *QType =
2675 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002676
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002677 Types.push_back(QType);
2678 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002679 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002680}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002681
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002682/// getObjCInterfaceType - Return the unique reference to the type for the
2683/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad4ba2a172011-01-12 09:06:06 +00002684QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002685 if (Decl->TypeForDecl)
2686 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002687
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002688 // FIXME: redeclarations?
2689 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2690 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2691 Decl->TypeForDecl = T;
2692 Types.push_back(T);
2693 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002694}
2695
Douglas Gregor72564e72009-02-26 23:50:07 +00002696/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2697/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002698/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002699/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002700/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002701QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002702 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002703 if (tofExpr->isTypeDependent()) {
2704 llvm::FoldingSetNodeID ID;
2705 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Douglas Gregorb1975722009-07-30 23:18:24 +00002707 void *InsertPos = 0;
2708 DependentTypeOfExprType *Canon
2709 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2710 if (Canon) {
2711 // We already have a "canonical" version of an identical, dependent
2712 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002713 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002714 QualType((TypeOfExprType*)Canon, 0));
2715 }
2716 else {
2717 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002718 Canon
2719 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002720 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2721 toe = Canon;
2722 }
2723 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002724 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002725 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002726 }
Steve Naroff9752f252007-08-01 18:02:17 +00002727 Types.push_back(toe);
2728 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002729}
2730
Steve Naroff9752f252007-08-01 18:02:17 +00002731/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2732/// TypeOfType AST's. The only motivation to unique these nodes would be
2733/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002734/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002735/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002736QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002737 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002738 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002739 Types.push_back(tot);
2740 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002741}
2742
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002743/// getDecltypeForExpr - Given an expr, will return the decltype for that
2744/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002745static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002746 if (e->isTypeDependent())
2747 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002748
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002749 // If e is an id expression or a class member access, decltype(e) is defined
2750 // as the type of the entity named by e.
2751 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2752 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2753 return VD->getType();
2754 }
2755 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2756 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2757 return FD->getType();
2758 }
2759 // If e is a function call or an invocation of an overloaded operator,
2760 // (parentheses around e are ignored), decltype(e) is defined as the
2761 // return type of that function.
2762 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2763 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002764
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002765 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002766
2767 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002768 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002769 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002770 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002771
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002772 return T;
2773}
2774
Anders Carlsson395b4752009-06-24 19:06:50 +00002775/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2776/// DecltypeType AST's. The only motivation to unique these nodes would be
2777/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002778/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002779/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002780QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002781 DecltypeType *dt;
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002782 if (e->isTypeDependent()) {
2783 llvm::FoldingSetNodeID ID;
2784 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002785
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002786 void *InsertPos = 0;
2787 DependentDecltypeType *Canon
2788 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2789 if (Canon) {
2790 // We already have a "canonical" version of an equivalent, dependent
2791 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002792 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002793 QualType((DecltypeType*)Canon, 0));
2794 }
2795 else {
2796 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002797 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002798 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2799 dt = Canon;
2800 }
2801 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002802 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002803 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002804 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002805 Types.push_back(dt);
2806 return QualType(dt, 0);
2807}
2808
Sean Huntca63c202011-05-24 22:41:36 +00002809/// getUnaryTransformationType - We don't unique these, since the memory
2810/// savings are minimal and these are rare.
2811QualType ASTContext::getUnaryTransformType(QualType BaseType,
2812 QualType UnderlyingType,
2813 UnaryTransformType::UTTKind Kind)
2814 const {
2815 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002816 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2817 Kind,
2818 UnderlyingType->isDependentType() ?
2819 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00002820 Types.push_back(Ty);
2821 return QualType(Ty, 0);
2822}
2823
Richard Smith483b9f32011-02-21 20:05:19 +00002824/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002825QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002826 void *InsertPos = 0;
2827 if (!DeducedType.isNull()) {
2828 // Look in the folding set for an existing type.
2829 llvm::FoldingSetNodeID ID;
2830 AutoType::Profile(ID, DeducedType);
2831 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2832 return QualType(AT, 0);
2833 }
2834
2835 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2836 Types.push_back(AT);
2837 if (InsertPos)
2838 AutoTypes.InsertNode(AT, InsertPos);
2839 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002840}
2841
Richard Smithad762fc2011-04-14 22:09:26 +00002842/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2843QualType ASTContext::getAutoDeductType() const {
2844 if (AutoDeductTy.isNull())
2845 AutoDeductTy = getAutoType(QualType());
2846 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2847 return AutoDeductTy;
2848}
2849
2850/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2851QualType ASTContext::getAutoRRefDeductType() const {
2852 if (AutoRRefDeductTy.isNull())
2853 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2854 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2855 return AutoRRefDeductTy;
2856}
2857
Reid Spencer5f016e22007-07-11 17:01:13 +00002858/// getTagDeclType - Return the unique reference to the type for the
2859/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00002860QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00002861 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002862 // FIXME: What is the design on getTagDeclType when it requires casting
2863 // away const? mutable?
2864 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002865}
2866
Mike Stump1eb44332009-09-09 15:08:12 +00002867/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2868/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2869/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002870CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002871 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002872}
2873
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002874/// getSignedWCharType - Return the type of "signed wchar_t".
2875/// Used when in C++, as a GCC extension.
2876QualType ASTContext::getSignedWCharType() const {
2877 // FIXME: derive from "Target" ?
2878 return WCharTy;
2879}
2880
2881/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2882/// Used when in C++, as a GCC extension.
2883QualType ASTContext::getUnsignedWCharType() const {
2884 // FIXME: derive from "Target" ?
2885 return UnsignedIntTy;
2886}
2887
Chris Lattner8b9023b2007-07-13 03:05:23 +00002888/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2889/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2890QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002891 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002892}
2893
Chris Lattnere6327742008-04-02 05:18:44 +00002894//===----------------------------------------------------------------------===//
2895// Type Operators
2896//===----------------------------------------------------------------------===//
2897
Jay Foad4ba2a172011-01-12 09:06:06 +00002898CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00002899 // Push qualifiers into arrays, and then discard any remaining
2900 // qualifiers.
2901 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002902 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002903 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002904 QualType Result;
2905 if (isa<ArrayType>(Ty)) {
2906 Result = getArrayDecayedType(QualType(Ty,0));
2907 } else if (isa<FunctionType>(Ty)) {
2908 Result = getPointerType(QualType(Ty, 0));
2909 } else {
2910 Result = QualType(Ty, 0);
2911 }
2912
2913 return CanQualType::CreateUnsafe(Result);
2914}
2915
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002916
John McCall62c28c82011-01-18 07:41:22 +00002917QualType ASTContext::getUnqualifiedArrayType(QualType type,
2918 Qualifiers &quals) {
2919 SplitQualType splitType = type.getSplitUnqualifiedType();
2920
2921 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2922 // the unqualified desugared type and then drops it on the floor.
2923 // We then have to strip that sugar back off with
2924 // getUnqualifiedDesugaredType(), which is silly.
2925 const ArrayType *AT =
2926 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2927
2928 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00002929 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00002930 quals = splitType.second;
2931 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002932 }
2933
John McCall62c28c82011-01-18 07:41:22 +00002934 // Otherwise, recurse on the array's element type.
2935 QualType elementType = AT->getElementType();
2936 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2937
2938 // If that didn't change the element type, AT has no qualifiers, so we
2939 // can just use the results in splitType.
2940 if (elementType == unqualElementType) {
2941 assert(quals.empty()); // from the recursive call
2942 quals = splitType.second;
2943 return QualType(splitType.first, 0);
2944 }
2945
2946 // Otherwise, add in the qualifiers from the outermost type, then
2947 // build the type back up.
2948 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002949
Douglas Gregor9dadd942010-05-17 18:45:21 +00002950 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002951 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002952 CAT->getSizeModifier(), 0);
2953 }
2954
Douglas Gregor9dadd942010-05-17 18:45:21 +00002955 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002956 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002957 }
2958
Douglas Gregor9dadd942010-05-17 18:45:21 +00002959 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002960 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00002961 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00002962 VAT->getSizeModifier(),
2963 VAT->getIndexTypeCVRQualifiers(),
2964 VAT->getBracketsRange());
2965 }
2966
2967 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00002968 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002969 DSAT->getSizeModifier(), 0,
2970 SourceRange());
2971}
2972
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002973/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2974/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2975/// they point to and return true. If T1 and T2 aren't pointer types
2976/// or pointer-to-member types, or if they are not similar at this
2977/// level, returns false and leaves T1 and T2 unchanged. Top-level
2978/// qualifiers on T1 and T2 are ignored. This function will typically
2979/// be called in a loop that successively "unwraps" pointer and
2980/// pointer-to-member types to compare them at each level.
2981bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2982 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2983 *T2PtrType = T2->getAs<PointerType>();
2984 if (T1PtrType && T2PtrType) {
2985 T1 = T1PtrType->getPointeeType();
2986 T2 = T2PtrType->getPointeeType();
2987 return true;
2988 }
2989
2990 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2991 *T2MPType = T2->getAs<MemberPointerType>();
2992 if (T1MPType && T2MPType &&
2993 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2994 QualType(T2MPType->getClass(), 0))) {
2995 T1 = T1MPType->getPointeeType();
2996 T2 = T2MPType->getPointeeType();
2997 return true;
2998 }
2999
3000 if (getLangOptions().ObjC1) {
3001 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3002 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3003 if (T1OPType && T2OPType) {
3004 T1 = T1OPType->getPointeeType();
3005 T2 = T2OPType->getPointeeType();
3006 return true;
3007 }
3008 }
3009
3010 // FIXME: Block pointers, too?
3011
3012 return false;
3013}
3014
Jay Foad4ba2a172011-01-12 09:06:06 +00003015DeclarationNameInfo
3016ASTContext::getNameForTemplate(TemplateName Name,
3017 SourceLocation NameLoc) const {
John McCall80ad16f2009-11-24 18:42:40 +00003018 if (TemplateDecl *TD = Name.getAsTemplateDecl())
Abramo Bagnara25777432010-08-11 22:01:17 +00003019 // DNInfo work in progress: CHECKME: what about DNLoc?
3020 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
3021
John McCall80ad16f2009-11-24 18:42:40 +00003022 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003023 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003024 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003025 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3026 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003027 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003028 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3029 // DNInfo work in progress: FIXME: source locations?
3030 DeclarationNameLoc DNLoc;
3031 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3032 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3033 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003034 }
3035 }
3036
John McCall0bd6feb2009-12-02 08:04:21 +00003037 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3038 assert(Storage);
Abramo Bagnara25777432010-08-11 22:01:17 +00003039 // DNInfo work in progress: CHECKME: what about DNLoc?
3040 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003041}
3042
Jay Foad4ba2a172011-01-12 09:06:06 +00003043TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003044 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3045 if (TemplateTemplateParmDecl *TTP
3046 = dyn_cast<TemplateTemplateParmDecl>(Template))
3047 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3048
3049 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003050 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003051 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003052
Douglas Gregor1aee05d2011-01-15 06:45:20 +00003053 if (SubstTemplateTemplateParmPackStorage *SubstPack
3054 = Name.getAsSubstTemplateTemplateParmPack()) {
3055 TemplateTemplateParmDecl *CanonParam
3056 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
3057 TemplateArgument CanonArgPack
3058 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
3059 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
3060 }
3061
John McCall0bd6feb2009-12-02 08:04:21 +00003062 assert(!Name.getAsOverloadedTemplate());
Mike Stump1eb44332009-09-09 15:08:12 +00003063
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003064 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3065 assert(DTN && "Non-dependent template names must refer to template decls.");
3066 return DTN->CanonicalTemplateName;
3067}
3068
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003069bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3070 X = getCanonicalTemplateName(X);
3071 Y = getCanonicalTemplateName(Y);
3072 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3073}
3074
Mike Stump1eb44332009-09-09 15:08:12 +00003075TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003076ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003077 switch (Arg.getKind()) {
3078 case TemplateArgument::Null:
3079 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003080
Douglas Gregor1275ae02009-07-28 23:00:59 +00003081 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003082 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003083
Douglas Gregor1275ae02009-07-28 23:00:59 +00003084 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003085 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003086
Douglas Gregor788cd062009-11-11 01:00:40 +00003087 case TemplateArgument::Template:
3088 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003089
3090 case TemplateArgument::TemplateExpansion:
3091 return TemplateArgument(getCanonicalTemplateName(
3092 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003093 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003094
Douglas Gregor1275ae02009-07-28 23:00:59 +00003095 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003096 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003097 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003098
Douglas Gregor1275ae02009-07-28 23:00:59 +00003099 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003100 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003101
Douglas Gregor1275ae02009-07-28 23:00:59 +00003102 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003103 if (Arg.pack_size() == 0)
3104 return Arg;
3105
Douglas Gregor910f8002010-11-07 23:05:16 +00003106 TemplateArgument *CanonArgs
3107 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003108 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003109 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003110 AEnd = Arg.pack_end();
3111 A != AEnd; (void)++A, ++Idx)
3112 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003113
Douglas Gregor910f8002010-11-07 23:05:16 +00003114 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003115 }
3116 }
3117
3118 // Silence GCC warning
3119 assert(false && "Unhandled template argument kind");
3120 return TemplateArgument();
3121}
3122
Douglas Gregord57959a2009-03-27 23:10:48 +00003123NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003124ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003125 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003126 return 0;
3127
3128 switch (NNS->getKind()) {
3129 case NestedNameSpecifier::Identifier:
3130 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003131 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003132 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3133 NNS->getAsIdentifier());
3134
3135 case NestedNameSpecifier::Namespace:
3136 // A namespace is canonical; build a nested-name-specifier with
3137 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003138 return NestedNameSpecifier::Create(*this, 0,
3139 NNS->getAsNamespace()->getOriginalNamespace());
3140
3141 case NestedNameSpecifier::NamespaceAlias:
3142 // A namespace is canonical; build a nested-name-specifier with
3143 // this namespace and no prefix.
3144 return NestedNameSpecifier::Create(*this, 0,
3145 NNS->getAsNamespaceAlias()->getNamespace()
3146 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003147
3148 case NestedNameSpecifier::TypeSpec:
3149 case NestedNameSpecifier::TypeSpecWithTemplate: {
3150 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003151
3152 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3153 // break it apart into its prefix and identifier, then reconsititute those
3154 // as the canonical nested-name-specifier. This is required to canonicalize
3155 // a dependent nested-name-specifier involving typedefs of dependent-name
3156 // types, e.g.,
3157 // typedef typename T::type T1;
3158 // typedef typename T1::type T2;
3159 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3160 NestedNameSpecifier *Prefix
3161 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3162 return NestedNameSpecifier::Create(*this, Prefix,
3163 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3164 }
3165
Douglas Gregor643f8432010-11-04 00:14:23 +00003166 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003167 if (const DependentTemplateSpecializationType *DTST
3168 = T->getAs<DependentTemplateSpecializationType>()) {
3169 NestedNameSpecifier *Prefix
3170 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003171
3172 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3173 Prefix, DTST->getIdentifier(),
3174 DTST->getNumArgs(),
3175 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003176 T = getCanonicalType(T);
3177 }
3178
John McCall3b657512011-01-19 10:06:00 +00003179 return NestedNameSpecifier::Create(*this, 0, false,
3180 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003181 }
3182
3183 case NestedNameSpecifier::Global:
3184 // The global specifier is canonical and unique.
3185 return NNS;
3186 }
3187
3188 // Required to silence a GCC warning
3189 return 0;
3190}
3191
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003192
Jay Foad4ba2a172011-01-12 09:06:06 +00003193const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003194 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003195 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003196 // Handle the common positive case fast.
3197 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3198 return AT;
3199 }
Mike Stump1eb44332009-09-09 15:08:12 +00003200
John McCall0953e762009-09-24 19:53:00 +00003201 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003202 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003203 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003204
John McCall0953e762009-09-24 19:53:00 +00003205 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003206 // implements C99 6.7.3p8: "If the specification of an array type includes
3207 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003208
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003209 // If we get here, we either have type qualifiers on the type, or we have
3210 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003211 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003212
John McCall3b657512011-01-19 10:06:00 +00003213 SplitQualType split = T.getSplitDesugaredType();
3214 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003215
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003216 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003217 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3218 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003219 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003220
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003221 // Otherwise, we have an array and we have qualifiers on it. Push the
3222 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003223 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003224
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003225 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3226 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3227 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003228 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003229 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3230 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3231 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003232 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003233
Mike Stump1eb44332009-09-09 15:08:12 +00003234 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003235 = dyn_cast<DependentSizedArrayType>(ATy))
3236 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003237 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003238 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003239 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003240 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003241 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003242
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003243 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003244 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003245 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003246 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003247 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003248 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003249}
3250
Chris Lattnere6327742008-04-02 05:18:44 +00003251/// getArrayDecayedType - Return the properly qualified result of decaying the
3252/// specified array type to a pointer. This operation is non-trivial when
3253/// handling typedefs etc. The canonical type of "T" must be an array type,
3254/// this returns a pointer to a properly qualified element of the array.
3255///
3256/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003257QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003258 // Get the element type with 'getAsArrayType' so that we don't lose any
3259 // typedefs in the element type of the array. This also handles propagation
3260 // of type qualifiers from the array type into the element type if present
3261 // (C99 6.7.3p8).
3262 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3263 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003264
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003265 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003266
3267 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003268 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003269}
3270
John McCall3b657512011-01-19 10:06:00 +00003271QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3272 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003273}
3274
John McCall3b657512011-01-19 10:06:00 +00003275QualType ASTContext::getBaseElementType(QualType type) const {
3276 Qualifiers qs;
3277 while (true) {
3278 SplitQualType split = type.getSplitDesugaredType();
3279 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3280 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003281
John McCall3b657512011-01-19 10:06:00 +00003282 type = array->getElementType();
3283 qs.addConsistentQualifiers(split.second);
3284 }
Mike Stump1eb44332009-09-09 15:08:12 +00003285
John McCall3b657512011-01-19 10:06:00 +00003286 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003287}
3288
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003289/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003290uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003291ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3292 uint64_t ElementCount = 1;
3293 do {
3294 ElementCount *= CA->getSize().getZExtValue();
3295 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3296 } while (CA);
3297 return ElementCount;
3298}
3299
Reid Spencer5f016e22007-07-11 17:01:13 +00003300/// getFloatingRank - Return a relative rank for floating point types.
3301/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003302static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003303 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003304 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003305
John McCall183700f2009-09-21 23:43:11 +00003306 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3307 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00003308 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003309 case BuiltinType::Float: return FloatRank;
3310 case BuiltinType::Double: return DoubleRank;
3311 case BuiltinType::LongDouble: return LongDoubleRank;
3312 }
3313}
3314
Mike Stump1eb44332009-09-09 15:08:12 +00003315/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3316/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003317/// 'typeDomain' is a real floating point or complex type.
3318/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003319QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3320 QualType Domain) const {
3321 FloatingRank EltRank = getFloatingRank(Size);
3322 if (Domain->isComplexType()) {
3323 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00003324 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003325 case FloatRank: return FloatComplexTy;
3326 case DoubleRank: return DoubleComplexTy;
3327 case LongDoubleRank: return LongDoubleComplexTy;
3328 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003329 }
Chris Lattner1361b112008-04-06 23:58:54 +00003330
3331 assert(Domain->isRealFloatingType() && "Unknown domain!");
3332 switch (EltRank) {
3333 default: assert(0 && "getFloatingRank(): illegal value for rank");
3334 case FloatRank: return FloatTy;
3335 case DoubleRank: return DoubleTy;
3336 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003337 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003338}
3339
Chris Lattner7cfeb082008-04-06 23:55:33 +00003340/// getFloatingTypeOrder - Compare the rank of the two specified floating
3341/// point types, ignoring the domain of the type (i.e. 'double' ==
3342/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003343/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003344int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003345 FloatingRank LHSR = getFloatingRank(LHS);
3346 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003347
Chris Lattnera75cea32008-04-06 23:38:49 +00003348 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003349 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003350 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003351 return 1;
3352 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003353}
3354
Chris Lattnerf52ab252008-04-06 22:59:24 +00003355/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3356/// routine will assert if passed a built-in type that isn't an integer or enum,
3357/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003358unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003359 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCallf4c73712011-01-19 06:33:43 +00003360 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00003361 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00003362
Chris Lattner3f59c972010-12-25 23:25:43 +00003363 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3364 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmana3426752009-07-05 23:44:27 +00003365 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3366
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003367 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3368 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3369
3370 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3371 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3372
Chris Lattnerf52ab252008-04-06 22:59:24 +00003373 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00003374 default: assert(0 && "getIntegerRank(): not a built-in integer");
3375 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003376 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003377 case BuiltinType::Char_S:
3378 case BuiltinType::Char_U:
3379 case BuiltinType::SChar:
3380 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003381 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003382 case BuiltinType::Short:
3383 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003384 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003385 case BuiltinType::Int:
3386 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003387 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003388 case BuiltinType::Long:
3389 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003390 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003391 case BuiltinType::LongLong:
3392 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003393 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003394 case BuiltinType::Int128:
3395 case BuiltinType::UInt128:
3396 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003397 }
3398}
3399
Eli Friedman04e83572009-08-20 04:21:42 +00003400/// \brief Whether this is a promotable bitfield reference according
3401/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3402///
3403/// \returns the type this bit-field will promote to, or NULL if no
3404/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003405QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003406 if (E->isTypeDependent() || E->isValueDependent())
3407 return QualType();
3408
Eli Friedman04e83572009-08-20 04:21:42 +00003409 FieldDecl *Field = E->getBitField();
3410 if (!Field)
3411 return QualType();
3412
3413 QualType FT = Field->getType();
3414
3415 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3416 uint64_t BitWidth = BitWidthAP.getZExtValue();
3417 uint64_t IntSize = getTypeSize(IntTy);
3418 // GCC extension compatibility: if the bit-field size is less than or equal
3419 // to the size of int, it gets promoted no matter what its type is.
3420 // For instance, unsigned long bf : 4 gets promoted to signed int.
3421 if (BitWidth < IntSize)
3422 return IntTy;
3423
3424 if (BitWidth == IntSize)
3425 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3426
3427 // Types bigger than int are not subject to promotions, and therefore act
3428 // like the base type.
3429 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3430 // is ridiculous.
3431 return QualType();
3432}
3433
Eli Friedmana95d7572009-08-19 07:44:53 +00003434/// getPromotedIntegerType - Returns the type that Promotable will
3435/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3436/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003437QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003438 assert(!Promotable.isNull());
3439 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003440 if (const EnumType *ET = Promotable->getAs<EnumType>())
3441 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003442 if (Promotable->isSignedIntegerType())
3443 return IntTy;
3444 uint64_t PromotableSize = getTypeSize(Promotable);
3445 uint64_t IntSize = getTypeSize(IntTy);
3446 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3447 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3448}
3449
Mike Stump1eb44332009-09-09 15:08:12 +00003450/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003451/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003452/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003453int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003454 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3455 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003456 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003457
Chris Lattnerf52ab252008-04-06 22:59:24 +00003458 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3459 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003460
Chris Lattner7cfeb082008-04-06 23:55:33 +00003461 unsigned LHSRank = getIntegerRank(LHSC);
3462 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003463
Chris Lattner7cfeb082008-04-06 23:55:33 +00003464 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3465 if (LHSRank == RHSRank) return 0;
3466 return LHSRank > RHSRank ? 1 : -1;
3467 }
Mike Stump1eb44332009-09-09 15:08:12 +00003468
Chris Lattner7cfeb082008-04-06 23:55:33 +00003469 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3470 if (LHSUnsigned) {
3471 // If the unsigned [LHS] type is larger, return it.
3472 if (LHSRank >= RHSRank)
3473 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003474
Chris Lattner7cfeb082008-04-06 23:55:33 +00003475 // If the signed type can represent all values of the unsigned type, it
3476 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003477 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003478 return -1;
3479 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003480
Chris Lattner7cfeb082008-04-06 23:55:33 +00003481 // If the unsigned [RHS] type is larger, return it.
3482 if (RHSRank >= LHSRank)
3483 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003484
Chris Lattner7cfeb082008-04-06 23:55:33 +00003485 // If the signed type can represent all values of the unsigned type, it
3486 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003487 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003488 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003489}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003490
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003491static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003492CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3493 DeclContext *DC, IdentifierInfo *Id) {
3494 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003495 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003496 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003497 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003498 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003499}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003500
Mike Stump1eb44332009-09-09 15:08:12 +00003501// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003502QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003503 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003504 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003505 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003506 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003507 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003508
Anders Carlssonf06273f2007-11-19 00:25:30 +00003509 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003510
Anders Carlsson71993dd2007-08-17 05:31:46 +00003511 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003512 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003513 // int flags;
3514 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003515 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003516 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003517 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003518 FieldTypes[3] = LongTy;
3519
Anders Carlsson71993dd2007-08-17 05:31:46 +00003520 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003521 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003522 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003523 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003524 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003525 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003526 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003527 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003528 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003529 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003530 }
3531
Douglas Gregor838db382010-02-11 01:19:42 +00003532 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003533 }
Mike Stump1eb44332009-09-09 15:08:12 +00003534
Anders Carlsson71993dd2007-08-17 05:31:46 +00003535 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003536}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003537
Douglas Gregor319ac892009-04-23 22:29:11 +00003538void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003539 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003540 assert(Rec && "Invalid CFConstantStringType");
3541 CFConstantStringTypeDecl = Rec->getDecl();
3542}
3543
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003544// getNSConstantStringType - Return the type used for constant NSStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003545QualType ASTContext::getNSConstantStringType() const {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003546 if (!NSConstantStringTypeDecl) {
3547 NSConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003548 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003549 &Idents.get("__builtin_NSString"));
3550 NSConstantStringTypeDecl->startDefinition();
3551
3552 QualType FieldTypes[3];
3553
3554 // const int *isa;
3555 FieldTypes[0] = getPointerType(IntTy.withConst());
3556 // const char *str;
3557 FieldTypes[1] = getPointerType(CharTy.withConst());
3558 // unsigned int length;
3559 FieldTypes[2] = UnsignedIntTy;
3560
3561 // Create fields
3562 for (unsigned i = 0; i < 3; ++i) {
3563 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003564 SourceLocation(),
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003565 SourceLocation(), 0,
3566 FieldTypes[i], /*TInfo=*/0,
3567 /*BitWidth=*/0,
3568 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003569 Field->setAccess(AS_public);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00003570 NSConstantStringTypeDecl->addDecl(Field);
3571 }
3572
3573 NSConstantStringTypeDecl->completeDefinition();
3574 }
3575
3576 return getTagDeclType(NSConstantStringTypeDecl);
3577}
3578
3579void ASTContext::setNSConstantStringType(QualType T) {
3580 const RecordType *Rec = T->getAs<RecordType>();
3581 assert(Rec && "Invalid NSConstantStringType");
3582 NSConstantStringTypeDecl = Rec->getDecl();
3583}
3584
Jay Foad4ba2a172011-01-12 09:06:06 +00003585QualType ASTContext::getObjCFastEnumerationStateType() const {
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003586 if (!ObjCFastEnumerationStateTypeDecl) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003587 ObjCFastEnumerationStateTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003588 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003589 &Idents.get("__objcFastEnumerationState"));
John McCall5cfa0112010-02-05 01:33:36 +00003590 ObjCFastEnumerationStateTypeDecl->startDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003591
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003592 QualType FieldTypes[] = {
3593 UnsignedLongTy,
Steve Naroffde2e22d2009-07-15 18:40:39 +00003594 getPointerType(ObjCIdTypedefType),
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003595 getPointerType(UnsignedLongTy),
3596 getConstantArrayType(UnsignedLongTy,
3597 llvm::APInt(32, 5), ArrayType::Normal, 0)
3598 };
Mike Stump1eb44332009-09-09 15:08:12 +00003599
Douglas Gregor44b43212008-12-11 16:49:14 +00003600 for (size_t i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003601 FieldDecl *Field = FieldDecl::Create(*this,
3602 ObjCFastEnumerationStateTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003603 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00003604 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003605 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003606 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003607 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003608 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003609 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003610 }
Mike Stump1eb44332009-09-09 15:08:12 +00003611
Douglas Gregor838db382010-02-11 01:19:42 +00003612 ObjCFastEnumerationStateTypeDecl->completeDefinition();
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003613 }
Mike Stump1eb44332009-09-09 15:08:12 +00003614
Anders Carlssonbd4c1ad2008-08-30 19:34:46 +00003615 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3616}
3617
Jay Foad4ba2a172011-01-12 09:06:06 +00003618QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003619 if (BlockDescriptorType)
3620 return getTagDeclType(BlockDescriptorType);
3621
3622 RecordDecl *T;
3623 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003624 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003625 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003626 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003627
3628 QualType FieldTypes[] = {
3629 UnsignedLongTy,
3630 UnsignedLongTy,
3631 };
3632
3633 const char *FieldNames[] = {
3634 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003635 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003636 };
3637
3638 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003639 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003640 SourceLocation(),
3641 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003642 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003643 /*BitWidth=*/0,
3644 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003645 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003646 T->addDecl(Field);
3647 }
3648
Douglas Gregor838db382010-02-11 01:19:42 +00003649 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003650
3651 BlockDescriptorType = T;
3652
3653 return getTagDeclType(BlockDescriptorType);
3654}
3655
3656void ASTContext::setBlockDescriptorType(QualType T) {
3657 const RecordType *Rec = T->getAs<RecordType>();
3658 assert(Rec && "Invalid BlockDescriptorType");
3659 BlockDescriptorType = Rec->getDecl();
3660}
3661
Jay Foad4ba2a172011-01-12 09:06:06 +00003662QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003663 if (BlockDescriptorExtendedType)
3664 return getTagDeclType(BlockDescriptorExtendedType);
3665
3666 RecordDecl *T;
3667 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003668 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003669 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003670 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003671
3672 QualType FieldTypes[] = {
3673 UnsignedLongTy,
3674 UnsignedLongTy,
3675 getPointerType(VoidPtrTy),
3676 getPointerType(VoidPtrTy)
3677 };
3678
3679 const char *FieldNames[] = {
3680 "reserved",
3681 "Size",
3682 "CopyFuncPtr",
3683 "DestroyFuncPtr"
3684 };
3685
3686 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003687 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003688 SourceLocation(),
3689 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003690 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003691 /*BitWidth=*/0,
3692 /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003693 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003694 T->addDecl(Field);
3695 }
3696
Douglas Gregor838db382010-02-11 01:19:42 +00003697 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003698
3699 BlockDescriptorExtendedType = T;
3700
3701 return getTagDeclType(BlockDescriptorExtendedType);
3702}
3703
3704void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3705 const RecordType *Rec = T->getAs<RecordType>();
3706 assert(Rec && "Invalid BlockDescriptorType");
3707 BlockDescriptorExtendedType = Rec->getDecl();
3708}
3709
Jay Foad4ba2a172011-01-12 09:06:06 +00003710bool ASTContext::BlockRequiresCopying(QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003711 if (Ty->isBlockPointerType())
3712 return true;
3713 if (isObjCNSObjectType(Ty))
3714 return true;
3715 if (Ty->isObjCObjectPointerType())
3716 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003717 if (getLangOptions().CPlusPlus) {
3718 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3719 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3720 return RD->hasConstCopyConstructor(*this);
3721
3722 }
3723 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003724 return false;
3725}
3726
Jay Foad4ba2a172011-01-12 09:06:06 +00003727QualType
3728ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003729 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003730 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003731 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003732 // unsigned int __flags;
3733 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003734 // void *__copy_helper; // as needed
3735 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003736 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003737 // } *
3738
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003739 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3740
3741 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003742 llvm::SmallString<36> Name;
3743 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3744 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003745 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003746 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003747 T->startDefinition();
3748 QualType Int32Ty = IntTy;
3749 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3750 QualType FieldTypes[] = {
3751 getPointerType(VoidPtrTy),
3752 getPointerType(getTagDeclType(T)),
3753 Int32Ty,
3754 Int32Ty,
3755 getPointerType(VoidPtrTy),
3756 getPointerType(VoidPtrTy),
3757 Ty
3758 };
3759
Daniel Dunbar4087f272010-08-17 22:39:59 +00003760 llvm::StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003761 "__isa",
3762 "__forwarding",
3763 "__flags",
3764 "__size",
3765 "__copy_helper",
3766 "__destroy_helper",
3767 DeclName,
3768 };
3769
3770 for (size_t i = 0; i < 7; ++i) {
3771 if (!HasCopyAndDispose && i >=4 && i <= 5)
3772 continue;
3773 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003774 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003775 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003776 FieldTypes[i], /*TInfo=*/0,
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003777 /*BitWidth=*/0, /*Mutable=*/false);
John McCall2888b652010-04-30 21:35:41 +00003778 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003779 T->addDecl(Field);
3780 }
3781
Douglas Gregor838db382010-02-11 01:19:42 +00003782 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003783
3784 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003785}
3786
Douglas Gregor319ac892009-04-23 22:29:11 +00003787void ASTContext::setObjCFastEnumerationStateType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003788 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003789 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3790 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3791}
3792
Anders Carlssone8c49532007-10-29 06:33:42 +00003793// This returns true if a type has been typedefed to BOOL:
3794// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003795static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003796 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003797 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3798 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003799
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003800 return false;
3801}
3802
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003803/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003804/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003805CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Ken Dyck199c3d62010-01-11 17:06:35 +00003806 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003807
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003808 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003809 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003810 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003811 // Treat arrays as pointers, since that's how they're passed in.
3812 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003813 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003814 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003815}
3816
3817static inline
3818std::string charUnitsToString(const CharUnits &CU) {
3819 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003820}
3821
John McCall6b5a61b2011-02-07 10:33:21 +00003822/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003823/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00003824std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3825 std::string S;
3826
David Chisnall5e530af2009-11-17 19:33:30 +00003827 const BlockDecl *Decl = Expr->getBlockDecl();
3828 QualType BlockTy =
3829 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3830 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003831 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003832 // Compute size of all parameters.
3833 // Start with computing size of a pointer in number of bytes.
3834 // FIXME: There might(should) be a better way of doing this computation!
3835 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003836 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3837 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003838 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003839 E = Decl->param_end(); PI != E; ++PI) {
3840 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003841 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003842 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003843 ParmOffset += sz;
3844 }
3845 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003846 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003847 // Block pointer and offset.
3848 S += "@?0";
3849 ParmOffset = PtrSize;
3850
3851 // Argument types.
3852 ParmOffset = PtrSize;
3853 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3854 Decl->param_end(); PI != E; ++PI) {
3855 ParmVarDecl *PVDecl = *PI;
3856 QualType PType = PVDecl->getOriginalType();
3857 if (const ArrayType *AT =
3858 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3859 // Use array's original type only if it has known number of
3860 // elements.
3861 if (!isa<ConstantArrayType>(AT))
3862 PType = PVDecl->getType();
3863 } else if (PType->isFunctionType())
3864 PType = PVDecl->getType();
3865 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003866 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003867 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003868 }
John McCall6b5a61b2011-02-07 10:33:21 +00003869
3870 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00003871}
3872
David Chisnall5389f482010-12-30 14:05:53 +00003873void ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3874 std::string& S) {
3875 // Encode result type.
3876 getObjCEncodingForType(Decl->getResultType(), S);
3877 CharUnits ParmOffset;
3878 // Compute size of all parameters.
3879 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3880 E = Decl->param_end(); PI != E; ++PI) {
3881 QualType PType = (*PI)->getType();
3882 CharUnits sz = getObjCEncodingTypeSize(PType);
3883 assert (sz.isPositive() &&
3884 "getObjCEncodingForMethodDecl - Incomplete param type");
3885 ParmOffset += sz;
3886 }
3887 S += charUnitsToString(ParmOffset);
3888 ParmOffset = CharUnits::Zero();
3889
3890 // Argument types.
3891 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3892 E = Decl->param_end(); PI != E; ++PI) {
3893 ParmVarDecl *PVDecl = *PI;
3894 QualType PType = PVDecl->getOriginalType();
3895 if (const ArrayType *AT =
3896 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3897 // Use array's original type only if it has known number of
3898 // elements.
3899 if (!isa<ConstantArrayType>(AT))
3900 PType = PVDecl->getType();
3901 } else if (PType->isFunctionType())
3902 PType = PVDecl->getType();
3903 getObjCEncodingForType(PType, S);
3904 S += charUnitsToString(ParmOffset);
3905 ParmOffset += getObjCEncodingTypeSize(PType);
3906 }
3907}
3908
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003909/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003910/// declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003911void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00003912 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003913 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003914 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003915 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003916 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003917 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003918 // Compute size of all parameters.
3919 // Start with computing size of a pointer in number of bytes.
3920 // FIXME: There might(should) be a better way of doing this computation!
3921 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003922 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003923 // The first two arguments (self and _cmd) are pointers; account for
3924 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003925 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003926 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003927 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003928 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003929 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003930 assert (sz.isPositive() &&
3931 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003932 ParmOffset += sz;
3933 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003934 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003935 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003936 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003937
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003938 // Argument types.
3939 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003940 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003941 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003942 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003943 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003944 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003945 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3946 // Use array's original type only if it has known number of
3947 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003948 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003949 PType = PVDecl->getType();
3950 } else if (PType->isFunctionType())
3951 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003952 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003953 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003954 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003955 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003956 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003957 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003958 }
3959}
3960
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003961/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003962/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003963/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3964/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003965/// Property attributes are stored as a comma-delimited C string. The simple
3966/// attributes readonly and bycopy are encoded as single characters. The
3967/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3968/// encoded as single characters, followed by an identifier. Property types
3969/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003970/// these attributes are defined by the following enumeration:
3971/// @code
3972/// enum PropertyAttributes {
3973/// kPropertyReadOnly = 'R', // property is read-only.
3974/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3975/// kPropertyByref = '&', // property is a reference to the value last assigned
3976/// kPropertyDynamic = 'D', // property is dynamic
3977/// kPropertyGetter = 'G', // followed by getter selector name
3978/// kPropertySetter = 'S', // followed by setter selector name
3979/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3980/// kPropertyType = 't' // followed by old-style type encoding.
3981/// kPropertyWeak = 'W' // 'weak' property
3982/// kPropertyStrong = 'P' // property GC'able
3983/// kPropertyNonAtomic = 'N' // property non-atomic
3984/// };
3985/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003986void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003987 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00003988 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003989 // Collect information from the property implementation decl(s).
3990 bool Dynamic = false;
3991 ObjCPropertyImplDecl *SynthesizePID = 0;
3992
3993 // FIXME: Duplicated code due to poor abstraction.
3994 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00003995 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003996 dyn_cast<ObjCCategoryImplDecl>(Container)) {
3997 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003998 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003999 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004000 ObjCPropertyImplDecl *PID = *i;
4001 if (PID->getPropertyDecl() == PD) {
4002 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4003 Dynamic = true;
4004 } else {
4005 SynthesizePID = PID;
4006 }
4007 }
4008 }
4009 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004010 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004011 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004012 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004013 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004014 ObjCPropertyImplDecl *PID = *i;
4015 if (PID->getPropertyDecl() == PD) {
4016 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4017 Dynamic = true;
4018 } else {
4019 SynthesizePID = PID;
4020 }
4021 }
Mike Stump1eb44332009-09-09 15:08:12 +00004022 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004023 }
4024 }
4025
4026 // FIXME: This is not very efficient.
4027 S = "T";
4028
4029 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004030 // GCC has some special rules regarding encoding of properties which
4031 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004032 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004033 true /* outermost type */,
4034 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004035
4036 if (PD->isReadOnly()) {
4037 S += ",R";
4038 } else {
4039 switch (PD->getSetterKind()) {
4040 case ObjCPropertyDecl::Assign: break;
4041 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004042 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004043 }
4044 }
4045
4046 // It really isn't clear at all what this means, since properties
4047 // are "dynamic by default".
4048 if (Dynamic)
4049 S += ",D";
4050
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004051 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4052 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004053
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004054 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4055 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004056 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004057 }
4058
4059 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4060 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004061 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004062 }
4063
4064 if (SynthesizePID) {
4065 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4066 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004067 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004068 }
4069
4070 // FIXME: OBJCGC: weak & strong
4071}
4072
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004073/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004074/// Another legacy compatibility encoding: 32-bit longs are encoded as
4075/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004076/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4077///
4078void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004079 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004080 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004081 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004082 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004083 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004084 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004085 PointeeTy = IntTy;
4086 }
4087 }
4088}
4089
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004090void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004091 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004092 // We follow the behavior of gcc, expanding structures which are
4093 // directly pointed to, and expanding embedded structures. Note that
4094 // these rules are sufficient to prevent recursive encoding of the
4095 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004096 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004097 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004098}
4099
David Chisnall64fd7e82010-06-04 01:10:52 +00004100static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4101 switch (T->getAs<BuiltinType>()->getKind()) {
4102 default: assert(0 && "Unhandled builtin type kind");
4103 case BuiltinType::Void: return 'v';
4104 case BuiltinType::Bool: return 'B';
4105 case BuiltinType::Char_U:
4106 case BuiltinType::UChar: return 'C';
4107 case BuiltinType::UShort: return 'S';
4108 case BuiltinType::UInt: return 'I';
4109 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004110 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004111 case BuiltinType::UInt128: return 'T';
4112 case BuiltinType::ULongLong: return 'Q';
4113 case BuiltinType::Char_S:
4114 case BuiltinType::SChar: return 'c';
4115 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004116 case BuiltinType::WChar_S:
4117 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004118 case BuiltinType::Int: return 'i';
4119 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004120 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004121 case BuiltinType::LongLong: return 'q';
4122 case BuiltinType::Int128: return 't';
4123 case BuiltinType::Float: return 'f';
4124 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004125 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004126 }
4127}
4128
Jay Foad4ba2a172011-01-12 09:06:06 +00004129static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004130 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004131 const Expr *E = FD->getBitWidth();
4132 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004133 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004134 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4135 // The GNU runtime requires more information; bitfields are encoded as b,
4136 // then the offset (in bits) of the first element, then the type of the
4137 // bitfield, then the size in bits. For example, in this structure:
4138 //
4139 // struct
4140 // {
4141 // int integer;
4142 // int flags:2;
4143 // };
4144 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4145 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4146 // information is not especially sensible, but we're stuck with it for
4147 // compatibility with GCC, although providing it breaks anything that
4148 // actually uses runtime introspection and wants to work on both runtimes...
4149 if (!Ctx->getLangOptions().NeXTRuntime) {
4150 const RecordDecl *RD = FD->getParent();
4151 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4152 // FIXME: This same linear search is also used in ExprConstant - it might
4153 // be better if the FieldDecl stored its offset. We'd be increasing the
4154 // size of the object slightly, but saving some time every time it is used.
4155 unsigned i = 0;
4156 for (RecordDecl::field_iterator Field = RD->field_begin(),
4157 FieldEnd = RD->field_end();
4158 Field != FieldEnd; (void)++Field, ++i) {
4159 if (*Field == FD)
4160 break;
4161 }
4162 S += llvm::utostr(RL.getFieldOffset(i));
David Chisnallc7ff82c2010-12-26 20:12:30 +00004163 if (T->isEnumeralType())
4164 S += 'i';
4165 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004166 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004167 }
4168 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004169 S += llvm::utostr(N);
4170}
4171
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004172// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004173void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4174 bool ExpandPointedToStructures,
4175 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004176 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004177 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004178 bool EncodingProperty,
4179 bool StructField) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004180 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004181 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004182 return EncodeBitField(this, S, T, FD);
4183 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004184 return;
4185 }
Mike Stump1eb44332009-09-09 15:08:12 +00004186
John McCall183700f2009-09-21 23:43:11 +00004187 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004188 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004189 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004190 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004191 return;
4192 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004193
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004194 // encoding for pointer or r3eference types.
4195 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004196 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004197 if (PT->isObjCSelType()) {
4198 S += ':';
4199 return;
4200 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004201 PointeeTy = PT->getPointeeType();
4202 }
4203 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4204 PointeeTy = RT->getPointeeType();
4205 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004206 bool isReadOnly = false;
4207 // For historical/compatibility reasons, the read-only qualifier of the
4208 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4209 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004210 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004211 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004212 if (OutermostType && T.isConstQualified()) {
4213 isReadOnly = true;
4214 S += 'r';
4215 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004216 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004217 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004218 while (P->getAs<PointerType>())
4219 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004220 if (P.isConstQualified()) {
4221 isReadOnly = true;
4222 S += 'r';
4223 }
4224 }
4225 if (isReadOnly) {
4226 // Another legacy compatibility encoding. Some ObjC qualifier and type
4227 // combinations need to be rearranged.
4228 // Rewrite "in const" from "nr" to "rn"
Benjamin Kramer02379412010-04-27 17:12:11 +00004229 if (llvm::StringRef(S).endswith("nr"))
4230 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004231 }
Mike Stump1eb44332009-09-09 15:08:12 +00004232
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004233 if (PointeeTy->isCharType()) {
4234 // char pointer types should be encoded as '*' unless it is a
4235 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004236 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004237 S += '*';
4238 return;
4239 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004240 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004241 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4242 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4243 S += '#';
4244 return;
4245 }
4246 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4247 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4248 S += '@';
4249 return;
4250 }
4251 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004252 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004253 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004254 getLegacyIntegralTypeEncoding(PointeeTy);
4255
Mike Stump1eb44332009-09-09 15:08:12 +00004256 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004257 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004258 return;
4259 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004260
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004261 if (const ArrayType *AT =
4262 // Ignore type qualifiers etc.
4263 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004264 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004265 // Incomplete arrays are encoded as a pointer to the array element.
4266 S += '^';
4267
Mike Stump1eb44332009-09-09 15:08:12 +00004268 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004269 false, ExpandStructures, FD);
4270 } else {
4271 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004272
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004273 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4274 if (getTypeSize(CAT->getElementType()) == 0)
4275 S += '0';
4276 else
4277 S += llvm::utostr(CAT->getSize().getZExtValue());
4278 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004279 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004280 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4281 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004282 S += '0';
4283 }
Mike Stump1eb44332009-09-09 15:08:12 +00004284
4285 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004286 false, ExpandStructures, FD);
4287 S += ']';
4288 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004289 return;
4290 }
Mike Stump1eb44332009-09-09 15:08:12 +00004291
John McCall183700f2009-09-21 23:43:11 +00004292 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004293 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004294 return;
4295 }
Mike Stump1eb44332009-09-09 15:08:12 +00004296
Ted Kremenek6217b802009-07-29 21:53:49 +00004297 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004298 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004299 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004300 // Anonymous structures print as '?'
4301 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4302 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004303 if (ClassTemplateSpecializationDecl *Spec
4304 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4305 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4306 std::string TemplateArgsStr
4307 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004308 TemplateArgs.data(),
4309 TemplateArgs.size(),
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004310 (*this).PrintingPolicy);
4311
4312 S += TemplateArgsStr;
4313 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004314 } else {
4315 S += '?';
4316 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004317 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004318 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004319 if (!RDecl->isUnion()) {
4320 getObjCEncodingForStructureImpl(RDecl, S, FD);
4321 } else {
4322 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4323 FieldEnd = RDecl->field_end();
4324 Field != FieldEnd; ++Field) {
4325 if (FD) {
4326 S += '"';
4327 S += Field->getNameAsString();
4328 S += '"';
4329 }
Mike Stump1eb44332009-09-09 15:08:12 +00004330
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004331 // Special case bit-fields.
4332 if (Field->isBitField()) {
4333 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4334 (*Field));
4335 } else {
4336 QualType qt = Field->getType();
4337 getLegacyIntegralTypeEncoding(qt);
4338 getObjCEncodingForTypeImpl(qt, S, false, true,
4339 FD, /*OutermostType*/false,
4340 /*EncodingProperty*/false,
4341 /*StructField*/true);
4342 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004343 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004344 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004345 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004346 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004347 return;
4348 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004349
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004350 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004351 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004352 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004353 else
4354 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004355 return;
4356 }
Mike Stump1eb44332009-09-09 15:08:12 +00004357
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004358 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004359 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004360 return;
4361 }
Mike Stump1eb44332009-09-09 15:08:12 +00004362
John McCallc12c5bb2010-05-15 11:32:37 +00004363 // Ignore protocol qualifiers when mangling at this level.
4364 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4365 T = OT->getBaseType();
4366
John McCall0953e762009-09-24 19:53:00 +00004367 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004368 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004369 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004370 S += '{';
4371 const IdentifierInfo *II = OI->getIdentifier();
4372 S += II->getName();
4373 S += '=';
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004374 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4375 DeepCollectObjCIvars(OI, true, Ivars);
4376 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4377 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4378 if (Field->isBitField())
4379 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004380 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004381 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004382 }
4383 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004384 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004385 }
Mike Stump1eb44332009-09-09 15:08:12 +00004386
John McCall183700f2009-09-21 23:43:11 +00004387 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004388 if (OPT->isObjCIdType()) {
4389 S += '@';
4390 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004391 }
Mike Stump1eb44332009-09-09 15:08:12 +00004392
Steve Naroff27d20a22009-10-28 22:03:49 +00004393 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4394 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4395 // Since this is a binary compatibility issue, need to consult with runtime
4396 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004397 S += '#';
4398 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004399 }
Mike Stump1eb44332009-09-09 15:08:12 +00004400
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004401 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004402 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004403 ExpandPointedToStructures,
4404 ExpandStructures, FD);
4405 if (FD || EncodingProperty) {
4406 // Note that we do extended encoding of protocol qualifer list
4407 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004408 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004409 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4410 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004411 S += '<';
4412 S += (*I)->getNameAsString();
4413 S += '>';
4414 }
4415 S += '"';
4416 }
4417 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004418 }
Mike Stump1eb44332009-09-09 15:08:12 +00004419
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004420 QualType PointeeTy = OPT->getPointeeType();
4421 if (!EncodingProperty &&
4422 isa<TypedefType>(PointeeTy.getTypePtr())) {
4423 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004424 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004425 // {...};
4426 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004427 getObjCEncodingForTypeImpl(PointeeTy, S,
4428 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004429 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004430 return;
4431 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004432
4433 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004434 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004435 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004436 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004437 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4438 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004439 S += '<';
4440 S += (*I)->getNameAsString();
4441 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004442 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004443 S += '"';
4444 }
4445 return;
4446 }
Mike Stump1eb44332009-09-09 15:08:12 +00004447
John McCall532ec7b2010-05-17 23:56:34 +00004448 // gcc just blithely ignores member pointers.
4449 // TODO: maybe there should be a mangling for these
4450 if (T->getAs<MemberPointerType>())
4451 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004452
4453 if (T->isVectorType()) {
4454 // This matches gcc's encoding, even though technically it is
4455 // insufficient.
4456 // FIXME. We should do a better job than gcc.
4457 return;
4458 }
4459
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004460 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004461}
4462
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004463void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4464 std::string &S,
4465 const FieldDecl *FD,
4466 bool includeVBases) const {
4467 assert(RDecl && "Expected non-null RecordDecl");
4468 assert(!RDecl->isUnion() && "Should not be called for unions");
4469 if (!RDecl->getDefinition())
4470 return;
4471
4472 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4473 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4474 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4475
4476 if (CXXRec) {
4477 for (CXXRecordDecl::base_class_iterator
4478 BI = CXXRec->bases_begin(),
4479 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4480 if (!BI->isVirtual()) {
4481 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4482 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4483 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4484 std::make_pair(offs, base));
4485 }
4486 }
4487 }
4488
4489 unsigned i = 0;
4490 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4491 FieldEnd = RDecl->field_end();
4492 Field != FieldEnd; ++Field, ++i) {
4493 uint64_t offs = layout.getFieldOffset(i);
4494 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4495 std::make_pair(offs, *Field));
4496 }
4497
4498 if (CXXRec && includeVBases) {
4499 for (CXXRecordDecl::base_class_iterator
4500 BI = CXXRec->vbases_begin(),
4501 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4502 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4503 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4504 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4505 std::make_pair(offs, base));
4506 }
4507 }
4508
4509 CharUnits size;
4510 if (CXXRec) {
4511 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4512 } else {
4513 size = layout.getSize();
4514 }
4515
4516 uint64_t CurOffs = 0;
4517 std::multimap<uint64_t, NamedDecl *>::iterator
4518 CurLayObj = FieldOrBaseOffsets.begin();
4519
4520 if (CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) {
4521 assert(CXXRec && CXXRec->isDynamicClass() &&
4522 "Offset 0 was empty but no VTable ?");
4523 if (FD) {
4524 S += "\"_vptr$";
4525 std::string recname = CXXRec->getNameAsString();
4526 if (recname.empty()) recname = "?";
4527 S += recname;
4528 S += '"';
4529 }
4530 S += "^^?";
4531 CurOffs += getTypeSize(VoidPtrTy);
4532 }
4533
4534 if (!RDecl->hasFlexibleArrayMember()) {
4535 // Mark the end of the structure.
4536 uint64_t offs = toBits(size);
4537 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4538 std::make_pair(offs, (NamedDecl*)0));
4539 }
4540
4541 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4542 assert(CurOffs <= CurLayObj->first);
4543
4544 if (CurOffs < CurLayObj->first) {
4545 uint64_t padding = CurLayObj->first - CurOffs;
4546 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4547 // packing/alignment of members is different that normal, in which case
4548 // the encoding will be out-of-sync with the real layout.
4549 // If the runtime switches to just consider the size of types without
4550 // taking into account alignment, we could make padding explicit in the
4551 // encoding (e.g. using arrays of chars). The encoding strings would be
4552 // longer then though.
4553 CurOffs += padding;
4554 }
4555
4556 NamedDecl *dcl = CurLayObj->second;
4557 if (dcl == 0)
4558 break; // reached end of structure.
4559
4560 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4561 // We expand the bases without their virtual bases since those are going
4562 // in the initial structure. Note that this differs from gcc which
4563 // expands virtual bases each time one is encountered in the hierarchy,
4564 // making the encoding type bigger than it really is.
4565 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
4566 if (!base->isEmpty())
4567 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
4568 } else {
4569 FieldDecl *field = cast<FieldDecl>(dcl);
4570 if (FD) {
4571 S += '"';
4572 S += field->getNameAsString();
4573 S += '"';
4574 }
4575
4576 if (field->isBitField()) {
4577 EncodeBitField(this, S, field->getType(), field);
4578 CurOffs += field->getBitWidth()->EvaluateAsInt(*this).getZExtValue();
4579 } else {
4580 QualType qt = field->getType();
4581 getLegacyIntegralTypeEncoding(qt);
4582 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4583 /*OutermostType*/false,
4584 /*EncodingProperty*/false,
4585 /*StructField*/true);
4586 CurOffs += getTypeSize(field->getType());
4587 }
4588 }
4589 }
4590}
4591
Mike Stump1eb44332009-09-09 15:08:12 +00004592void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004593 std::string& S) const {
4594 if (QT & Decl::OBJC_TQ_In)
4595 S += 'n';
4596 if (QT & Decl::OBJC_TQ_Inout)
4597 S += 'N';
4598 if (QT & Decl::OBJC_TQ_Out)
4599 S += 'o';
4600 if (QT & Decl::OBJC_TQ_Bycopy)
4601 S += 'O';
4602 if (QT & Decl::OBJC_TQ_Byref)
4603 S += 'R';
4604 if (QT & Decl::OBJC_TQ_Oneway)
4605 S += 'V';
4606}
4607
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004608void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004609 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004610
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004611 BuiltinVaListType = T;
4612}
4613
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004614void ASTContext::setObjCIdType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004615 ObjCIdTypedefType = T;
Steve Naroff7e219e42007-10-15 14:41:52 +00004616}
4617
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004618void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00004619 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004620}
4621
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004622void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004623 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004624}
4625
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004626void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004627 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004628}
4629
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004630void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004631 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004632 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004633
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004634 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004635}
4636
John McCall0bd6feb2009-12-02 08:04:21 +00004637/// \brief Retrieve the template name that corresponds to a non-empty
4638/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004639TemplateName
4640ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4641 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004642 unsigned size = End - Begin;
4643 assert(size > 1 && "set is not overloaded!");
4644
4645 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4646 size * sizeof(FunctionTemplateDecl*));
4647 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4648
4649 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004650 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004651 NamedDecl *D = *I;
4652 assert(isa<FunctionTemplateDecl>(D) ||
4653 (isa<UsingShadowDecl>(D) &&
4654 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4655 *Storage++ = D;
4656 }
4657
4658 return TemplateName(OT);
4659}
4660
Douglas Gregor7532dc62009-03-30 22:58:21 +00004661/// \brief Retrieve the template name that represents a qualified
4662/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004663TemplateName
4664ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4665 bool TemplateKeyword,
4666 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004667 assert(NNS && "Missing nested-name-specifier in qualified template name");
4668
Douglas Gregor789b1f62010-02-04 18:10:26 +00004669 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004670 llvm::FoldingSetNodeID ID;
4671 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4672
4673 void *InsertPos = 0;
4674 QualifiedTemplateName *QTN =
4675 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4676 if (!QTN) {
4677 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4678 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4679 }
4680
4681 return TemplateName(QTN);
4682}
4683
4684/// \brief Retrieve the template name that represents a dependent
4685/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004686TemplateName
4687ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4688 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004689 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004690 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004691
4692 llvm::FoldingSetNodeID ID;
4693 DependentTemplateName::Profile(ID, NNS, Name);
4694
4695 void *InsertPos = 0;
4696 DependentTemplateName *QTN =
4697 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4698
4699 if (QTN)
4700 return TemplateName(QTN);
4701
4702 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4703 if (CanonNNS == NNS) {
4704 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4705 } else {
4706 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4707 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004708 DependentTemplateName *CheckQTN =
4709 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4710 assert(!CheckQTN && "Dependent type name canonicalization broken");
4711 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004712 }
4713
4714 DependentTemplateNames.InsertNode(QTN, InsertPos);
4715 return TemplateName(QTN);
4716}
4717
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004718/// \brief Retrieve the template name that represents a dependent
4719/// template name such as \c MetaFun::template operator+.
4720TemplateName
4721ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004722 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004723 assert((!NNS || NNS->isDependent()) &&
4724 "Nested name specifier must be dependent");
4725
4726 llvm::FoldingSetNodeID ID;
4727 DependentTemplateName::Profile(ID, NNS, Operator);
4728
4729 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004730 DependentTemplateName *QTN
4731 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004732
4733 if (QTN)
4734 return TemplateName(QTN);
4735
4736 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4737 if (CanonNNS == NNS) {
4738 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4739 } else {
4740 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4741 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004742
4743 DependentTemplateName *CheckQTN
4744 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4745 assert(!CheckQTN && "Dependent template name canonicalization broken");
4746 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004747 }
4748
4749 DependentTemplateNames.InsertNode(QTN, InsertPos);
4750 return TemplateName(QTN);
4751}
4752
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004753TemplateName
4754ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4755 const TemplateArgument &ArgPack) const {
4756 ASTContext &Self = const_cast<ASTContext &>(*this);
4757 llvm::FoldingSetNodeID ID;
4758 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4759
4760 void *InsertPos = 0;
4761 SubstTemplateTemplateParmPackStorage *Subst
4762 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4763
4764 if (!Subst) {
4765 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4766 ArgPack.pack_size(),
4767 ArgPack.pack_begin());
4768 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4769 }
4770
4771 return TemplateName(Subst);
4772}
4773
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004774/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004775/// TargetInfo, produce the corresponding type. The unsigned @p Type
4776/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004777CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004778 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004779 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004780 case TargetInfo::SignedShort: return ShortTy;
4781 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4782 case TargetInfo::SignedInt: return IntTy;
4783 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4784 case TargetInfo::SignedLong: return LongTy;
4785 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4786 case TargetInfo::SignedLongLong: return LongLongTy;
4787 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4788 }
4789
4790 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004791 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004792}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004793
4794//===----------------------------------------------------------------------===//
4795// Type Predicates.
4796//===----------------------------------------------------------------------===//
4797
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004798/// isObjCNSObjectType - Return true if this is an NSObject object using
4799/// NSObject attribute on a c-style pointer type.
4800/// FIXME - Make it work directly on types.
Steve Narofff4954562009-07-16 15:41:00 +00004801/// FIXME: Move to Type.
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004802///
4803bool ASTContext::isObjCNSObjectType(QualType Ty) const {
John McCallf4c73712011-01-19 06:33:43 +00004804 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
Richard Smith162e1c12011-04-15 14:24:37 +00004805 if (TypedefNameDecl *TD = TDT->getDecl())
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004806 if (TD->getAttr<ObjCNSObjectAttr>())
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004807 return true;
4808 }
Mike Stump1eb44332009-09-09 15:08:12 +00004809 return false;
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004810}
4811
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004812/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4813/// garbage collection attribute.
4814///
John McCallae278a32011-01-12 00:34:59 +00004815Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4816 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4817 return Qualifiers::GCNone;
4818
4819 assert(getLangOptions().ObjC1);
4820 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4821
4822 // Default behaviour under objective-C's gc is for ObjC pointers
4823 // (or pointers to them) be treated as though they were declared
4824 // as __strong.
4825 if (GCAttrs == Qualifiers::GCNone) {
4826 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4827 return Qualifiers::Strong;
4828 else if (Ty->isPointerType())
4829 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4830 } else {
4831 // It's not valid to set GC attributes on anything that isn't a
4832 // pointer.
4833#ifndef NDEBUG
4834 QualType CT = Ty->getCanonicalTypeInternal();
4835 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4836 CT = AT->getElementType();
4837 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4838#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004839 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004840 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004841}
4842
Chris Lattner6ac46a42008-04-07 06:51:04 +00004843//===----------------------------------------------------------------------===//
4844// Type Compatibility Testing
4845//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004846
Mike Stump1eb44332009-09-09 15:08:12 +00004847/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004848/// compatible.
4849static bool areCompatVectorTypes(const VectorType *LHS,
4850 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004851 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004852 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004853 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004854}
4855
Douglas Gregor255210e2010-08-06 10:14:59 +00004856bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4857 QualType SecondVec) {
4858 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4859 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4860
4861 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4862 return true;
4863
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004864 // Treat Neon vector types and most AltiVec vector types as if they are the
4865 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00004866 const VectorType *First = FirstVec->getAs<VectorType>();
4867 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004868 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00004869 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004870 First->getVectorKind() != VectorType::AltiVecPixel &&
4871 First->getVectorKind() != VectorType::AltiVecBool &&
4872 Second->getVectorKind() != VectorType::AltiVecPixel &&
4873 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00004874 return true;
4875
4876 return false;
4877}
4878
Steve Naroff4084c302009-07-23 01:01:38 +00004879//===----------------------------------------------------------------------===//
4880// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4881//===----------------------------------------------------------------------===//
4882
4883/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4884/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00004885bool
4886ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4887 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00004888 if (lProto == rProto)
4889 return true;
4890 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4891 E = rProto->protocol_end(); PI != E; ++PI)
4892 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4893 return true;
4894 return false;
4895}
4896
Steve Naroff4084c302009-07-23 01:01:38 +00004897/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4898/// return true if lhs's protocols conform to rhs's protocol; false
4899/// otherwise.
4900bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4901 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4902 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4903 return false;
4904}
4905
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004906/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4907/// Class<p1, ...>.
4908bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4909 QualType rhs) {
4910 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4911 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4912 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4913
4914 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4915 E = lhsQID->qual_end(); I != E; ++I) {
4916 bool match = false;
4917 ObjCProtocolDecl *lhsProto = *I;
4918 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4919 E = rhsOPT->qual_end(); J != E; ++J) {
4920 ObjCProtocolDecl *rhsProto = *J;
4921 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4922 match = true;
4923 break;
4924 }
4925 }
4926 if (!match)
4927 return false;
4928 }
4929 return true;
4930}
4931
Steve Naroff4084c302009-07-23 01:01:38 +00004932/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4933/// ObjCQualifiedIDType.
4934bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4935 bool compare) {
4936 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004937 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004938 lhs->isObjCIdType() || lhs->isObjCClassType())
4939 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004940 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004941 rhs->isObjCIdType() || rhs->isObjCClassType())
4942 return true;
4943
4944 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004945 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004946
Steve Naroff4084c302009-07-23 01:01:38 +00004947 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004948
Steve Naroff4084c302009-07-23 01:01:38 +00004949 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004950 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004951 // make sure we check the class hierarchy.
4952 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4953 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4954 E = lhsQID->qual_end(); I != E; ++I) {
4955 // when comparing an id<P> on lhs with a static type on rhs,
4956 // see if static class implements all of id's protocols, directly or
4957 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004958 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004959 return false;
4960 }
4961 }
4962 // If there are no qualifiers and no interface, we have an 'id'.
4963 return true;
4964 }
Mike Stump1eb44332009-09-09 15:08:12 +00004965 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004966 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4967 E = lhsQID->qual_end(); I != E; ++I) {
4968 ObjCProtocolDecl *lhsProto = *I;
4969 bool match = false;
4970
4971 // when comparing an id<P> on lhs with a static type on rhs,
4972 // see if static class implements all of id's protocols, directly or
4973 // through its super class and categories.
4974 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4975 E = rhsOPT->qual_end(); J != E; ++J) {
4976 ObjCProtocolDecl *rhsProto = *J;
4977 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4978 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4979 match = true;
4980 break;
4981 }
4982 }
Mike Stump1eb44332009-09-09 15:08:12 +00004983 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00004984 // make sure we check the class hierarchy.
4985 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4986 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4987 E = lhsQID->qual_end(); I != E; ++I) {
4988 // when comparing an id<P> on lhs with a static type on rhs,
4989 // see if static class implements all of id's protocols, directly or
4990 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004991 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00004992 match = true;
4993 break;
4994 }
4995 }
4996 }
4997 if (!match)
4998 return false;
4999 }
Mike Stump1eb44332009-09-09 15:08:12 +00005000
Steve Naroff4084c302009-07-23 01:01:38 +00005001 return true;
5002 }
Mike Stump1eb44332009-09-09 15:08:12 +00005003
Steve Naroff4084c302009-07-23 01:01:38 +00005004 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5005 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5006
Mike Stump1eb44332009-09-09 15:08:12 +00005007 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005008 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005009 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005010 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5011 E = lhsOPT->qual_end(); I != E; ++I) {
5012 ObjCProtocolDecl *lhsProto = *I;
5013 bool match = false;
5014
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005015 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005016 // see if static class implements all of id's protocols, directly or
5017 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005018 // First, lhs protocols in the qualifier list must be found, direct
5019 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005020 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5021 E = rhsQID->qual_end(); J != E; ++J) {
5022 ObjCProtocolDecl *rhsProto = *J;
5023 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5024 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5025 match = true;
5026 break;
5027 }
5028 }
5029 if (!match)
5030 return false;
5031 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005032
5033 // Static class's protocols, or its super class or category protocols
5034 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5035 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5036 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5037 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5038 // This is rather dubious but matches gcc's behavior. If lhs has
5039 // no type qualifier and its class has no static protocol(s)
5040 // assume that it is mismatch.
5041 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5042 return false;
5043 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5044 LHSInheritedProtocols.begin(),
5045 E = LHSInheritedProtocols.end(); I != E; ++I) {
5046 bool match = false;
5047 ObjCProtocolDecl *lhsProto = (*I);
5048 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5049 E = rhsQID->qual_end(); J != E; ++J) {
5050 ObjCProtocolDecl *rhsProto = *J;
5051 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5052 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5053 match = true;
5054 break;
5055 }
5056 }
5057 if (!match)
5058 return false;
5059 }
5060 }
Steve Naroff4084c302009-07-23 01:01:38 +00005061 return true;
5062 }
5063 return false;
5064}
5065
Eli Friedman3d815e72008-08-22 00:56:42 +00005066/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005067/// compatible for assignment from RHS to LHS. This handles validation of any
5068/// protocol qualifiers on the LHS or RHS.
5069///
Steve Naroff14108da2009-07-10 23:34:53 +00005070bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5071 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005072 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5073 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5074
Steve Naroffde2e22d2009-07-15 18:40:39 +00005075 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005076 if (LHS->isObjCUnqualifiedIdOrClass() ||
5077 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005078 return true;
5079
John McCallc12c5bb2010-05-15 11:32:37 +00005080 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005081 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5082 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005083 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005084
5085 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5086 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5087 QualType(RHSOPT,0));
5088
John McCallc12c5bb2010-05-15 11:32:37 +00005089 // If we have 2 user-defined types, fall into that path.
5090 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005091 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005092
Steve Naroff4084c302009-07-23 01:01:38 +00005093 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005094}
5095
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005096/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005097/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005098/// arguments in block literals. When passed as arguments, passing 'A*' where
5099/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5100/// not OK. For the return type, the opposite is not OK.
5101bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5102 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005103 const ObjCObjectPointerType *RHSOPT,
5104 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005105 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005106 return true;
5107
5108 if (LHSOPT->isObjCBuiltinType()) {
5109 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5110 }
5111
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005112 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005113 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5114 QualType(RHSOPT,0),
5115 false);
5116
5117 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5118 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5119 if (LHS && RHS) { // We have 2 user-defined types.
5120 if (LHS != RHS) {
5121 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005122 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005123 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005124 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005125 }
5126 else
5127 return true;
5128 }
5129 return false;
5130}
5131
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005132/// getIntersectionOfProtocols - This routine finds the intersection of set
5133/// of protocols inherited from two distinct objective-c pointer objects.
5134/// It is used to build composite qualifier list of the composite type of
5135/// the conditional expression involving two objective-c pointer objects.
5136static
5137void getIntersectionOfProtocols(ASTContext &Context,
5138 const ObjCObjectPointerType *LHSOPT,
5139 const ObjCObjectPointerType *RHSOPT,
5140 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
5141
John McCallc12c5bb2010-05-15 11:32:37 +00005142 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5143 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5144 assert(LHS->getInterface() && "LHS must have an interface base");
5145 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005146
5147 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5148 unsigned LHSNumProtocols = LHS->getNumProtocols();
5149 if (LHSNumProtocols > 0)
5150 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5151 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005152 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005153 Context.CollectInheritedProtocols(LHS->getInterface(),
5154 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005155 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5156 LHSInheritedProtocols.end());
5157 }
5158
5159 unsigned RHSNumProtocols = RHS->getNumProtocols();
5160 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005161 ObjCProtocolDecl **RHSProtocols =
5162 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005163 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5164 if (InheritedProtocolSet.count(RHSProtocols[i]))
5165 IntersectionOfProtocols.push_back(RHSProtocols[i]);
5166 }
5167 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005168 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005169 Context.CollectInheritedProtocols(RHS->getInterface(),
5170 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005171 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5172 RHSInheritedProtocols.begin(),
5173 E = RHSInheritedProtocols.end(); I != E; ++I)
5174 if (InheritedProtocolSet.count((*I)))
5175 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005176 }
5177}
5178
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005179/// areCommonBaseCompatible - Returns common base class of the two classes if
5180/// one found. Note that this is O'2 algorithm. But it will be called as the
5181/// last type comparison in a ?-exp of ObjC pointer types before a
5182/// warning is issued. So, its invokation is extremely rare.
5183QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005184 const ObjCObjectPointerType *Lptr,
5185 const ObjCObjectPointerType *Rptr) {
5186 const ObjCObjectType *LHS = Lptr->getObjectType();
5187 const ObjCObjectType *RHS = Rptr->getObjectType();
5188 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5189 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005190 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005191 return QualType();
5192
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005193 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005194 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005195 if (canAssignObjCInterfaces(LHS, RHS)) {
John McCallc12c5bb2010-05-15 11:32:37 +00005196 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
5197 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5198
5199 QualType Result = QualType(LHS, 0);
5200 if (!Protocols.empty())
5201 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5202 Result = getObjCObjectPointerType(Result);
5203 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005204 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005205 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005206
5207 return QualType();
5208}
5209
John McCallc12c5bb2010-05-15 11:32:37 +00005210bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5211 const ObjCObjectType *RHS) {
5212 assert(LHS->getInterface() && "LHS is not an interface type");
5213 assert(RHS->getInterface() && "RHS is not an interface type");
5214
Chris Lattner6ac46a42008-04-07 06:51:04 +00005215 // Verify that the base decls are compatible: the RHS must be a subclass of
5216 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005217 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005218 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005219
Chris Lattner6ac46a42008-04-07 06:51:04 +00005220 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5221 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005222 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005223 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005224
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005225 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5226 // more detailed analysis is required.
5227 if (RHS->getNumProtocols() == 0) {
5228 // OK, if LHS is a superclass of RHS *and*
5229 // this superclass is assignment compatible with LHS.
5230 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005231 bool IsSuperClass =
5232 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5233 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005234 // OK if conversion of LHS to SuperClass results in narrowing of types
5235 // ; i.e., SuperClass may implement at least one of the protocols
5236 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5237 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5238 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005239 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005240 // If super class has no protocols, it is not a match.
5241 if (SuperClassInheritedProtocols.empty())
5242 return false;
5243
5244 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5245 LHSPE = LHS->qual_end();
5246 LHSPI != LHSPE; LHSPI++) {
5247 bool SuperImplementsProtocol = false;
5248 ObjCProtocolDecl *LHSProto = (*LHSPI);
5249
5250 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5251 SuperClassInheritedProtocols.begin(),
5252 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5253 ObjCProtocolDecl *SuperClassProto = (*I);
5254 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5255 SuperImplementsProtocol = true;
5256 break;
5257 }
5258 }
5259 if (!SuperImplementsProtocol)
5260 return false;
5261 }
5262 return true;
5263 }
5264 return false;
5265 }
Mike Stump1eb44332009-09-09 15:08:12 +00005266
John McCallc12c5bb2010-05-15 11:32:37 +00005267 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5268 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005269 LHSPI != LHSPE; LHSPI++) {
5270 bool RHSImplementsProtocol = false;
5271
5272 // If the RHS doesn't implement the protocol on the left, the types
5273 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005274 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5275 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005276 RHSPI != RHSPE; RHSPI++) {
5277 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005278 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005279 break;
5280 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005281 }
5282 // FIXME: For better diagnostics, consider passing back the protocol name.
5283 if (!RHSImplementsProtocol)
5284 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005285 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005286 // The RHS implements all protocols listed on the LHS.
5287 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005288}
5289
Steve Naroff389bf462009-02-12 17:52:19 +00005290bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5291 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005292 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5293 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005294
Steve Naroff14108da2009-07-10 23:34:53 +00005295 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005296 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005297
5298 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5299 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005300}
5301
Douglas Gregor569c3162010-08-07 11:51:51 +00005302bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5303 return canAssignObjCInterfaces(
5304 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5305 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5306}
5307
Mike Stump1eb44332009-09-09 15:08:12 +00005308/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005309/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005310/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005311/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005312bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5313 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005314 if (getLangOptions().CPlusPlus)
5315 return hasSameType(LHS, RHS);
5316
Douglas Gregor447234d2010-07-29 15:18:02 +00005317 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005318}
5319
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005320bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5321 return !mergeTypes(LHS, RHS, true).isNull();
5322}
5323
Peter Collingbourne48466752010-10-24 18:30:18 +00005324/// mergeTransparentUnionType - if T is a transparent union type and a member
5325/// of T is compatible with SubType, return the merged type, else return
5326/// QualType()
5327QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5328 bool OfBlockPointer,
5329 bool Unqualified) {
5330 if (const RecordType *UT = T->getAsUnionType()) {
5331 RecordDecl *UD = UT->getDecl();
5332 if (UD->hasAttr<TransparentUnionAttr>()) {
5333 for (RecordDecl::field_iterator it = UD->field_begin(),
5334 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005335 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005336 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5337 if (!MT.isNull())
5338 return MT;
5339 }
5340 }
5341 }
5342
5343 return QualType();
5344}
5345
5346/// mergeFunctionArgumentTypes - merge two types which appear as function
5347/// argument types
5348QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5349 bool OfBlockPointer,
5350 bool Unqualified) {
5351 // GNU extension: two types are compatible if they appear as a function
5352 // argument, one of the types is a transparent union type and the other
5353 // type is compatible with a union member
5354 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5355 Unqualified);
5356 if (!lmerge.isNull())
5357 return lmerge;
5358
5359 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5360 Unqualified);
5361 if (!rmerge.isNull())
5362 return rmerge;
5363
5364 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5365}
5366
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005367QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005368 bool OfBlockPointer,
5369 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005370 const FunctionType *lbase = lhs->getAs<FunctionType>();
5371 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005372 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5373 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005374 bool allLTypes = true;
5375 bool allRTypes = true;
5376
5377 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005378 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005379 if (OfBlockPointer) {
5380 QualType RHS = rbase->getResultType();
5381 QualType LHS = lbase->getResultType();
5382 bool UnqualifiedResult = Unqualified;
5383 if (!UnqualifiedResult)
5384 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005385 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005386 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005387 else
John McCall8cc246c2010-12-15 01:06:38 +00005388 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5389 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005390 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005391
5392 if (Unqualified)
5393 retType = retType.getUnqualifiedType();
5394
5395 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5396 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5397 if (Unqualified) {
5398 LRetType = LRetType.getUnqualifiedType();
5399 RRetType = RRetType.getUnqualifiedType();
5400 }
5401
5402 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005403 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005404 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005405 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005406
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005407 // FIXME: double check this
5408 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5409 // rbase->getRegParmAttr() != 0 &&
5410 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005411 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5412 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005413
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005414 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005415 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005416 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005417
John McCall8cc246c2010-12-15 01:06:38 +00005418 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005419 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5420 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005421 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5422 return QualType();
5423
5424 // It's noreturn if either type is.
5425 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5426 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5427 if (NoReturn != lbaseInfo.getNoReturn())
5428 allLTypes = false;
5429 if (NoReturn != rbaseInfo.getNoReturn())
5430 allRTypes = false;
5431
5432 FunctionType::ExtInfo einfo(NoReturn,
Eli Friedmana49218e2011-04-09 08:18:08 +00005433 lbaseInfo.getHasRegParm(),
John McCall8cc246c2010-12-15 01:06:38 +00005434 lbaseInfo.getRegParm(),
5435 lbaseInfo.getCC());
John McCalle23cf432010-12-14 08:05:40 +00005436
Eli Friedman3d815e72008-08-22 00:56:42 +00005437 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005438 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5439 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005440 unsigned lproto_nargs = lproto->getNumArgs();
5441 unsigned rproto_nargs = rproto->getNumArgs();
5442
5443 // Compatible functions must have the same number of arguments
5444 if (lproto_nargs != rproto_nargs)
5445 return QualType();
5446
5447 // Variadic and non-variadic functions aren't compatible
5448 if (lproto->isVariadic() != rproto->isVariadic())
5449 return QualType();
5450
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005451 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5452 return QualType();
5453
Eli Friedman3d815e72008-08-22 00:56:42 +00005454 // Check argument compatibility
5455 llvm::SmallVector<QualType, 10> types;
5456 for (unsigned i = 0; i < lproto_nargs; i++) {
5457 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5458 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005459 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5460 OfBlockPointer,
5461 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005462 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005463
5464 if (Unqualified)
5465 argtype = argtype.getUnqualifiedType();
5466
Eli Friedman3d815e72008-08-22 00:56:42 +00005467 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005468 if (Unqualified) {
5469 largtype = largtype.getUnqualifiedType();
5470 rargtype = rargtype.getUnqualifiedType();
5471 }
5472
Chris Lattner61710852008-10-05 17:34:18 +00005473 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5474 allLTypes = false;
5475 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5476 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005477 }
5478 if (allLTypes) return lhs;
5479 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005480
5481 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5482 EPI.ExtInfo = einfo;
5483 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005484 }
5485
5486 if (lproto) allRTypes = false;
5487 if (rproto) allLTypes = false;
5488
Douglas Gregor72564e72009-02-26 23:50:07 +00005489 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005490 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005491 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005492 if (proto->isVariadic()) return QualType();
5493 // Check that the types are compatible with the types that
5494 // would result from default argument promotions (C99 6.7.5.3p15).
5495 // The only types actually affected are promotable integer
5496 // types and floats, which would be passed as a different
5497 // type depending on whether the prototype is visible.
5498 unsigned proto_nargs = proto->getNumArgs();
5499 for (unsigned i = 0; i < proto_nargs; ++i) {
5500 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005501
5502 // Look at the promotion type of enum types, since that is the type used
5503 // to pass enum values.
5504 if (const EnumType *Enum = argTy->getAs<EnumType>())
5505 argTy = Enum->getDecl()->getPromotionType();
5506
Eli Friedman3d815e72008-08-22 00:56:42 +00005507 if (argTy->isPromotableIntegerType() ||
5508 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5509 return QualType();
5510 }
5511
5512 if (allLTypes) return lhs;
5513 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005514
5515 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5516 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005517 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005518 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005519 }
5520
5521 if (allLTypes) return lhs;
5522 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005523 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005524}
5525
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005526QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005527 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005528 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005529 // C++ [expr]: If an expression initially has the type "reference to T", the
5530 // type is adjusted to "T" prior to any further analysis, the expression
5531 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005532 // expression is an lvalue unless the reference is an rvalue reference and
5533 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005534 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5535 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005536
5537 if (Unqualified) {
5538 LHS = LHS.getUnqualifiedType();
5539 RHS = RHS.getUnqualifiedType();
5540 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005541
Eli Friedman3d815e72008-08-22 00:56:42 +00005542 QualType LHSCan = getCanonicalType(LHS),
5543 RHSCan = getCanonicalType(RHS);
5544
5545 // If two types are identical, they are compatible.
5546 if (LHSCan == RHSCan)
5547 return LHS;
5548
John McCall0953e762009-09-24 19:53:00 +00005549 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005550 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5551 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005552 if (LQuals != RQuals) {
5553 // If any of these qualifiers are different, we have a type
5554 // mismatch.
5555 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5556 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5557 return QualType();
5558
5559 // Exactly one GC qualifier difference is allowed: __strong is
5560 // okay if the other type has no GC qualifier but is an Objective
5561 // C object pointer (i.e. implicitly strong by default). We fix
5562 // this by pretending that the unqualified type was actually
5563 // qualified __strong.
5564 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5565 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5566 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5567
5568 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5569 return QualType();
5570
5571 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5572 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5573 }
5574 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5575 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5576 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005577 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005578 }
5579
5580 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005581
Eli Friedman852d63b2009-06-01 01:22:52 +00005582 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5583 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005584
Chris Lattner1adb8832008-01-14 05:45:46 +00005585 // We want to consider the two function types to be the same for these
5586 // comparisons, just force one to the other.
5587 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5588 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005589
5590 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005591 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5592 LHSClass = Type::ConstantArray;
5593 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5594 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005595
John McCallc12c5bb2010-05-15 11:32:37 +00005596 // ObjCInterfaces are just specialized ObjCObjects.
5597 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5598 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5599
Nate Begeman213541a2008-04-18 23:10:10 +00005600 // Canonicalize ExtVector -> Vector.
5601 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5602 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005603
Chris Lattnera36a61f2008-04-07 05:43:21 +00005604 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005605 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005606 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005607 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005608 // Compatibility is based on the underlying type, not the promotion
5609 // type.
John McCall183700f2009-09-21 23:43:11 +00005610 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005611 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5612 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005613 }
John McCall183700f2009-09-21 23:43:11 +00005614 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005615 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5616 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005617 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005618
Eli Friedman3d815e72008-08-22 00:56:42 +00005619 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005620 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005621
Steve Naroff4a746782008-01-09 22:43:08 +00005622 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005623 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005624#define TYPE(Class, Base)
5625#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005626#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005627#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5628#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5629#include "clang/AST/TypeNodes.def"
5630 assert(false && "Non-canonical and dependent types shouldn't get here");
5631 return QualType();
5632
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005633 case Type::LValueReference:
5634 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005635 case Type::MemberPointer:
5636 assert(false && "C++ should never be in mergeTypes");
5637 return QualType();
5638
John McCallc12c5bb2010-05-15 11:32:37 +00005639 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005640 case Type::IncompleteArray:
5641 case Type::VariableArray:
5642 case Type::FunctionProto:
5643 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00005644 assert(false && "Types are eliminated above");
5645 return QualType();
5646
Chris Lattner1adb8832008-01-14 05:45:46 +00005647 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005648 {
5649 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005650 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5651 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005652 if (Unqualified) {
5653 LHSPointee = LHSPointee.getUnqualifiedType();
5654 RHSPointee = RHSPointee.getUnqualifiedType();
5655 }
5656 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5657 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005658 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005659 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005660 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005661 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005662 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005663 return getPointerType(ResultType);
5664 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005665 case Type::BlockPointer:
5666 {
5667 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005668 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5669 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005670 if (Unqualified) {
5671 LHSPointee = LHSPointee.getUnqualifiedType();
5672 RHSPointee = RHSPointee.getUnqualifiedType();
5673 }
5674 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5675 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005676 if (ResultType.isNull()) return QualType();
5677 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5678 return LHS;
5679 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5680 return RHS;
5681 return getBlockPointerType(ResultType);
5682 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005683 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005684 {
5685 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5686 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5687 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5688 return QualType();
5689
5690 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5691 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005692 if (Unqualified) {
5693 LHSElem = LHSElem.getUnqualifiedType();
5694 RHSElem = RHSElem.getUnqualifiedType();
5695 }
5696
5697 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005698 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005699 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5700 return LHS;
5701 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5702 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005703 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5704 ArrayType::ArraySizeModifier(), 0);
5705 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5706 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005707 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5708 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005709 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5710 return LHS;
5711 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5712 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005713 if (LVAT) {
5714 // FIXME: This isn't correct! But tricky to implement because
5715 // the array's size has to be the size of LHS, but the type
5716 // has to be different.
5717 return LHS;
5718 }
5719 if (RVAT) {
5720 // FIXME: This isn't correct! But tricky to implement because
5721 // the array's size has to be the size of RHS, but the type
5722 // has to be different.
5723 return RHS;
5724 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005725 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5726 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005727 return getIncompleteArrayType(ResultType,
5728 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005729 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005730 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005731 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005732 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005733 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005734 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005735 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005736 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005737 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005738 case Type::Complex:
5739 // Distinct complex types are incompatible.
5740 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005741 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005742 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005743 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5744 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005745 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005746 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005747 case Type::ObjCObject: {
5748 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005749 // FIXME: This should be type compatibility, e.g. whether
5750 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005751 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5752 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5753 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005754 return LHS;
5755
Eli Friedman3d815e72008-08-22 00:56:42 +00005756 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005757 }
Steve Naroff14108da2009-07-10 23:34:53 +00005758 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005759 if (OfBlockPointer) {
5760 if (canAssignObjCInterfacesInBlockPointer(
5761 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005762 RHS->getAs<ObjCObjectPointerType>(),
5763 BlockReturnType))
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005764 return LHS;
5765 return QualType();
5766 }
John McCall183700f2009-09-21 23:43:11 +00005767 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5768 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005769 return LHS;
5770
Steve Naroffbc76dd02008-12-10 22:14:21 +00005771 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005772 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005773 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005774
5775 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005776}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005777
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005778/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5779/// 'RHS' attributes and returns the merged version; including for function
5780/// return types.
5781QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5782 QualType LHSCan = getCanonicalType(LHS),
5783 RHSCan = getCanonicalType(RHS);
5784 // If two types are identical, they are compatible.
5785 if (LHSCan == RHSCan)
5786 return LHS;
5787 if (RHSCan->isFunctionType()) {
5788 if (!LHSCan->isFunctionType())
5789 return QualType();
5790 QualType OldReturnType =
5791 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5792 QualType NewReturnType =
5793 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5794 QualType ResReturnType =
5795 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5796 if (ResReturnType.isNull())
5797 return QualType();
5798 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5799 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5800 // In either case, use OldReturnType to build the new function type.
5801 const FunctionType *F = LHS->getAs<FunctionType>();
5802 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00005803 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5804 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005805 QualType ResultType
5806 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005807 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005808 return ResultType;
5809 }
5810 }
5811 return QualType();
5812 }
5813
5814 // If the qualifiers are different, the types can still be merged.
5815 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5816 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5817 if (LQuals != RQuals) {
5818 // If any of these qualifiers are different, we have a type mismatch.
5819 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5820 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5821 return QualType();
5822
5823 // Exactly one GC qualifier difference is allowed: __strong is
5824 // okay if the other type has no GC qualifier but is an Objective
5825 // C object pointer (i.e. implicitly strong by default). We fix
5826 // this by pretending that the unqualified type was actually
5827 // qualified __strong.
5828 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5829 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5830 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5831
5832 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5833 return QualType();
5834
5835 if (GC_L == Qualifiers::Strong)
5836 return LHS;
5837 if (GC_R == Qualifiers::Strong)
5838 return RHS;
5839 return QualType();
5840 }
5841
5842 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5843 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5844 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5845 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5846 if (ResQT == LHSBaseQT)
5847 return LHS;
5848 if (ResQT == RHSBaseQT)
5849 return RHS;
5850 }
5851 return QualType();
5852}
5853
Chris Lattner5426bf62008-04-07 07:01:58 +00005854//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005855// Integer Predicates
5856//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005857
Jay Foad4ba2a172011-01-12 09:06:06 +00005858unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00005859 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005860 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005861 if (T->isBooleanType())
5862 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00005863 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005864 return (unsigned)getTypeSize(T);
5865}
5866
5867QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005868 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005869
5870 // Turn <4 x signed int> -> <4 x unsigned int>
5871 if (const VectorType *VTy = T->getAs<VectorType>())
5872 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00005873 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005874
5875 // For enums, we return the unsigned version of the base type.
5876 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005877 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005878
5879 const BuiltinType *BTy = T->getAs<BuiltinType>();
5880 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005881 switch (BTy->getKind()) {
5882 case BuiltinType::Char_S:
5883 case BuiltinType::SChar:
5884 return UnsignedCharTy;
5885 case BuiltinType::Short:
5886 return UnsignedShortTy;
5887 case BuiltinType::Int:
5888 return UnsignedIntTy;
5889 case BuiltinType::Long:
5890 return UnsignedLongTy;
5891 case BuiltinType::LongLong:
5892 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005893 case BuiltinType::Int128:
5894 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005895 default:
5896 assert(0 && "Unexpected signed integer type");
5897 return QualType();
5898 }
5899}
5900
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005901ASTMutationListener::~ASTMutationListener() { }
5902
Chris Lattner86df27b2009-06-14 00:45:47 +00005903
5904//===----------------------------------------------------------------------===//
5905// Builtin Type Computation
5906//===----------------------------------------------------------------------===//
5907
5908/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00005909/// pointer over the consumed characters. This returns the resultant type. If
5910/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5911/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5912/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00005913///
5914/// RequiresICE is filled in on return to indicate whether the value is required
5915/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00005916static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005917 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00005918 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00005919 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005920 // Modifiers.
5921 int HowLong = 0;
5922 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00005923 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005924
Chris Lattner33daae62010-10-01 22:42:38 +00005925 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00005926 bool Done = false;
5927 while (!Done) {
5928 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005929 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005930 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00005931 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005932 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005933 case 'S':
5934 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5935 assert(!Signed && "Can't use 'S' modifier multiple times!");
5936 Signed = true;
5937 break;
5938 case 'U':
5939 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5940 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5941 Unsigned = true;
5942 break;
5943 case 'L':
5944 assert(HowLong <= 2 && "Can't have LLLL modifier");
5945 ++HowLong;
5946 break;
5947 }
5948 }
5949
5950 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005951
Chris Lattner86df27b2009-06-14 00:45:47 +00005952 // Read the base type.
5953 switch (*Str++) {
5954 default: assert(0 && "Unknown builtin type letter!");
5955 case 'v':
5956 assert(HowLong == 0 && !Signed && !Unsigned &&
5957 "Bad modifiers used with 'v'!");
5958 Type = Context.VoidTy;
5959 break;
5960 case 'f':
5961 assert(HowLong == 0 && !Signed && !Unsigned &&
5962 "Bad modifiers used with 'f'!");
5963 Type = Context.FloatTy;
5964 break;
5965 case 'd':
5966 assert(HowLong < 2 && !Signed && !Unsigned &&
5967 "Bad modifiers used with 'd'!");
5968 if (HowLong)
5969 Type = Context.LongDoubleTy;
5970 else
5971 Type = Context.DoubleTy;
5972 break;
5973 case 's':
5974 assert(HowLong == 0 && "Bad modifiers used with 's'!");
5975 if (Unsigned)
5976 Type = Context.UnsignedShortTy;
5977 else
5978 Type = Context.ShortTy;
5979 break;
5980 case 'i':
5981 if (HowLong == 3)
5982 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5983 else if (HowLong == 2)
5984 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5985 else if (HowLong == 1)
5986 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5987 else
5988 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5989 break;
5990 case 'c':
5991 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5992 if (Signed)
5993 Type = Context.SignedCharTy;
5994 else if (Unsigned)
5995 Type = Context.UnsignedCharTy;
5996 else
5997 Type = Context.CharTy;
5998 break;
5999 case 'b': // boolean
6000 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6001 Type = Context.BoolTy;
6002 break;
6003 case 'z': // size_t.
6004 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6005 Type = Context.getSizeType();
6006 break;
6007 case 'F':
6008 Type = Context.getCFConstantStringType();
6009 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006010 case 'G':
6011 Type = Context.getObjCIdType();
6012 break;
6013 case 'H':
6014 Type = Context.getObjCSelType();
6015 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006016 case 'a':
6017 Type = Context.getBuiltinVaListType();
6018 assert(!Type.isNull() && "builtin va list type not initialized!");
6019 break;
6020 case 'A':
6021 // This is a "reference" to a va_list; however, what exactly
6022 // this means depends on how va_list is defined. There are two
6023 // different kinds of va_list: ones passed by value, and ones
6024 // passed by reference. An example of a by-value va_list is
6025 // x86, where va_list is a char*. An example of by-ref va_list
6026 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6027 // we want this argument to be a char*&; for x86-64, we want
6028 // it to be a __va_list_tag*.
6029 Type = Context.getBuiltinVaListType();
6030 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006031 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006032 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006033 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006034 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006035 break;
6036 case 'V': {
6037 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006038 unsigned NumElements = strtoul(Str, &End, 10);
6039 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006040 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006041
Chris Lattner14e0e742010-10-01 22:53:11 +00006042 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6043 RequiresICE, false);
6044 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006045
6046 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006047 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006048 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006049 break;
6050 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006051 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006052 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6053 false);
6054 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006055 Type = Context.getComplexType(ElementType);
6056 break;
6057 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006058 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006059 Type = Context.getFILEType();
6060 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006061 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006062 return QualType();
6063 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006064 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006065 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006066 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006067 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006068 else
6069 Type = Context.getjmp_bufType();
6070
Mike Stumpfd612db2009-07-28 23:47:15 +00006071 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006072 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006073 return QualType();
6074 }
6075 break;
Mike Stump782fa302009-07-28 02:25:19 +00006076 }
Mike Stump1eb44332009-09-09 15:08:12 +00006077
Chris Lattner33daae62010-10-01 22:42:38 +00006078 // If there are modifiers and if we're allowed to parse them, go for it.
6079 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006080 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006081 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006082 default: Done = true; --Str; break;
6083 case '*':
6084 case '&': {
6085 // Both pointers and references can have their pointee types
6086 // qualified with an address space.
6087 char *End;
6088 unsigned AddrSpace = strtoul(Str, &End, 10);
6089 if (End != Str && AddrSpace != 0) {
6090 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6091 Str = End;
6092 }
6093 if (c == '*')
6094 Type = Context.getPointerType(Type);
6095 else
6096 Type = Context.getLValueReferenceType(Type);
6097 break;
6098 }
6099 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6100 case 'C':
6101 Type = Type.withConst();
6102 break;
6103 case 'D':
6104 Type = Context.getVolatileType(Type);
6105 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006106 }
6107 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006108
Chris Lattner14e0e742010-10-01 22:53:11 +00006109 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006110 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006111
Chris Lattner86df27b2009-06-14 00:45:47 +00006112 return Type;
6113}
6114
6115/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006116QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006117 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006118 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006119 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006120
Chris Lattner86df27b2009-06-14 00:45:47 +00006121 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006122
Chris Lattner14e0e742010-10-01 22:53:11 +00006123 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006124 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006125 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6126 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006127 if (Error != GE_None)
6128 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006129
6130 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6131
Chris Lattner86df27b2009-06-14 00:45:47 +00006132 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006133 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006134 if (Error != GE_None)
6135 return QualType();
6136
Chris Lattner14e0e742010-10-01 22:53:11 +00006137 // If this argument is required to be an IntegerConstantExpression and the
6138 // caller cares, fill in the bitmask we return.
6139 if (RequiresICE && IntegerConstantArgs)
6140 *IntegerConstantArgs |= 1 << ArgTypes.size();
6141
Chris Lattner86df27b2009-06-14 00:45:47 +00006142 // Do array -> pointer decay. The builtin should use the decayed type.
6143 if (Ty->isArrayType())
6144 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006145
Chris Lattner86df27b2009-06-14 00:45:47 +00006146 ArgTypes.push_back(Ty);
6147 }
6148
6149 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6150 "'.' should only occur at end of builtin type list!");
6151
John McCall00ccbef2010-12-21 00:44:39 +00006152 FunctionType::ExtInfo EI;
6153 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6154
6155 bool Variadic = (TypeStr[0] == '.');
6156
6157 // We really shouldn't be making a no-proto type here, especially in C++.
6158 if (ArgTypes.empty() && Variadic)
6159 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006160
John McCalle23cf432010-12-14 08:05:40 +00006161 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006162 EPI.ExtInfo = EI;
6163 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006164
6165 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006166}
Eli Friedmana95d7572009-08-19 07:44:53 +00006167
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006168GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6169 GVALinkage External = GVA_StrongExternal;
6170
6171 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006172 switch (L) {
6173 case NoLinkage:
6174 case InternalLinkage:
6175 case UniqueExternalLinkage:
6176 return GVA_Internal;
6177
6178 case ExternalLinkage:
6179 switch (FD->getTemplateSpecializationKind()) {
6180 case TSK_Undeclared:
6181 case TSK_ExplicitSpecialization:
6182 External = GVA_StrongExternal;
6183 break;
6184
6185 case TSK_ExplicitInstantiationDefinition:
6186 return GVA_ExplicitTemplateInstantiation;
6187
6188 case TSK_ExplicitInstantiationDeclaration:
6189 case TSK_ImplicitInstantiation:
6190 External = GVA_TemplateInstantiation;
6191 break;
6192 }
6193 }
6194
6195 if (!FD->isInlined())
6196 return External;
6197
6198 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6199 // GNU or C99 inline semantics. Determine whether this symbol should be
6200 // externally visible.
6201 if (FD->isInlineDefinitionExternallyVisible())
6202 return External;
6203
6204 // C99 inline semantics, where the symbol is not externally visible.
6205 return GVA_C99Inline;
6206 }
6207
6208 // C++0x [temp.explicit]p9:
6209 // [ Note: The intent is that an inline function that is the subject of
6210 // an explicit instantiation declaration will still be implicitly
6211 // instantiated when used so that the body can be considered for
6212 // inlining, but that no out-of-line copy of the inline function would be
6213 // generated in the translation unit. -- end note ]
6214 if (FD->getTemplateSpecializationKind()
6215 == TSK_ExplicitInstantiationDeclaration)
6216 return GVA_C99Inline;
6217
6218 return GVA_CXXInline;
6219}
6220
6221GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6222 // If this is a static data member, compute the kind of template
6223 // specialization. Otherwise, this variable is not part of a
6224 // template.
6225 TemplateSpecializationKind TSK = TSK_Undeclared;
6226 if (VD->isStaticDataMember())
6227 TSK = VD->getTemplateSpecializationKind();
6228
6229 Linkage L = VD->getLinkage();
6230 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6231 VD->getType()->getLinkage() == UniqueExternalLinkage)
6232 L = UniqueExternalLinkage;
6233
6234 switch (L) {
6235 case NoLinkage:
6236 case InternalLinkage:
6237 case UniqueExternalLinkage:
6238 return GVA_Internal;
6239
6240 case ExternalLinkage:
6241 switch (TSK) {
6242 case TSK_Undeclared:
6243 case TSK_ExplicitSpecialization:
6244 return GVA_StrongExternal;
6245
6246 case TSK_ExplicitInstantiationDeclaration:
6247 llvm_unreachable("Variable should not be instantiated");
6248 // Fall through to treat this like any other instantiation.
6249
6250 case TSK_ExplicitInstantiationDefinition:
6251 return GVA_ExplicitTemplateInstantiation;
6252
6253 case TSK_ImplicitInstantiation:
6254 return GVA_TemplateInstantiation;
6255 }
6256 }
6257
6258 return GVA_StrongExternal;
6259}
6260
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006261bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006262 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6263 if (!VD->isFileVarDecl())
6264 return false;
6265 } else if (!isa<FunctionDecl>(D))
6266 return false;
6267
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006268 // Weak references don't produce any output by themselves.
6269 if (D->hasAttr<WeakRefAttr>())
6270 return false;
6271
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006272 // Aliases and used decls are required.
6273 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6274 return true;
6275
6276 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6277 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006278 if (!FD->doesThisDeclarationHaveABody())
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006279 return false;
6280
6281 // Constructors and destructors are required.
6282 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6283 return true;
6284
6285 // The key function for a class is required.
6286 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6287 const CXXRecordDecl *RD = MD->getParent();
6288 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6289 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6290 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6291 return true;
6292 }
6293 }
6294
6295 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6296
6297 // static, static inline, always_inline, and extern inline functions can
6298 // always be deferred. Normal inline functions can be deferred in C99/C++.
6299 // Implicit template instantiations can also be deferred in C++.
6300 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6301 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6302 return false;
6303 return true;
6304 }
6305
6306 const VarDecl *VD = cast<VarDecl>(D);
6307 assert(VD->isFileVarDecl() && "Expected file scoped var");
6308
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006309 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6310 return false;
6311
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006312 // Structs that have non-trivial constructors or destructors are required.
6313
6314 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006315 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006316 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6317 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006318 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6319 RD->hasTrivialCopyConstructor() &&
6320 RD->hasTrivialMoveConstructor() &&
6321 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006322 return true;
6323 }
6324 }
6325
6326 GVALinkage L = GetGVALinkageForVariable(VD);
6327 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6328 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6329 return false;
6330 }
6331
6332 return true;
6333}
Charles Davis071cc7d2010-08-16 03:33:14 +00006334
Charles Davisee743f92010-11-09 18:04:24 +00006335CallingConv ASTContext::getDefaultMethodCallConv() {
6336 // Pass through to the C++ ABI object
6337 return ABI->getDefaultMethodCallConv();
6338}
6339
Jay Foad4ba2a172011-01-12 09:06:06 +00006340bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006341 // Pass through to the C++ ABI object
6342 return ABI->isNearlyEmpty(RD);
6343}
6344
Peter Collingbourne14110472011-01-13 18:57:25 +00006345MangleContext *ASTContext::createMangleContext() {
6346 switch (Target.getCXXABI()) {
6347 case CXXABI_ARM:
6348 case CXXABI_Itanium:
6349 return createItaniumMangleContext(*this, getDiagnostics());
6350 case CXXABI_Microsoft:
6351 return createMicrosoftMangleContext(*this, getDiagnostics());
6352 }
6353 assert(0 && "Unsupported ABI");
6354 return 0;
6355}
6356
Charles Davis071cc7d2010-08-16 03:33:14 +00006357CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006358
6359size_t ASTContext::getSideTableAllocatedMemory() const {
6360 size_t bytes = 0;
6361 bytes += ASTRecordLayouts.getMemorySize();
6362 bytes += ObjCLayouts.getMemorySize();
6363 bytes += KeyFunctions.getMemorySize();
6364 bytes += ObjCImpls.getMemorySize();
6365 bytes += BlockVarCopyInits.getMemorySize();
6366 bytes += DeclAttrs.getMemorySize();
6367 bytes += InstantiatedFromStaticDataMember.getMemorySize();
6368 bytes += InstantiatedFromUsingDecl.getMemorySize();
6369 bytes += InstantiatedFromUsingShadowDecl.getMemorySize();
6370 bytes += InstantiatedFromUnnamedFieldDecl.getMemorySize();
6371 return bytes;
6372}
6373