blob: 15f85ba9c48279b03750a52c6a5fe44520950401 [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000035#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000036
Chris Lattnerddc135e2006-11-10 06:34:16 +000037using namespace clang;
38
Douglas Gregor9672f922010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Steve Naroff0af91202007-04-27 21:51:21 +000052enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000053 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000054};
55
Douglas Gregor7dbfb462010-06-16 21:09:37 +000056void
57ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
58 TemplateTemplateParmDecl *Parm) {
59 ID.AddInteger(Parm->getDepth());
60 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +000061 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000062
63 TemplateParameterList *Params = Parm->getTemplateParameters();
64 ID.AddInteger(Params->size());
65 for (TemplateParameterList::const_iterator P = Params->begin(),
66 PEnd = Params->end();
67 P != PEnd; ++P) {
68 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
69 ID.AddInteger(0);
70 ID.AddBoolean(TTP->isParameterPack());
71 continue;
72 }
73
74 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
75 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +000076 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +000077 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +000081 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
82 QualType T = NTTP->getExpansionType(I);
83 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
84 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +000085 } else
86 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +000087 continue;
88 }
89
90 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
91 ID.AddInteger(2);
92 Profile(ID, TTP);
93 }
94}
95
96TemplateTemplateParmDecl *
97ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000098 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000099 // Check if we already have a canonical template template parameter.
100 llvm::FoldingSetNodeID ID;
101 CanonicalTemplateTemplateParm::Profile(ID, TTP);
102 void *InsertPos = 0;
103 CanonicalTemplateTemplateParm *Canonical
104 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
105 if (Canonical)
106 return Canonical->getParam();
107
108 // Build a canonical template parameter list.
109 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000110 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000111 CanonParams.reserve(Params->size());
112 for (TemplateParameterList::const_iterator P = Params->begin(),
113 PEnd = Params->end();
114 P != PEnd; ++P) {
115 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
116 CanonParams.push_back(
117 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000118 SourceLocation(),
119 SourceLocation(),
120 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000121 TTP->getIndex(), 0, false,
122 TTP->isParameterPack()));
123 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000124 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
125 QualType T = getCanonicalType(NTTP->getType());
126 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
127 NonTypeTemplateParmDecl *Param;
128 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000129 SmallVector<QualType, 2> ExpandedTypes;
130 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000131 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
132 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
133 ExpandedTInfos.push_back(
134 getTrivialTypeSourceInfo(ExpandedTypes.back()));
135 }
136
137 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000138 SourceLocation(),
139 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000140 NTTP->getDepth(),
141 NTTP->getPosition(), 0,
142 T,
143 TInfo,
144 ExpandedTypes.data(),
145 ExpandedTypes.size(),
146 ExpandedTInfos.data());
147 } else {
148 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000149 SourceLocation(),
150 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000151 NTTP->getDepth(),
152 NTTP->getPosition(), 0,
153 T,
154 NTTP->isParameterPack(),
155 TInfo);
156 }
157 CanonParams.push_back(Param);
158
159 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000160 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
161 cast<TemplateTemplateParmDecl>(*P)));
162 }
163
164 TemplateTemplateParmDecl *CanonTTP
165 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
166 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000167 TTP->getPosition(),
168 TTP->isParameterPack(),
169 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000170 TemplateParameterList::Create(*this, SourceLocation(),
171 SourceLocation(),
172 CanonParams.data(),
173 CanonParams.size(),
174 SourceLocation()));
175
176 // Get the new insert position for the node we care about.
177 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
178 assert(Canonical == 0 && "Shouldn't be in the map!");
179 (void)Canonical;
180
181 // Create the canonical template template parameter entry.
182 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
183 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
184 return CanonTTP;
185}
186
Charles Davis53c59df2010-08-16 03:33:14 +0000187CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000188 if (!LangOpts.CPlusPlus) return 0;
189
Charles Davis6bcb07a2010-08-19 02:18:14 +0000190 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000191 case CXXABI_ARM:
192 return CreateARMCXXABI(*this);
193 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000194 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000195 case CXXABI_Microsoft:
196 return CreateMicrosoftCXXABI(*this);
197 }
David Blaikie8a40f702012-01-17 06:56:22 +0000198 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000199}
200
Douglas Gregore8bbc122011-09-02 00:18:52 +0000201static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000202 const LangOptions &LOpts) {
203 if (LOpts.FakeAddressSpaceMap) {
204 // The fake address space map must have a distinct entry for each
205 // language-specific address space.
206 static const unsigned FakeAddrSpaceMap[] = {
207 1, // opencl_global
208 2, // opencl_local
209 3 // opencl_constant
210 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000211 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000212 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000213 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000214 }
215}
216
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000217ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000218 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000219 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000220 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000221 unsigned size_reserve,
222 bool DelayInitialization)
223 : FunctionProtoTypes(this_()),
224 TemplateSpecializationTypes(this_()),
225 DependentTemplateSpecializationTypes(this_()),
226 SubstTemplateTemplateParmPacks(this_()),
227 GlobalNestedNameSpecifier(0),
228 Int128Decl(0), UInt128Decl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000229 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000230 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000231 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000232 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
233 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
234 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000235 NullTypeSourceInfo(QualType()),
236 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000237 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000238 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000239 Idents(idents), Selectors(sels),
240 BuiltinInfo(builtins),
241 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000242 ExternalSource(0), Listener(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000243 LastSDM(0, 0),
244 UniqueBlockByRefTypeID(0)
245{
Mike Stump11289f42009-09-09 15:08:12 +0000246 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000247 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000248
249 if (!DelayInitialization) {
250 assert(t && "No target supplied for ASTContext initialization");
251 InitBuiltinTypes(*t);
252 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000253}
254
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000255ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000256 // Release the DenseMaps associated with DeclContext objects.
257 // FIXME: Is this the ideal solution?
258 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000259
Douglas Gregor5b11d492010-07-25 17:53:33 +0000260 // Call all of the deallocation functions.
261 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
262 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000263
Ted Kremenek076baeb2010-06-08 23:00:58 +0000264 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000265 // because they can contain DenseMaps.
266 for (llvm::DenseMap<const ObjCContainerDecl*,
267 const ASTRecordLayout*>::iterator
268 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
269 // Increment in loop to prevent using deallocated memory.
270 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
271 R->Destroy(*this);
272
Ted Kremenek076baeb2010-06-08 23:00:58 +0000273 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
274 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
275 // Increment in loop to prevent using deallocated memory.
276 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
277 R->Destroy(*this);
278 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000279
280 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
281 AEnd = DeclAttrs.end();
282 A != AEnd; ++A)
283 A->second->~AttrVec();
284}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000285
Douglas Gregor1a809332010-05-23 18:26:36 +0000286void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
287 Deallocations.push_back(std::make_pair(Callback, Data));
288}
289
Mike Stump11289f42009-09-09 15:08:12 +0000290void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000291ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000292 ExternalSource.reset(Source.take());
293}
294
Chris Lattner4eb445d2007-01-26 01:27:23 +0000295void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000296 llvm::errs() << "\n*** AST Context Stats:\n";
297 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000298
Douglas Gregora30d0462009-05-26 14:40:08 +0000299 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000300#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000301#define ABSTRACT_TYPE(Name, Parent)
302#include "clang/AST/TypeNodes.def"
303 0 // Extra
304 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000305
Chris Lattner4eb445d2007-01-26 01:27:23 +0000306 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
307 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000308 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000309 }
310
Douglas Gregora30d0462009-05-26 14:40:08 +0000311 unsigned Idx = 0;
312 unsigned TotalBytes = 0;
313#define TYPE(Name, Parent) \
314 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000315 llvm::errs() << " " << counts[Idx] << " " << #Name \
316 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000317 TotalBytes += counts[Idx] * sizeof(Name##Type); \
318 ++Idx;
319#define ABSTRACT_TYPE(Name, Parent)
320#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000321
Chandler Carruth3c147a72011-07-04 05:32:14 +0000322 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
323
Douglas Gregor7454c562010-07-02 20:37:36 +0000324 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000325 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
326 << NumImplicitDefaultConstructors
327 << " implicit default constructors created\n";
328 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
329 << NumImplicitCopyConstructors
330 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000331 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000332 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
333 << NumImplicitMoveConstructors
334 << " implicit move constructors created\n";
335 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
336 << NumImplicitCopyAssignmentOperators
337 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000338 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000339 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
340 << NumImplicitMoveAssignmentOperators
341 << " implicit move assignment operators created\n";
342 llvm::errs() << NumImplicitDestructorsDeclared << "/"
343 << NumImplicitDestructors
344 << " implicit destructors created\n";
345
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000346 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000347 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000348 ExternalSource->PrintStats();
349 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000350
Douglas Gregor5b11d492010-07-25 17:53:33 +0000351 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000352}
353
Douglas Gregor801c99d2011-08-12 06:49:56 +0000354TypedefDecl *ASTContext::getInt128Decl() const {
355 if (!Int128Decl) {
356 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
357 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
358 getTranslationUnitDecl(),
359 SourceLocation(),
360 SourceLocation(),
361 &Idents.get("__int128_t"),
362 TInfo);
363 }
364
365 return Int128Decl;
366}
367
368TypedefDecl *ASTContext::getUInt128Decl() const {
369 if (!UInt128Decl) {
370 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
371 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
372 getTranslationUnitDecl(),
373 SourceLocation(),
374 SourceLocation(),
375 &Idents.get("__uint128_t"),
376 TInfo);
377 }
378
379 return UInt128Decl;
380}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000381
John McCall48f2d582009-10-23 23:03:21 +0000382void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000383 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000384 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000385 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000386}
387
Douglas Gregore8bbc122011-09-02 00:18:52 +0000388void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
389 assert((!this->Target || this->Target == &Target) &&
390 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000391 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000392
Douglas Gregore8bbc122011-09-02 00:18:52 +0000393 this->Target = &Target;
394
395 ABI.reset(createCXXABI(Target));
396 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
397
Chris Lattner970e54e2006-11-12 00:37:36 +0000398 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000399 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000400
Chris Lattner970e54e2006-11-12 00:37:36 +0000401 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000402 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000403 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000404 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000405 InitBuiltinType(CharTy, BuiltinType::Char_S);
406 else
407 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000408 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000409 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
410 InitBuiltinType(ShortTy, BuiltinType::Short);
411 InitBuiltinType(IntTy, BuiltinType::Int);
412 InitBuiltinType(LongTy, BuiltinType::Long);
413 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000414
Chris Lattner970e54e2006-11-12 00:37:36 +0000415 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000416 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
417 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
418 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
419 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
420 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000421
Chris Lattner970e54e2006-11-12 00:37:36 +0000422 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000423 InitBuiltinType(FloatTy, BuiltinType::Float);
424 InitBuiltinType(DoubleTy, BuiltinType::Double);
425 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000426
Chris Lattnerf122cef2009-04-30 02:43:43 +0000427 // GNU extension, 128-bit integers.
428 InitBuiltinType(Int128Ty, BuiltinType::Int128);
429 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
430
Chris Lattnerad3467e2010-12-25 23:25:43 +0000431 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000432 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000433 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
434 else // -fshort-wchar makes wchar_t be unsigned.
435 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
436 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000437 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000438
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000439 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
440 InitBuiltinType(Char16Ty, BuiltinType::Char16);
441 else // C99
442 Char16Ty = getFromTargetType(Target.getChar16Type());
443
444 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
445 InitBuiltinType(Char32Ty, BuiltinType::Char32);
446 else // C99
447 Char32Ty = getFromTargetType(Target.getChar32Type());
448
Douglas Gregor4619e432008-12-05 23:32:09 +0000449 // Placeholder type for type-dependent expressions whose type is
450 // completely unknown. No code should ever check a type against
451 // DependentTy and users should never see it; however, it is here to
452 // help diagnose failures to properly check for type-dependent
453 // expressions.
454 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000455
John McCall36e7fe32010-10-12 00:20:44 +0000456 // Placeholder type for functions.
457 InitBuiltinType(OverloadTy, BuiltinType::Overload);
458
John McCall0009fcc2011-04-26 20:42:42 +0000459 // Placeholder type for bound members.
460 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
461
John McCall526ab472011-10-25 17:37:35 +0000462 // Placeholder type for pseudo-objects.
463 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
464
John McCall31996342011-04-07 08:22:57 +0000465 // "any" type; useful for debugger-like clients.
466 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
467
John McCall8a6b59a2011-10-17 18:09:15 +0000468 // Placeholder type for unbridged ARC casts.
469 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
470
Chris Lattner970e54e2006-11-12 00:37:36 +0000471 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000472 FloatComplexTy = getComplexType(FloatTy);
473 DoubleComplexTy = getComplexType(DoubleTy);
474 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000475
Steve Naroff66e9f332007-10-15 14:41:52 +0000476 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000477
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000478 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000479 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
480 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000481 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000482
483 // Builtin type for __objc_yes and __objc_no
484 ObjCBuiltinBoolTy = SignedCharTy;
485
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000486 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000487
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000488 // void * type
489 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000490
491 // nullptr type (C++0x 2.14.7)
492 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000493
494 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
495 InitBuiltinType(HalfTy, BuiltinType::Half);
Chris Lattner970e54e2006-11-12 00:37:36 +0000496}
497
David Blaikie9c902b52011-09-25 23:23:43 +0000498DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000499 return SourceMgr.getDiagnostics();
500}
501
Douglas Gregor561eceb2010-08-30 16:49:28 +0000502AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
503 AttrVec *&Result = DeclAttrs[D];
504 if (!Result) {
505 void *Mem = Allocate(sizeof(AttrVec));
506 Result = new (Mem) AttrVec;
507 }
508
509 return *Result;
510}
511
512/// \brief Erase the attributes corresponding to the given declaration.
513void ASTContext::eraseDeclAttrs(const Decl *D) {
514 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
515 if (Pos != DeclAttrs.end()) {
516 Pos->second->~AttrVec();
517 DeclAttrs.erase(Pos);
518 }
519}
520
Douglas Gregor86d142a2009-10-08 07:24:58 +0000521MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000522ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000523 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000524 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000525 = InstantiatedFromStaticDataMember.find(Var);
526 if (Pos == InstantiatedFromStaticDataMember.end())
527 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000528
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000529 return Pos->second;
530}
531
Mike Stump11289f42009-09-09 15:08:12 +0000532void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000533ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000534 TemplateSpecializationKind TSK,
535 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000536 assert(Inst->isStaticDataMember() && "Not a static data member");
537 assert(Tmpl->isStaticDataMember() && "Not a static data member");
538 assert(!InstantiatedFromStaticDataMember[Inst] &&
539 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000540 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000541 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000542}
543
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000544FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
545 const FunctionDecl *FD){
546 assert(FD && "Specialization is 0");
547 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000548 = ClassScopeSpecializationPattern.find(FD);
549 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000550 return 0;
551
552 return Pos->second;
553}
554
555void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
556 FunctionDecl *Pattern) {
557 assert(FD && "Specialization is 0");
558 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000559 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000560}
561
John McCalle61f2ba2009-11-18 02:36:19 +0000562NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000563ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000564 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000565 = InstantiatedFromUsingDecl.find(UUD);
566 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000567 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000568
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000569 return Pos->second;
570}
571
572void
John McCallb96ec562009-12-04 22:46:56 +0000573ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
574 assert((isa<UsingDecl>(Pattern) ||
575 isa<UnresolvedUsingValueDecl>(Pattern) ||
576 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
577 "pattern decl is not a using decl");
578 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
579 InstantiatedFromUsingDecl[Inst] = Pattern;
580}
581
582UsingShadowDecl *
583ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
584 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
585 = InstantiatedFromUsingShadowDecl.find(Inst);
586 if (Pos == InstantiatedFromUsingShadowDecl.end())
587 return 0;
588
589 return Pos->second;
590}
591
592void
593ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
594 UsingShadowDecl *Pattern) {
595 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
596 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000597}
598
Anders Carlsson5da84842009-09-01 04:26:58 +0000599FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
600 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
601 = InstantiatedFromUnnamedFieldDecl.find(Field);
602 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
603 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000604
Anders Carlsson5da84842009-09-01 04:26:58 +0000605 return Pos->second;
606}
607
608void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
609 FieldDecl *Tmpl) {
610 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
611 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
612 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
613 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000614
Anders Carlsson5da84842009-09-01 04:26:58 +0000615 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
616}
617
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000618bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
619 const FieldDecl *LastFD) const {
620 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000621 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000622}
623
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000624bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
625 const FieldDecl *LastFD) const {
626 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000627 FD->getBitWidthValue(*this) == 0 &&
628 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000629}
630
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000631bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
632 const FieldDecl *LastFD) const {
633 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000634 FD->getBitWidthValue(*this) &&
635 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000636}
637
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000638bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000639 const FieldDecl *LastFD) const {
640 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000641 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000642}
643
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000644bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000645 const FieldDecl *LastFD) const {
646 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000647 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000648}
649
Douglas Gregor832940b2010-03-02 23:58:15 +0000650ASTContext::overridden_cxx_method_iterator
651ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
652 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
653 = OverriddenMethods.find(Method);
654 if (Pos == OverriddenMethods.end())
655 return 0;
656
657 return Pos->second.begin();
658}
659
660ASTContext::overridden_cxx_method_iterator
661ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
662 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
663 = OverriddenMethods.find(Method);
664 if (Pos == OverriddenMethods.end())
665 return 0;
666
667 return Pos->second.end();
668}
669
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000670unsigned
671ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
672 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
673 = OverriddenMethods.find(Method);
674 if (Pos == OverriddenMethods.end())
675 return 0;
676
677 return Pos->second.size();
678}
679
Douglas Gregor832940b2010-03-02 23:58:15 +0000680void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
681 const CXXMethodDecl *Overridden) {
682 OverriddenMethods[Method].push_back(Overridden);
683}
684
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000685void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
686 assert(!Import->NextLocalImport && "Import declaration already in the chain");
687 assert(!Import->isFromASTFile() && "Non-local import declaration");
688 if (!FirstLocalImport) {
689 FirstLocalImport = Import;
690 LastLocalImport = Import;
691 return;
692 }
693
694 LastLocalImport->NextLocalImport = Import;
695 LastLocalImport = Import;
696}
697
Chris Lattner53cfe802007-07-18 17:52:12 +0000698//===----------------------------------------------------------------------===//
699// Type Sizing and Analysis
700//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000701
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000702/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
703/// scalar floating point type.
704const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000705 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000706 assert(BT && "Not a floating point type!");
707 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000708 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000709 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000710 case BuiltinType::Float: return Target->getFloatFormat();
711 case BuiltinType::Double: return Target->getDoubleFormat();
712 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000713 }
714}
715
Ken Dyck160146e2010-01-27 17:10:57 +0000716/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000717/// specified decl. Note that bitfields do not have a valid alignment, so
718/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000719/// If @p RefAsPointee, references are treated like their underlying type
720/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000721CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000722 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000723
John McCall94268702010-10-08 18:24:19 +0000724 bool UseAlignAttrOnly = false;
725 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
726 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000727
John McCall94268702010-10-08 18:24:19 +0000728 // __attribute__((aligned)) can increase or decrease alignment
729 // *except* on a struct or struct member, where it only increases
730 // alignment unless 'packed' is also specified.
731 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000732 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000733 // ignore that possibility; Sema should diagnose it.
734 if (isa<FieldDecl>(D)) {
735 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
736 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
737 } else {
738 UseAlignAttrOnly = true;
739 }
740 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000741 else if (isa<FieldDecl>(D))
742 UseAlignAttrOnly =
743 D->hasAttr<PackedAttr>() ||
744 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000745
John McCall4e819612011-01-20 07:57:12 +0000746 // If we're using the align attribute only, just ignore everything
747 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000748 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000749 // do nothing
750
John McCall94268702010-10-08 18:24:19 +0000751 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000752 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000753 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000754 if (RefAsPointee)
755 T = RT->getPointeeType();
756 else
757 T = getPointerType(RT->getPointeeType());
758 }
759 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000760 // Adjust alignments of declarations with array type by the
761 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000762 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000763 const ArrayType *arrayType;
764 if (MinWidth && (arrayType = getAsArrayType(T))) {
765 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000766 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000767 else if (isa<ConstantArrayType>(arrayType) &&
768 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000769 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000770
John McCall33ddac02011-01-19 10:06:00 +0000771 // Walk through any array types while we're at it.
772 T = getBaseElementType(arrayType);
773 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000774 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000775 }
John McCall4e819612011-01-20 07:57:12 +0000776
777 // Fields can be subject to extra alignment constraints, like if
778 // the field is packed, the struct is packed, or the struct has a
779 // a max-field-alignment constraint (#pragma pack). So calculate
780 // the actual alignment of the field within the struct, and then
781 // (as we're expected to) constrain that by the alignment of the type.
782 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
783 // So calculate the alignment of the field.
784 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
785
786 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000787 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000788
789 // Use the GCD of that and the offset within the record.
790 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
791 if (offset > 0) {
792 // Alignment is always a power of 2, so the GCD will be a power of 2,
793 // which means we get to do this crazy thing instead of Euclid's.
794 uint64_t lowBitOfOffset = offset & (~offset + 1);
795 if (lowBitOfOffset < fieldAlign)
796 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
797 }
798
799 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000800 }
Chris Lattner68061312009-01-24 21:53:27 +0000801 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000802
Ken Dyckcc56c542011-01-15 18:38:59 +0000803 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000804}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000805
John McCall87fe5d52010-05-20 01:18:31 +0000806std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000807ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000808 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000809 return std::make_pair(toCharUnitsFromBits(Info.first),
810 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000811}
812
813std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000814ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000815 return getTypeInfoInChars(T.getTypePtr());
816}
817
Daniel Dunbarc6475872012-03-09 04:12:54 +0000818std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
819 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
820 if (it != MemoizedTypeInfo.end())
821 return it->second;
822
823 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
824 MemoizedTypeInfo.insert(std::make_pair(T, Info));
825 return Info;
826}
827
828/// getTypeInfoImpl - Return the size of the specified type, in bits. This
829/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000830///
831/// FIXME: Pointers into different addr spaces could have different sizes and
832/// alignment requirements: getPointerInfo should take an AddrSpace, this
833/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000834std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +0000835ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000836 uint64_t Width=0;
837 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000838 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000839#define TYPE(Class, Base)
840#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000841#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000842#define DEPENDENT_TYPE(Class, Base) case Type::Class:
843#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000844 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000845
Chris Lattner355332d2007-07-13 22:27:08 +0000846 case Type::FunctionNoProto:
847 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000848 // GCC extension: alignof(function) = 32 bits
849 Width = 0;
850 Align = 32;
851 break;
852
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000853 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000854 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000855 Width = 0;
856 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
857 break;
858
Steve Naroff5c131802007-08-30 01:06:46 +0000859 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000860 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000861
Chris Lattner37e05872008-03-05 18:54:05 +0000862 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000863 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +0000864 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
865 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000866 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000867 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000868 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000869 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000870 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000871 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000872 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000873 const VectorType *VT = cast<VectorType>(T);
874 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
875 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000876 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000877 // If the alignment is not a power of 2, round up to the next power of 2.
878 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000879 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000880 Align = llvm::NextPowerOf2(Align);
881 Width = llvm::RoundUpToAlignment(Width, Align);
882 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000883 break;
884 }
Chris Lattner647fb222007-07-18 18:26:58 +0000885
Chris Lattner7570e9c2008-03-08 08:52:55 +0000886 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000887 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000888 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000889 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000890 // GCC extension: alignof(void) = 8 bits.
891 Width = 0;
892 Align = 8;
893 break;
894
Chris Lattner6a4f7452007-12-19 19:23:28 +0000895 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000896 Width = Target->getBoolWidth();
897 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000898 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000899 case BuiltinType::Char_S:
900 case BuiltinType::Char_U:
901 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000902 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000903 Width = Target->getCharWidth();
904 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000905 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000906 case BuiltinType::WChar_S:
907 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000908 Width = Target->getWCharWidth();
909 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000910 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000911 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000912 Width = Target->getChar16Width();
913 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000914 break;
915 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000916 Width = Target->getChar32Width();
917 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000918 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000919 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000920 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000921 Width = Target->getShortWidth();
922 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000923 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000924 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000925 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000926 Width = Target->getIntWidth();
927 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000928 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000929 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000930 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000931 Width = Target->getLongWidth();
932 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000933 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000934 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000935 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000936 Width = Target->getLongLongWidth();
937 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000938 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000939 case BuiltinType::Int128:
940 case BuiltinType::UInt128:
941 Width = 128;
942 Align = 128; // int128_t is 128-bit aligned on all targets.
943 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000944 case BuiltinType::Half:
945 Width = Target->getHalfWidth();
946 Align = Target->getHalfAlign();
947 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000948 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000949 Width = Target->getFloatWidth();
950 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000951 break;
952 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000953 Width = Target->getDoubleWidth();
954 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000955 break;
956 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000957 Width = Target->getLongDoubleWidth();
958 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000959 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000960 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000961 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
962 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000963 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000964 case BuiltinType::ObjCId:
965 case BuiltinType::ObjCClass:
966 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000967 Width = Target->getPointerWidth(0);
968 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000969 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000970 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000971 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000972 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000973 Width = Target->getPointerWidth(0);
974 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000975 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000976 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000977 unsigned AS = getTargetAddressSpace(
978 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000979 Width = Target->getPointerWidth(AS);
980 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +0000981 break;
982 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000983 case Type::LValueReference:
984 case Type::RValueReference: {
985 // alignof and sizeof should never enter this code path here, so we go
986 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000987 unsigned AS = getTargetAddressSpace(
988 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000989 Width = Target->getPointerWidth(AS);
990 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000991 break;
992 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000993 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000994 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000995 Width = Target->getPointerWidth(AS);
996 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000997 break;
998 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000999 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001000 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001001 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001002 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001003 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001004 Align = PtrDiffInfo.second;
1005 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001006 }
Chris Lattner647fb222007-07-18 18:26:58 +00001007 case Type::Complex: {
1008 // Complex types have the same alignment as their elements, but twice the
1009 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001010 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001011 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001012 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001013 Align = EltInfo.second;
1014 break;
1015 }
John McCall8b07ec22010-05-15 11:32:37 +00001016 case Type::ObjCObject:
1017 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001018 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001019 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001020 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001021 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001022 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001023 break;
1024 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001025 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001026 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001027 const TagType *TT = cast<TagType>(T);
1028
1029 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001030 Width = 8;
1031 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001032 break;
1033 }
Mike Stump11289f42009-09-09 15:08:12 +00001034
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001035 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001036 return getTypeInfo(ET->getDecl()->getIntegerType());
1037
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001038 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001039 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001040 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001041 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001042 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001043 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001044
Chris Lattner63d2b362009-10-22 05:17:15 +00001045 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001046 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1047 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001048
Richard Smith30482bc2011-02-20 03:19:35 +00001049 case Type::Auto: {
1050 const AutoType *A = cast<AutoType>(T);
1051 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001052 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001053 }
1054
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001055 case Type::Paren:
1056 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1057
Douglas Gregoref462e62009-04-30 17:32:17 +00001058 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001059 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001060 std::pair<uint64_t, unsigned> Info
1061 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001062 // If the typedef has an aligned attribute on it, it overrides any computed
1063 // alignment we have. This violates the GCC documentation (which says that
1064 // attribute(aligned) can only round up) but matches its implementation.
1065 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1066 Align = AttrAlign;
1067 else
1068 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001069 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001070 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001071 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001072
1073 case Type::TypeOfExpr:
1074 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1075 .getTypePtr());
1076
1077 case Type::TypeOf:
1078 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1079
Anders Carlsson81df7b82009-06-24 19:06:50 +00001080 case Type::Decltype:
1081 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1082 .getTypePtr());
1083
Alexis Hunte852b102011-05-24 22:41:36 +00001084 case Type::UnaryTransform:
1085 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1086
Abramo Bagnara6150c882010-05-11 21:36:43 +00001087 case Type::Elaborated:
1088 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001089
John McCall81904512011-01-06 01:58:22 +00001090 case Type::Attributed:
1091 return getTypeInfo(
1092 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1093
Richard Smith3f1b5d02011-05-05 21:57:07 +00001094 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001095 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001096 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001097 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1098 // A type alias template specialization may refer to a typedef with the
1099 // aligned attribute on it.
1100 if (TST->isTypeAlias())
1101 return getTypeInfo(TST->getAliasedType().getTypePtr());
1102 else
1103 return getTypeInfo(getCanonicalType(T));
1104 }
1105
Eli Friedman0dfb8892011-10-06 23:00:33 +00001106 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001107 std::pair<uint64_t, unsigned> Info
1108 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1109 Width = Info.first;
1110 Align = Info.second;
1111 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1112 llvm::isPowerOf2_64(Width)) {
1113 // We can potentially perform lock-free atomic operations for this
1114 // type; promote the alignment appropriately.
1115 // FIXME: We could potentially promote the width here as well...
1116 // is that worthwhile? (Non-struct atomic types generally have
1117 // power-of-two size anyway, but structs might not. Requires a bit
1118 // of implementation work to make sure we zero out the extra bits.)
1119 Align = static_cast<unsigned>(Width);
1120 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001121 }
1122
Douglas Gregoref462e62009-04-30 17:32:17 +00001123 }
Mike Stump11289f42009-09-09 15:08:12 +00001124
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001125 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001126 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001127}
1128
Ken Dyckcc56c542011-01-15 18:38:59 +00001129/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1130CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1131 return CharUnits::fromQuantity(BitSize / getCharWidth());
1132}
1133
Ken Dyckb0fcc592011-02-11 01:54:29 +00001134/// toBits - Convert a size in characters to a size in characters.
1135int64_t ASTContext::toBits(CharUnits CharSize) const {
1136 return CharSize.getQuantity() * getCharWidth();
1137}
1138
Ken Dyck8c89d592009-12-22 14:23:30 +00001139/// getTypeSizeInChars - Return the size of the specified type, in characters.
1140/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001141CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001142 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001143}
Jay Foad39c79802011-01-12 09:06:06 +00001144CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001145 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001146}
1147
Ken Dycka6046ab2010-01-26 17:25:18 +00001148/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001149/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001150CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001151 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001152}
Jay Foad39c79802011-01-12 09:06:06 +00001153CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001154 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001155}
1156
Chris Lattnera3402cd2009-01-27 18:08:34 +00001157/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1158/// type for the current target in bits. This can be different than the ABI
1159/// alignment in cases where it is beneficial for performance to overalign
1160/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001161unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001162 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001163
1164 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001165 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001166 T = CT->getElementType().getTypePtr();
1167 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001168 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1169 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001170 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1171
Chris Lattnera3402cd2009-01-27 18:08:34 +00001172 return ABIAlign;
1173}
1174
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001175/// DeepCollectObjCIvars -
1176/// This routine first collects all declared, but not synthesized, ivars in
1177/// super class and then collects all ivars, including those synthesized for
1178/// current class. This routine is used for implementation of current class
1179/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001180///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001181void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1182 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001183 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001184 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1185 DeepCollectObjCIvars(SuperClass, false, Ivars);
1186 if (!leafClass) {
1187 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1188 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001189 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001190 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001191 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001192 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001193 Iv= Iv->getNextIvar())
1194 Ivars.push_back(Iv);
1195 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001196}
1197
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001198/// CollectInheritedProtocols - Collect all protocols in current class and
1199/// those inherited by it.
1200void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001201 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001202 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001203 // We can use protocol_iterator here instead of
1204 // all_referenced_protocol_iterator since we are walking all categories.
1205 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1206 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001207 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001208 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001209 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001210 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001211 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001212 CollectInheritedProtocols(*P, Protocols);
1213 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001214 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001215
1216 // Categories of this Interface.
1217 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1218 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1219 CollectInheritedProtocols(CDeclChain, Protocols);
1220 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1221 while (SD) {
1222 CollectInheritedProtocols(SD, Protocols);
1223 SD = SD->getSuperClass();
1224 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001225 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001226 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001227 PE = OC->protocol_end(); P != PE; ++P) {
1228 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001229 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001230 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1231 PE = Proto->protocol_end(); P != PE; ++P)
1232 CollectInheritedProtocols(*P, Protocols);
1233 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001234 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001235 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1236 PE = OP->protocol_end(); P != PE; ++P) {
1237 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001238 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001239 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1240 PE = Proto->protocol_end(); P != PE; ++P)
1241 CollectInheritedProtocols(*P, Protocols);
1242 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001243 }
1244}
1245
Jay Foad39c79802011-01-12 09:06:06 +00001246unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001247 unsigned count = 0;
1248 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001249 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1250 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001251 count += CDecl->ivar_size();
1252
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001253 // Count ivar defined in this class's implementation. This
1254 // includes synthesized ivars.
1255 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001256 count += ImplDecl->ivar_size();
1257
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001258 return count;
1259}
1260
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001261bool ASTContext::isSentinelNullExpr(const Expr *E) {
1262 if (!E)
1263 return false;
1264
1265 // nullptr_t is always treated as null.
1266 if (E->getType()->isNullPtrType()) return true;
1267
1268 if (E->getType()->isAnyPointerType() &&
1269 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1270 Expr::NPC_ValueDependentIsNull))
1271 return true;
1272
1273 // Unfortunately, __null has type 'int'.
1274 if (isa<GNUNullExpr>(E)) return true;
1275
1276 return false;
1277}
1278
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001279/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1280ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1281 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1282 I = ObjCImpls.find(D);
1283 if (I != ObjCImpls.end())
1284 return cast<ObjCImplementationDecl>(I->second);
1285 return 0;
1286}
1287/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1288ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1289 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1290 I = ObjCImpls.find(D);
1291 if (I != ObjCImpls.end())
1292 return cast<ObjCCategoryImplDecl>(I->second);
1293 return 0;
1294}
1295
1296/// \brief Set the implementation of ObjCInterfaceDecl.
1297void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1298 ObjCImplementationDecl *ImplD) {
1299 assert(IFaceD && ImplD && "Passed null params");
1300 ObjCImpls[IFaceD] = ImplD;
1301}
1302/// \brief Set the implementation of ObjCCategoryDecl.
1303void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1304 ObjCCategoryImplDecl *ImplD) {
1305 assert(CatD && ImplD && "Passed null params");
1306 ObjCImpls[CatD] = ImplD;
1307}
1308
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001309ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1310 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1311 return ID;
1312 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1313 return CD->getClassInterface();
1314 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1315 return IMD->getClassInterface();
1316
1317 return 0;
1318}
1319
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001320/// \brief Get the copy initialization expression of VarDecl,or NULL if
1321/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001322Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001323 assert(VD && "Passed null params");
1324 assert(VD->hasAttr<BlocksAttr>() &&
1325 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001326 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001327 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001328 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1329}
1330
1331/// \brief Set the copy inialization expression of a block var decl.
1332void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1333 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001334 assert(VD->hasAttr<BlocksAttr>() &&
1335 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001336 BlockVarCopyInits[VD] = Init;
1337}
1338
John McCallbcd03502009-12-07 02:54:59 +00001339/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001340///
John McCallbcd03502009-12-07 02:54:59 +00001341/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001342/// the TypeLoc wrappers.
1343///
1344/// \param T the type that will be the basis for type source info. This type
1345/// should refer to how the declarator was written in source code, not to
1346/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001347TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001348 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001349 if (!DataSize)
1350 DataSize = TypeLoc::getFullDataSizeForType(T);
1351 else
1352 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001353 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001354
John McCallbcd03502009-12-07 02:54:59 +00001355 TypeSourceInfo *TInfo =
1356 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1357 new (TInfo) TypeSourceInfo(T);
1358 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001359}
1360
John McCallbcd03502009-12-07 02:54:59 +00001361TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001362 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001363 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001364 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001365 return DI;
1366}
1367
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001368const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001369ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001370 return getObjCLayout(D, 0);
1371}
1372
1373const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001374ASTContext::getASTObjCImplementationLayout(
1375 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001376 return getObjCLayout(D->getClassInterface(), D);
1377}
1378
Chris Lattner983a8bb2007-07-13 22:13:22 +00001379//===----------------------------------------------------------------------===//
1380// Type creation/memoization methods
1381//===----------------------------------------------------------------------===//
1382
Jay Foad39c79802011-01-12 09:06:06 +00001383QualType
John McCall33ddac02011-01-19 10:06:00 +00001384ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1385 unsigned fastQuals = quals.getFastQualifiers();
1386 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001387
1388 // Check if we've already instantiated this type.
1389 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001390 ExtQuals::Profile(ID, baseType, quals);
1391 void *insertPos = 0;
1392 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1393 assert(eq->getQualifiers() == quals);
1394 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001395 }
1396
John McCall33ddac02011-01-19 10:06:00 +00001397 // If the base type is not canonical, make the appropriate canonical type.
1398 QualType canon;
1399 if (!baseType->isCanonicalUnqualified()) {
1400 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001401 canonSplit.Quals.addConsistentQualifiers(quals);
1402 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001403
1404 // Re-find the insert position.
1405 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1406 }
1407
1408 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1409 ExtQualNodes.InsertNode(eq, insertPos);
1410 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001411}
1412
Jay Foad39c79802011-01-12 09:06:06 +00001413QualType
1414ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001415 QualType CanT = getCanonicalType(T);
1416 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001417 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001418
John McCall8ccfcb52009-09-24 19:53:00 +00001419 // If we are composing extended qualifiers together, merge together
1420 // into one ExtQuals node.
1421 QualifierCollector Quals;
1422 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001423
John McCall8ccfcb52009-09-24 19:53:00 +00001424 // If this type already has an address space specified, it cannot get
1425 // another one.
1426 assert(!Quals.hasAddressSpace() &&
1427 "Type cannot be in multiple addr spaces!");
1428 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001429
John McCall8ccfcb52009-09-24 19:53:00 +00001430 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001431}
1432
Chris Lattnerd60183d2009-02-18 22:53:11 +00001433QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001434 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001435 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001436 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001437 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001438
John McCall53fa7142010-12-24 02:08:15 +00001439 if (const PointerType *ptr = T->getAs<PointerType>()) {
1440 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001441 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001442 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1443 return getPointerType(ResultType);
1444 }
1445 }
Mike Stump11289f42009-09-09 15:08:12 +00001446
John McCall8ccfcb52009-09-24 19:53:00 +00001447 // If we are composing extended qualifiers together, merge together
1448 // into one ExtQuals node.
1449 QualifierCollector Quals;
1450 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001451
John McCall8ccfcb52009-09-24 19:53:00 +00001452 // If this type already has an ObjCGC specified, it cannot get
1453 // another one.
1454 assert(!Quals.hasObjCGCAttr() &&
1455 "Type cannot have multiple ObjCGCs!");
1456 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001457
John McCall8ccfcb52009-09-24 19:53:00 +00001458 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001459}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001460
John McCall4f5019e2010-12-19 02:44:49 +00001461const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1462 FunctionType::ExtInfo Info) {
1463 if (T->getExtInfo() == Info)
1464 return T;
1465
1466 QualType Result;
1467 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1468 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1469 } else {
1470 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1471 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1472 EPI.ExtInfo = Info;
1473 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1474 FPT->getNumArgs(), EPI);
1475 }
1476
1477 return cast<FunctionType>(Result.getTypePtr());
1478}
1479
Chris Lattnerc6395932007-06-22 20:56:16 +00001480/// getComplexType - Return the uniqued reference to the type for a complex
1481/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001482QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001483 // Unique pointers, to guarantee there is only one pointer of a particular
1484 // structure.
1485 llvm::FoldingSetNodeID ID;
1486 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001487
Chris Lattnerc6395932007-06-22 20:56:16 +00001488 void *InsertPos = 0;
1489 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1490 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001491
Chris Lattnerc6395932007-06-22 20:56:16 +00001492 // If the pointee type isn't canonical, this won't be a canonical type either,
1493 // so fill in the canonical type field.
1494 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001495 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001496 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001497
Chris Lattnerc6395932007-06-22 20:56:16 +00001498 // Get the new insert position for the node we care about.
1499 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001500 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001501 }
John McCall90d1c2d2009-09-24 23:30:46 +00001502 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001503 Types.push_back(New);
1504 ComplexTypes.InsertNode(New, InsertPos);
1505 return QualType(New, 0);
1506}
1507
Chris Lattner970e54e2006-11-12 00:37:36 +00001508/// getPointerType - Return the uniqued reference to the type for a pointer to
1509/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001510QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001511 // Unique pointers, to guarantee there is only one pointer of a particular
1512 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001513 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001514 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001515
Chris Lattner67521df2007-01-27 01:29:36 +00001516 void *InsertPos = 0;
1517 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001518 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001519
Chris Lattner7ccecb92006-11-12 08:50:50 +00001520 // If the pointee type isn't canonical, this won't be a canonical type either,
1521 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001522 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001523 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001524 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001525
Chris Lattner67521df2007-01-27 01:29:36 +00001526 // Get the new insert position for the node we care about.
1527 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001528 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001529 }
John McCall90d1c2d2009-09-24 23:30:46 +00001530 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001531 Types.push_back(New);
1532 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001533 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001534}
1535
Mike Stump11289f42009-09-09 15:08:12 +00001536/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001537/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001538QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001539 assert(T->isFunctionType() && "block of function types only");
1540 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001541 // structure.
1542 llvm::FoldingSetNodeID ID;
1543 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001544
Steve Naroffec33ed92008-08-27 16:04:49 +00001545 void *InsertPos = 0;
1546 if (BlockPointerType *PT =
1547 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1548 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001549
1550 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001551 // type either so fill in the canonical type field.
1552 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001553 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001554 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001555
Steve Naroffec33ed92008-08-27 16:04:49 +00001556 // Get the new insert position for the node we care about.
1557 BlockPointerType *NewIP =
1558 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001559 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001560 }
John McCall90d1c2d2009-09-24 23:30:46 +00001561 BlockPointerType *New
1562 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001563 Types.push_back(New);
1564 BlockPointerTypes.InsertNode(New, InsertPos);
1565 return QualType(New, 0);
1566}
1567
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001568/// getLValueReferenceType - Return the uniqued reference to the type for an
1569/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001570QualType
1571ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001572 assert(getCanonicalType(T) != OverloadTy &&
1573 "Unresolved overloaded function type");
1574
Bill Wendling3708c182007-05-27 10:15:43 +00001575 // Unique pointers, to guarantee there is only one pointer of a particular
1576 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001577 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001578 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001579
1580 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001581 if (LValueReferenceType *RT =
1582 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001583 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001584
John McCallfc93cf92009-10-22 22:37:11 +00001585 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1586
Bill Wendling3708c182007-05-27 10:15:43 +00001587 // If the referencee type isn't canonical, this won't be a canonical type
1588 // either, so fill in the canonical type field.
1589 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001590 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1591 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1592 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001593
Bill Wendling3708c182007-05-27 10:15:43 +00001594 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001595 LValueReferenceType *NewIP =
1596 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001597 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001598 }
1599
John McCall90d1c2d2009-09-24 23:30:46 +00001600 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001601 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1602 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001603 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001604 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001605
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001606 return QualType(New, 0);
1607}
1608
1609/// getRValueReferenceType - Return the uniqued reference to the type for an
1610/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001611QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001612 // Unique pointers, to guarantee there is only one pointer of a particular
1613 // structure.
1614 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001615 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001616
1617 void *InsertPos = 0;
1618 if (RValueReferenceType *RT =
1619 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1620 return QualType(RT, 0);
1621
John McCallfc93cf92009-10-22 22:37:11 +00001622 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1623
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001624 // If the referencee type isn't canonical, this won't be a canonical type
1625 // either, so fill in the canonical type field.
1626 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001627 if (InnerRef || !T.isCanonical()) {
1628 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1629 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001630
1631 // Get the new insert position for the node we care about.
1632 RValueReferenceType *NewIP =
1633 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001634 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001635 }
1636
John McCall90d1c2d2009-09-24 23:30:46 +00001637 RValueReferenceType *New
1638 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001639 Types.push_back(New);
1640 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001641 return QualType(New, 0);
1642}
1643
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001644/// getMemberPointerType - Return the uniqued reference to the type for a
1645/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001646QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001647 // Unique pointers, to guarantee there is only one pointer of a particular
1648 // structure.
1649 llvm::FoldingSetNodeID ID;
1650 MemberPointerType::Profile(ID, T, Cls);
1651
1652 void *InsertPos = 0;
1653 if (MemberPointerType *PT =
1654 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1655 return QualType(PT, 0);
1656
1657 // If the pointee or class type isn't canonical, this won't be a canonical
1658 // type either, so fill in the canonical type field.
1659 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001660 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001661 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1662
1663 // Get the new insert position for the node we care about.
1664 MemberPointerType *NewIP =
1665 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001666 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001667 }
John McCall90d1c2d2009-09-24 23:30:46 +00001668 MemberPointerType *New
1669 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001670 Types.push_back(New);
1671 MemberPointerTypes.InsertNode(New, InsertPos);
1672 return QualType(New, 0);
1673}
1674
Mike Stump11289f42009-09-09 15:08:12 +00001675/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001676/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001677QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001678 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001679 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001680 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001681 assert((EltTy->isDependentType() ||
1682 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001683 "Constant array of VLAs is illegal!");
1684
Chris Lattnere2df3f92009-05-13 04:12:56 +00001685 // Convert the array size into a canonical width matching the pointer size for
1686 // the target.
1687 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001688 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001689 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001690
Chris Lattner23b7eb62007-06-15 23:05:46 +00001691 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001692 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001693
Chris Lattner36f8e652007-01-27 08:31:04 +00001694 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001695 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001696 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001697 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001698
John McCall33ddac02011-01-19 10:06:00 +00001699 // If the element type isn't canonical or has qualifiers, this won't
1700 // be a canonical type either, so fill in the canonical type field.
1701 QualType Canon;
1702 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1703 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001704 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001705 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001706 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001707
Chris Lattner36f8e652007-01-27 08:31:04 +00001708 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001709 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001710 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001711 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001712 }
Mike Stump11289f42009-09-09 15:08:12 +00001713
John McCall90d1c2d2009-09-24 23:30:46 +00001714 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001715 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001716 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001717 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001718 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001719}
1720
John McCall06549462011-01-18 08:40:38 +00001721/// getVariableArrayDecayedType - Turns the given type, which may be
1722/// variably-modified, into the corresponding type with all the known
1723/// sizes replaced with [*].
1724QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1725 // Vastly most common case.
1726 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001727
John McCall06549462011-01-18 08:40:38 +00001728 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001729
John McCall06549462011-01-18 08:40:38 +00001730 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001731 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001732 switch (ty->getTypeClass()) {
1733#define TYPE(Class, Base)
1734#define ABSTRACT_TYPE(Class, Base)
1735#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1736#include "clang/AST/TypeNodes.def"
1737 llvm_unreachable("didn't desugar past all non-canonical types?");
1738
1739 // These types should never be variably-modified.
1740 case Type::Builtin:
1741 case Type::Complex:
1742 case Type::Vector:
1743 case Type::ExtVector:
1744 case Type::DependentSizedExtVector:
1745 case Type::ObjCObject:
1746 case Type::ObjCInterface:
1747 case Type::ObjCObjectPointer:
1748 case Type::Record:
1749 case Type::Enum:
1750 case Type::UnresolvedUsing:
1751 case Type::TypeOfExpr:
1752 case Type::TypeOf:
1753 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001754 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001755 case Type::DependentName:
1756 case Type::InjectedClassName:
1757 case Type::TemplateSpecialization:
1758 case Type::DependentTemplateSpecialization:
1759 case Type::TemplateTypeParm:
1760 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001761 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001762 case Type::PackExpansion:
1763 llvm_unreachable("type should never be variably-modified");
1764
1765 // These types can be variably-modified but should never need to
1766 // further decay.
1767 case Type::FunctionNoProto:
1768 case Type::FunctionProto:
1769 case Type::BlockPointer:
1770 case Type::MemberPointer:
1771 return type;
1772
1773 // These types can be variably-modified. All these modifications
1774 // preserve structure except as noted by comments.
1775 // TODO: if we ever care about optimizing VLAs, there are no-op
1776 // optimizations available here.
1777 case Type::Pointer:
1778 result = getPointerType(getVariableArrayDecayedType(
1779 cast<PointerType>(ty)->getPointeeType()));
1780 break;
1781
1782 case Type::LValueReference: {
1783 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1784 result = getLValueReferenceType(
1785 getVariableArrayDecayedType(lv->getPointeeType()),
1786 lv->isSpelledAsLValue());
1787 break;
1788 }
1789
1790 case Type::RValueReference: {
1791 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1792 result = getRValueReferenceType(
1793 getVariableArrayDecayedType(lv->getPointeeType()));
1794 break;
1795 }
1796
Eli Friedman0dfb8892011-10-06 23:00:33 +00001797 case Type::Atomic: {
1798 const AtomicType *at = cast<AtomicType>(ty);
1799 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1800 break;
1801 }
1802
John McCall06549462011-01-18 08:40:38 +00001803 case Type::ConstantArray: {
1804 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1805 result = getConstantArrayType(
1806 getVariableArrayDecayedType(cat->getElementType()),
1807 cat->getSize(),
1808 cat->getSizeModifier(),
1809 cat->getIndexTypeCVRQualifiers());
1810 break;
1811 }
1812
1813 case Type::DependentSizedArray: {
1814 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1815 result = getDependentSizedArrayType(
1816 getVariableArrayDecayedType(dat->getElementType()),
1817 dat->getSizeExpr(),
1818 dat->getSizeModifier(),
1819 dat->getIndexTypeCVRQualifiers(),
1820 dat->getBracketsRange());
1821 break;
1822 }
1823
1824 // Turn incomplete types into [*] types.
1825 case Type::IncompleteArray: {
1826 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1827 result = getVariableArrayType(
1828 getVariableArrayDecayedType(iat->getElementType()),
1829 /*size*/ 0,
1830 ArrayType::Normal,
1831 iat->getIndexTypeCVRQualifiers(),
1832 SourceRange());
1833 break;
1834 }
1835
1836 // Turn VLA types into [*] types.
1837 case Type::VariableArray: {
1838 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1839 result = getVariableArrayType(
1840 getVariableArrayDecayedType(vat->getElementType()),
1841 /*size*/ 0,
1842 ArrayType::Star,
1843 vat->getIndexTypeCVRQualifiers(),
1844 vat->getBracketsRange());
1845 break;
1846 }
1847 }
1848
1849 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00001850 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00001851}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001852
Steve Naroffcadebd02007-08-30 18:14:25 +00001853/// getVariableArrayType - Returns a non-unique reference to the type for a
1854/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001855QualType ASTContext::getVariableArrayType(QualType EltTy,
1856 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001857 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001858 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001859 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001860 // Since we don't unique expressions, it isn't possible to unique VLA's
1861 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001862 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001863
John McCall33ddac02011-01-19 10:06:00 +00001864 // Be sure to pull qualifiers off the element type.
1865 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1866 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001867 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001868 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00001869 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001870 }
1871
John McCall90d1c2d2009-09-24 23:30:46 +00001872 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001873 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001874
1875 VariableArrayTypes.push_back(New);
1876 Types.push_back(New);
1877 return QualType(New, 0);
1878}
1879
Douglas Gregor4619e432008-12-05 23:32:09 +00001880/// getDependentSizedArrayType - Returns a non-unique reference to
1881/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001882/// type.
John McCall33ddac02011-01-19 10:06:00 +00001883QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1884 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001885 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001886 unsigned elementTypeQuals,
1887 SourceRange brackets) const {
1888 assert((!numElements || numElements->isTypeDependent() ||
1889 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001890 "Size must be type- or value-dependent!");
1891
John McCall33ddac02011-01-19 10:06:00 +00001892 // Dependently-sized array types that do not have a specified number
1893 // of elements will have their sizes deduced from a dependent
1894 // initializer. We do no canonicalization here at all, which is okay
1895 // because they can't be used in most locations.
1896 if (!numElements) {
1897 DependentSizedArrayType *newType
1898 = new (*this, TypeAlignment)
1899 DependentSizedArrayType(*this, elementType, QualType(),
1900 numElements, ASM, elementTypeQuals,
1901 brackets);
1902 Types.push_back(newType);
1903 return QualType(newType, 0);
1904 }
1905
1906 // Otherwise, we actually build a new type every time, but we
1907 // also build a canonical type.
1908
1909 SplitQualType canonElementType = getCanonicalType(elementType).split();
1910
1911 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001912 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001913 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00001914 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001915 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001916
John McCall33ddac02011-01-19 10:06:00 +00001917 // Look for an existing type with these properties.
1918 DependentSizedArrayType *canonTy =
1919 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001920
John McCall33ddac02011-01-19 10:06:00 +00001921 // If we don't have one, build one.
1922 if (!canonTy) {
1923 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00001924 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001925 QualType(), numElements, ASM, elementTypeQuals,
1926 brackets);
1927 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1928 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001929 }
1930
John McCall33ddac02011-01-19 10:06:00 +00001931 // Apply qualifiers from the element type to the array.
1932 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00001933 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00001934
John McCall33ddac02011-01-19 10:06:00 +00001935 // If we didn't need extra canonicalization for the element type,
1936 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00001937 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00001938 return canon;
1939
1940 // Otherwise, we need to build a type which follows the spelling
1941 // of the element type.
1942 DependentSizedArrayType *sugaredType
1943 = new (*this, TypeAlignment)
1944 DependentSizedArrayType(*this, elementType, canon, numElements,
1945 ASM, elementTypeQuals, brackets);
1946 Types.push_back(sugaredType);
1947 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001948}
1949
John McCall33ddac02011-01-19 10:06:00 +00001950QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001951 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001952 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001953 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001954 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001955
John McCall33ddac02011-01-19 10:06:00 +00001956 void *insertPos = 0;
1957 if (IncompleteArrayType *iat =
1958 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1959 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001960
1961 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001962 // either, so fill in the canonical type field. We also have to pull
1963 // qualifiers off the element type.
1964 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001965
John McCall33ddac02011-01-19 10:06:00 +00001966 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1967 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00001968 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001969 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001970 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001971
1972 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001973 IncompleteArrayType *existing =
1974 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1975 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001976 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001977
John McCall33ddac02011-01-19 10:06:00 +00001978 IncompleteArrayType *newType = new (*this, TypeAlignment)
1979 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001980
John McCall33ddac02011-01-19 10:06:00 +00001981 IncompleteArrayTypes.InsertNode(newType, insertPos);
1982 Types.push_back(newType);
1983 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001984}
1985
Steve Naroff91fcddb2007-07-18 18:00:27 +00001986/// getVectorType - Return the unique reference to a vector type of
1987/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001988QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001989 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001990 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001991
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001992 // Check if we've already instantiated a vector of this type.
1993 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001994 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001995
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001996 void *InsertPos = 0;
1997 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1998 return QualType(VTP, 0);
1999
2000 // If the element type isn't canonical, this won't be a canonical type either,
2001 // so fill in the canonical type field.
2002 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002003 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002004 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002005
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002006 // Get the new insert position for the node we care about.
2007 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002008 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002009 }
John McCall90d1c2d2009-09-24 23:30:46 +00002010 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002011 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002012 VectorTypes.InsertNode(New, InsertPos);
2013 Types.push_back(New);
2014 return QualType(New, 0);
2015}
2016
Nate Begemance4d7fc2008-04-18 23:10:10 +00002017/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002018/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002019QualType
2020ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002021 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002022
Steve Naroff91fcddb2007-07-18 18:00:27 +00002023 // Check if we've already instantiated a vector of this type.
2024 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002025 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002026 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002027 void *InsertPos = 0;
2028 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2029 return QualType(VTP, 0);
2030
2031 // If the element type isn't canonical, this won't be a canonical type either,
2032 // so fill in the canonical type field.
2033 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002034 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002035 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002036
Steve Naroff91fcddb2007-07-18 18:00:27 +00002037 // Get the new insert position for the node we care about.
2038 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002039 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002040 }
John McCall90d1c2d2009-09-24 23:30:46 +00002041 ExtVectorType *New = new (*this, TypeAlignment)
2042 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002043 VectorTypes.InsertNode(New, InsertPos);
2044 Types.push_back(New);
2045 return QualType(New, 0);
2046}
2047
Jay Foad39c79802011-01-12 09:06:06 +00002048QualType
2049ASTContext::getDependentSizedExtVectorType(QualType vecType,
2050 Expr *SizeExpr,
2051 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002052 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002053 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002054 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002055
Douglas Gregor352169a2009-07-31 03:54:25 +00002056 void *InsertPos = 0;
2057 DependentSizedExtVectorType *Canon
2058 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2059 DependentSizedExtVectorType *New;
2060 if (Canon) {
2061 // We already have a canonical version of this array type; use it as
2062 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002063 New = new (*this, TypeAlignment)
2064 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2065 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002066 } else {
2067 QualType CanonVecTy = getCanonicalType(vecType);
2068 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002069 New = new (*this, TypeAlignment)
2070 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2071 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002072
2073 DependentSizedExtVectorType *CanonCheck
2074 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2075 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2076 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002077 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2078 } else {
2079 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2080 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002081 New = new (*this, TypeAlignment)
2082 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002083 }
2084 }
Mike Stump11289f42009-09-09 15:08:12 +00002085
Douglas Gregor758a8692009-06-17 21:51:59 +00002086 Types.push_back(New);
2087 return QualType(New, 0);
2088}
2089
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002090/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002091///
Jay Foad39c79802011-01-12 09:06:06 +00002092QualType
2093ASTContext::getFunctionNoProtoType(QualType ResultTy,
2094 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002095 const CallingConv DefaultCC = Info.getCC();
2096 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2097 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002098 // Unique functions, to guarantee there is only one function of a particular
2099 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002100 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002101 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002102
Chris Lattner47955de2007-01-27 08:37:20 +00002103 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002104 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002105 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002106 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002107
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002108 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002109 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002110 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002111 Canonical =
2112 getFunctionNoProtoType(getCanonicalType(ResultTy),
2113 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002114
Chris Lattner47955de2007-01-27 08:37:20 +00002115 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002116 FunctionNoProtoType *NewIP =
2117 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002118 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002119 }
Mike Stump11289f42009-09-09 15:08:12 +00002120
Roman Divacky65b88cd2011-03-01 17:40:53 +00002121 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002122 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002123 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002124 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002125 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002126 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002127}
2128
2129/// getFunctionType - Return a normal function type with a typed argument
2130/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002131QualType
2132ASTContext::getFunctionType(QualType ResultTy,
2133 const QualType *ArgArray, unsigned NumArgs,
2134 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002135 // Unique functions, to guarantee there is only one function of a particular
2136 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002137 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002138 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002139
2140 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002141 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002142 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002143 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002144
2145 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002146 bool isCanonical =
2147 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2148 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002149 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002150 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002151 isCanonical = false;
2152
Roman Divacky65b88cd2011-03-01 17:40:53 +00002153 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2154 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2155 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002156
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002157 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002158 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002159 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002160 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002161 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002162 CanonicalArgs.reserve(NumArgs);
2163 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002164 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002165
John McCalldb40c7f2010-12-14 08:05:40 +00002166 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002167 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002168 CanonicalEPI.ExceptionSpecType = EST_None;
2169 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002170 CanonicalEPI.ExtInfo
2171 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2172
Chris Lattner76a00cf2008-04-06 22:59:24 +00002173 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002174 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002175 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002176
Chris Lattnerfd4de792007-01-27 01:15:32 +00002177 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002178 FunctionProtoType *NewIP =
2179 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002180 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002181 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002182
John McCall31168b02011-06-15 23:02:42 +00002183 // FunctionProtoType objects are allocated with extra bytes after
2184 // them for three variable size arrays at the end:
2185 // - parameter types
2186 // - exception types
2187 // - consumed-arguments flags
2188 // Instead of the exception types, there could be a noexcept
2189 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002190 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002191 NumArgs * sizeof(QualType);
2192 if (EPI.ExceptionSpecType == EST_Dynamic)
2193 Size += EPI.NumExceptions * sizeof(QualType);
2194 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002195 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002196 }
John McCall31168b02011-06-15 23:02:42 +00002197 if (EPI.ConsumedArguments)
2198 Size += NumArgs * sizeof(bool);
2199
John McCalldb40c7f2010-12-14 08:05:40 +00002200 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002201 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2202 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002203 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002204 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002205 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002206 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002207}
Chris Lattneref51c202006-11-10 07:17:23 +00002208
John McCalle78aac42010-03-10 03:28:59 +00002209#ifndef NDEBUG
2210static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2211 if (!isa<CXXRecordDecl>(D)) return false;
2212 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2213 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2214 return true;
2215 if (RD->getDescribedClassTemplate() &&
2216 !isa<ClassTemplateSpecializationDecl>(RD))
2217 return true;
2218 return false;
2219}
2220#endif
2221
2222/// getInjectedClassNameType - Return the unique reference to the
2223/// injected class name type for the specified templated declaration.
2224QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002225 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002226 assert(NeedsInjectedClassNameType(Decl));
2227 if (Decl->TypeForDecl) {
2228 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002229 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002230 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2231 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2232 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2233 } else {
John McCall424cec92011-01-19 06:33:43 +00002234 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002235 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002236 Decl->TypeForDecl = newType;
2237 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002238 }
2239 return QualType(Decl->TypeForDecl, 0);
2240}
2241
Douglas Gregor83a586e2008-04-13 21:07:44 +00002242/// getTypeDeclType - Return the unique reference to the type for the
2243/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002244QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002245 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002246 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002247
Richard Smithdda56e42011-04-15 14:24:37 +00002248 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002249 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002250
John McCall96f0b5f2010-03-10 06:48:02 +00002251 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2252 "Template type parameter types are always available.");
2253
John McCall81e38502010-02-16 03:57:14 +00002254 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002255 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002256 "struct/union has previous declaration");
2257 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002258 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002259 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002260 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002261 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002262 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002263 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002264 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002265 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2266 Decl->TypeForDecl = newType;
2267 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002268 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002269 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002270
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002271 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002272}
2273
Chris Lattner32d920b2007-01-26 02:01:53 +00002274/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002275/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002276QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002277ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2278 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002279 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002280
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002281 if (Canonical.isNull())
2282 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002283 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002284 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002285 Decl->TypeForDecl = newType;
2286 Types.push_back(newType);
2287 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002288}
2289
Jay Foad39c79802011-01-12 09:06:06 +00002290QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002291 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2292
Douglas Gregorec9fd132012-01-14 16:38:05 +00002293 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002294 if (PrevDecl->TypeForDecl)
2295 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2296
John McCall424cec92011-01-19 06:33:43 +00002297 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2298 Decl->TypeForDecl = newType;
2299 Types.push_back(newType);
2300 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002301}
2302
Jay Foad39c79802011-01-12 09:06:06 +00002303QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002304 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2305
Douglas Gregorec9fd132012-01-14 16:38:05 +00002306 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002307 if (PrevDecl->TypeForDecl)
2308 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2309
John McCall424cec92011-01-19 06:33:43 +00002310 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2311 Decl->TypeForDecl = newType;
2312 Types.push_back(newType);
2313 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002314}
2315
John McCall81904512011-01-06 01:58:22 +00002316QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2317 QualType modifiedType,
2318 QualType equivalentType) {
2319 llvm::FoldingSetNodeID id;
2320 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2321
2322 void *insertPos = 0;
2323 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2324 if (type) return QualType(type, 0);
2325
2326 QualType canon = getCanonicalType(equivalentType);
2327 type = new (*this, TypeAlignment)
2328 AttributedType(canon, attrKind, modifiedType, equivalentType);
2329
2330 Types.push_back(type);
2331 AttributedTypes.InsertNode(type, insertPos);
2332
2333 return QualType(type, 0);
2334}
2335
2336
John McCallcebee162009-10-18 09:09:24 +00002337/// \brief Retrieve a substitution-result type.
2338QualType
2339ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002340 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002341 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002342 && "replacement types must always be canonical");
2343
2344 llvm::FoldingSetNodeID ID;
2345 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2346 void *InsertPos = 0;
2347 SubstTemplateTypeParmType *SubstParm
2348 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2349
2350 if (!SubstParm) {
2351 SubstParm = new (*this, TypeAlignment)
2352 SubstTemplateTypeParmType(Parm, Replacement);
2353 Types.push_back(SubstParm);
2354 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2355 }
2356
2357 return QualType(SubstParm, 0);
2358}
2359
Douglas Gregorada4b792011-01-14 02:55:32 +00002360/// \brief Retrieve a
2361QualType ASTContext::getSubstTemplateTypeParmPackType(
2362 const TemplateTypeParmType *Parm,
2363 const TemplateArgument &ArgPack) {
2364#ifndef NDEBUG
2365 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2366 PEnd = ArgPack.pack_end();
2367 P != PEnd; ++P) {
2368 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2369 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2370 }
2371#endif
2372
2373 llvm::FoldingSetNodeID ID;
2374 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2375 void *InsertPos = 0;
2376 if (SubstTemplateTypeParmPackType *SubstParm
2377 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2378 return QualType(SubstParm, 0);
2379
2380 QualType Canon;
2381 if (!Parm->isCanonicalUnqualified()) {
2382 Canon = getCanonicalType(QualType(Parm, 0));
2383 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2384 ArgPack);
2385 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2386 }
2387
2388 SubstTemplateTypeParmPackType *SubstParm
2389 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2390 ArgPack);
2391 Types.push_back(SubstParm);
2392 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2393 return QualType(SubstParm, 0);
2394}
2395
Douglas Gregoreff93e02009-02-05 23:33:38 +00002396/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002397/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002398/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002399QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002400 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002401 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002402 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002403 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002404 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002405 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002406 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2407
2408 if (TypeParm)
2409 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002410
Chandler Carruth08836322011-05-01 00:51:33 +00002411 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002412 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002413 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002414
2415 TemplateTypeParmType *TypeCheck
2416 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2417 assert(!TypeCheck && "Template type parameter canonical type broken");
2418 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002419 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002420 TypeParm = new (*this, TypeAlignment)
2421 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002422
2423 Types.push_back(TypeParm);
2424 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2425
2426 return QualType(TypeParm, 0);
2427}
2428
John McCalle78aac42010-03-10 03:28:59 +00002429TypeSourceInfo *
2430ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2431 SourceLocation NameLoc,
2432 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002433 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002434 assert(!Name.getAsDependentTemplateName() &&
2435 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002436 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002437
2438 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2439 TemplateSpecializationTypeLoc TL
2440 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002441 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002442 TL.setTemplateNameLoc(NameLoc);
2443 TL.setLAngleLoc(Args.getLAngleLoc());
2444 TL.setRAngleLoc(Args.getRAngleLoc());
2445 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2446 TL.setArgLocInfo(i, Args[i].getLocInfo());
2447 return DI;
2448}
2449
Mike Stump11289f42009-09-09 15:08:12 +00002450QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002451ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002452 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002453 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002454 assert(!Template.getAsDependentTemplateName() &&
2455 "No dependent template names here!");
2456
John McCall6b51f282009-11-23 01:53:49 +00002457 unsigned NumArgs = Args.size();
2458
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002459 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002460 ArgVec.reserve(NumArgs);
2461 for (unsigned i = 0; i != NumArgs; ++i)
2462 ArgVec.push_back(Args[i].getArgument());
2463
John McCall2408e322010-04-27 00:57:59 +00002464 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002465 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002466}
2467
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002468#ifndef NDEBUG
2469static bool hasAnyPackExpansions(const TemplateArgument *Args,
2470 unsigned NumArgs) {
2471 for (unsigned I = 0; I != NumArgs; ++I)
2472 if (Args[I].isPackExpansion())
2473 return true;
2474
2475 return true;
2476}
2477#endif
2478
John McCall0ad16662009-10-29 08:12:44 +00002479QualType
2480ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002481 const TemplateArgument *Args,
2482 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002483 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002484 assert(!Template.getAsDependentTemplateName() &&
2485 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002486 // Look through qualified template names.
2487 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2488 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002489
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002490 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002491 Template.getAsTemplateDecl() &&
2492 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002493 QualType CanonType;
2494 if (!Underlying.isNull())
2495 CanonType = getCanonicalType(Underlying);
2496 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002497 // We can get here with an alias template when the specialization contains
2498 // a pack expansion that does not match up with a parameter pack.
2499 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2500 "Caller must compute aliased type");
2501 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002502 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2503 NumArgs);
2504 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002505
Douglas Gregora8e02e72009-07-28 23:00:59 +00002506 // Allocate the (non-canonical) template specialization type, but don't
2507 // try to unique it: these types typically have location information that
2508 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002509 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2510 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002511 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002512 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002513 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002514 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2515 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002516
Douglas Gregor8bf42052009-02-09 18:46:07 +00002517 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002518 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002519}
2520
Mike Stump11289f42009-09-09 15:08:12 +00002521QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002522ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2523 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002524 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002525 assert(!Template.getAsDependentTemplateName() &&
2526 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002527
Douglas Gregore29139c2011-03-03 17:04:51 +00002528 // Look through qualified template names.
2529 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2530 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002531
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002532 // Build the canonical template specialization type.
2533 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002534 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002535 CanonArgs.reserve(NumArgs);
2536 for (unsigned I = 0; I != NumArgs; ++I)
2537 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2538
2539 // Determine whether this canonical template specialization type already
2540 // exists.
2541 llvm::FoldingSetNodeID ID;
2542 TemplateSpecializationType::Profile(ID, CanonTemplate,
2543 CanonArgs.data(), NumArgs, *this);
2544
2545 void *InsertPos = 0;
2546 TemplateSpecializationType *Spec
2547 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2548
2549 if (!Spec) {
2550 // Allocate a new canonical template specialization type.
2551 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2552 sizeof(TemplateArgument) * NumArgs),
2553 TypeAlignment);
2554 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2555 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002556 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002557 Types.push_back(Spec);
2558 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2559 }
2560
2561 assert(Spec->isDependentType() &&
2562 "Non-dependent template-id type must have a canonical type");
2563 return QualType(Spec, 0);
2564}
2565
2566QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002567ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2568 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002569 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002570 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002571 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002572
2573 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002574 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002575 if (T)
2576 return QualType(T, 0);
2577
Douglas Gregorc42075a2010-02-04 18:10:26 +00002578 QualType Canon = NamedType;
2579 if (!Canon.isCanonical()) {
2580 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002581 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2582 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002583 (void)CheckT;
2584 }
2585
Abramo Bagnara6150c882010-05-11 21:36:43 +00002586 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002587 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002588 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002589 return QualType(T, 0);
2590}
2591
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002592QualType
Jay Foad39c79802011-01-12 09:06:06 +00002593ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002594 llvm::FoldingSetNodeID ID;
2595 ParenType::Profile(ID, InnerType);
2596
2597 void *InsertPos = 0;
2598 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2599 if (T)
2600 return QualType(T, 0);
2601
2602 QualType Canon = InnerType;
2603 if (!Canon.isCanonical()) {
2604 Canon = getCanonicalType(InnerType);
2605 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2606 assert(!CheckT && "Paren canonical type broken");
2607 (void)CheckT;
2608 }
2609
2610 T = new (*this) ParenType(InnerType, Canon);
2611 Types.push_back(T);
2612 ParenTypes.InsertNode(T, InsertPos);
2613 return QualType(T, 0);
2614}
2615
Douglas Gregor02085352010-03-31 20:19:30 +00002616QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2617 NestedNameSpecifier *NNS,
2618 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002619 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002620 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2621
2622 if (Canon.isNull()) {
2623 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002624 ElaboratedTypeKeyword CanonKeyword = Keyword;
2625 if (Keyword == ETK_None)
2626 CanonKeyword = ETK_Typename;
2627
2628 if (CanonNNS != NNS || CanonKeyword != Keyword)
2629 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002630 }
2631
2632 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002633 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002634
2635 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002636 DependentNameType *T
2637 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002638 if (T)
2639 return QualType(T, 0);
2640
Douglas Gregor02085352010-03-31 20:19:30 +00002641 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002642 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002643 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002644 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002645}
2646
Mike Stump11289f42009-09-09 15:08:12 +00002647QualType
John McCallc392f372010-06-11 00:33:02 +00002648ASTContext::getDependentTemplateSpecializationType(
2649 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002650 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002651 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002652 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002653 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002654 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002655 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2656 ArgCopy.push_back(Args[I].getArgument());
2657 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2658 ArgCopy.size(),
2659 ArgCopy.data());
2660}
2661
2662QualType
2663ASTContext::getDependentTemplateSpecializationType(
2664 ElaboratedTypeKeyword Keyword,
2665 NestedNameSpecifier *NNS,
2666 const IdentifierInfo *Name,
2667 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002668 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002669 assert((!NNS || NNS->isDependent()) &&
2670 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002671
Douglas Gregorc42075a2010-02-04 18:10:26 +00002672 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002673 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2674 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002675
2676 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002677 DependentTemplateSpecializationType *T
2678 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002679 if (T)
2680 return QualType(T, 0);
2681
John McCallc392f372010-06-11 00:33:02 +00002682 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002683
John McCallc392f372010-06-11 00:33:02 +00002684 ElaboratedTypeKeyword CanonKeyword = Keyword;
2685 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2686
2687 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002688 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002689 for (unsigned I = 0; I != NumArgs; ++I) {
2690 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2691 if (!CanonArgs[I].structurallyEquals(Args[I]))
2692 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002693 }
2694
John McCallc392f372010-06-11 00:33:02 +00002695 QualType Canon;
2696 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2697 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2698 Name, NumArgs,
2699 CanonArgs.data());
2700
2701 // Find the insert position again.
2702 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2703 }
2704
2705 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2706 sizeof(TemplateArgument) * NumArgs),
2707 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002708 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002709 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002710 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002711 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002712 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002713}
2714
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002715QualType ASTContext::getPackExpansionType(QualType Pattern,
2716 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002717 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002718 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002719
2720 assert(Pattern->containsUnexpandedParameterPack() &&
2721 "Pack expansions must expand one or more parameter packs");
2722 void *InsertPos = 0;
2723 PackExpansionType *T
2724 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2725 if (T)
2726 return QualType(T, 0);
2727
2728 QualType Canon;
2729 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002730 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002731
2732 // Find the insert position again.
2733 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2734 }
2735
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002736 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002737 Types.push_back(T);
2738 PackExpansionTypes.InsertNode(T, InsertPos);
2739 return QualType(T, 0);
2740}
2741
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002742/// CmpProtocolNames - Comparison predicate for sorting protocols
2743/// alphabetically.
2744static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2745 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002746 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002747}
2748
John McCall8b07ec22010-05-15 11:32:37 +00002749static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002750 unsigned NumProtocols) {
2751 if (NumProtocols == 0) return true;
2752
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002753 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2754 return false;
2755
John McCallfc93cf92009-10-22 22:37:11 +00002756 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002757 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2758 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002759 return false;
2760 return true;
2761}
2762
2763static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002764 unsigned &NumProtocols) {
2765 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002766
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002767 // Sort protocols, keyed by name.
2768 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2769
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002770 // Canonicalize.
2771 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2772 Protocols[I] = Protocols[I]->getCanonicalDecl();
2773
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002774 // Remove duplicates.
2775 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2776 NumProtocols = ProtocolsEnd-Protocols;
2777}
2778
John McCall8b07ec22010-05-15 11:32:37 +00002779QualType ASTContext::getObjCObjectType(QualType BaseType,
2780 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002781 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002782 // If the base type is an interface and there aren't any protocols
2783 // to add, then the interface type will do just fine.
2784 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2785 return BaseType;
2786
2787 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002788 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002789 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002790 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002791 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2792 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002793
John McCall8b07ec22010-05-15 11:32:37 +00002794 // Build the canonical type, which has the canonical base type and
2795 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002796 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002797 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2798 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2799 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002800 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002801 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002802 unsigned UniqueCount = NumProtocols;
2803
John McCallfc93cf92009-10-22 22:37:11 +00002804 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002805 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2806 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002807 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002808 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2809 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002810 }
2811
2812 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002813 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2814 }
2815
2816 unsigned Size = sizeof(ObjCObjectTypeImpl);
2817 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2818 void *Mem = Allocate(Size, TypeAlignment);
2819 ObjCObjectTypeImpl *T =
2820 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2821
2822 Types.push_back(T);
2823 ObjCObjectTypes.InsertNode(T, InsertPos);
2824 return QualType(T, 0);
2825}
2826
2827/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2828/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002829QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002830 llvm::FoldingSetNodeID ID;
2831 ObjCObjectPointerType::Profile(ID, ObjectT);
2832
2833 void *InsertPos = 0;
2834 if (ObjCObjectPointerType *QT =
2835 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2836 return QualType(QT, 0);
2837
2838 // Find the canonical object type.
2839 QualType Canonical;
2840 if (!ObjectT.isCanonical()) {
2841 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2842
2843 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002844 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2845 }
2846
Douglas Gregorf85bee62010-02-08 22:59:26 +00002847 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002848 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2849 ObjCObjectPointerType *QType =
2850 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002851
Steve Narofffb4330f2009-06-17 22:40:22 +00002852 Types.push_back(QType);
2853 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002854 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002855}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002856
Douglas Gregor1c283312010-08-11 12:19:30 +00002857/// getObjCInterfaceType - Return the unique reference to the type for the
2858/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002859QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2860 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002861 if (Decl->TypeForDecl)
2862 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002863
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002864 if (PrevDecl) {
2865 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2866 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2867 return QualType(PrevDecl->TypeForDecl, 0);
2868 }
2869
Douglas Gregor7671e532011-12-16 16:34:57 +00002870 // Prefer the definition, if there is one.
2871 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2872 Decl = Def;
2873
Douglas Gregor1c283312010-08-11 12:19:30 +00002874 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2875 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2876 Decl->TypeForDecl = T;
2877 Types.push_back(T);
2878 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002879}
2880
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002881/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2882/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002883/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002884/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002885/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002886QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002887 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002888 if (tofExpr->isTypeDependent()) {
2889 llvm::FoldingSetNodeID ID;
2890 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002891
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002892 void *InsertPos = 0;
2893 DependentTypeOfExprType *Canon
2894 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2895 if (Canon) {
2896 // We already have a "canonical" version of an identical, dependent
2897 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002898 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002899 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002900 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002901 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002902 Canon
2903 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002904 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2905 toe = Canon;
2906 }
2907 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002908 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002909 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002910 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002911 Types.push_back(toe);
2912 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002913}
2914
Steve Naroffa773cd52007-08-01 18:02:17 +00002915/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2916/// TypeOfType AST's. The only motivation to unique these nodes would be
2917/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002918/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002919/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002920QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002921 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002922 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002923 Types.push_back(tot);
2924 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002925}
2926
Anders Carlssonad6bd352009-06-24 21:24:56 +00002927
Anders Carlsson81df7b82009-06-24 19:06:50 +00002928/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2929/// DecltypeType AST's. The only motivation to unique these nodes would be
2930/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002931/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00002932/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00002933QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002934 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002935
2936 // C++0x [temp.type]p2:
2937 // If an expression e involves a template parameter, decltype(e) denotes a
2938 // unique dependent type. Two such decltype-specifiers refer to the same
2939 // type only if their expressions are equivalent (14.5.6.1).
2940 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002941 llvm::FoldingSetNodeID ID;
2942 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002943
Douglas Gregora21f6c32009-07-30 23:36:40 +00002944 void *InsertPos = 0;
2945 DependentDecltypeType *Canon
2946 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2947 if (Canon) {
2948 // We already have a "canonical" version of an equivalent, dependent
2949 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002950 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002951 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002952 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002953 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002954 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002955 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2956 dt = Canon;
2957 }
2958 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00002959 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
2960 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00002961 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002962 Types.push_back(dt);
2963 return QualType(dt, 0);
2964}
2965
Alexis Hunte852b102011-05-24 22:41:36 +00002966/// getUnaryTransformationType - We don't unique these, since the memory
2967/// savings are minimal and these are rare.
2968QualType ASTContext::getUnaryTransformType(QualType BaseType,
2969 QualType UnderlyingType,
2970 UnaryTransformType::UTTKind Kind)
2971 const {
2972 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002973 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2974 Kind,
2975 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00002976 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00002977 Types.push_back(Ty);
2978 return QualType(Ty, 0);
2979}
2980
Richard Smithb2bc2e62011-02-21 20:05:19 +00002981/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002982QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002983 void *InsertPos = 0;
2984 if (!DeducedType.isNull()) {
2985 // Look in the folding set for an existing type.
2986 llvm::FoldingSetNodeID ID;
2987 AutoType::Profile(ID, DeducedType);
2988 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2989 return QualType(AT, 0);
2990 }
2991
2992 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2993 Types.push_back(AT);
2994 if (InsertPos)
2995 AutoTypes.InsertNode(AT, InsertPos);
2996 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002997}
2998
Eli Friedman0dfb8892011-10-06 23:00:33 +00002999/// getAtomicType - Return the uniqued reference to the atomic type for
3000/// the given value type.
3001QualType ASTContext::getAtomicType(QualType T) const {
3002 // Unique pointers, to guarantee there is only one pointer of a particular
3003 // structure.
3004 llvm::FoldingSetNodeID ID;
3005 AtomicType::Profile(ID, T);
3006
3007 void *InsertPos = 0;
3008 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3009 return QualType(AT, 0);
3010
3011 // If the atomic value type isn't canonical, this won't be a canonical type
3012 // either, so fill in the canonical type field.
3013 QualType Canonical;
3014 if (!T.isCanonical()) {
3015 Canonical = getAtomicType(getCanonicalType(T));
3016
3017 // Get the new insert position for the node we care about.
3018 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3019 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3020 }
3021 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3022 Types.push_back(New);
3023 AtomicTypes.InsertNode(New, InsertPos);
3024 return QualType(New, 0);
3025}
3026
Richard Smith02e85f32011-04-14 22:09:26 +00003027/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3028QualType ASTContext::getAutoDeductType() const {
3029 if (AutoDeductTy.isNull())
3030 AutoDeductTy = getAutoType(QualType());
3031 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3032 return AutoDeductTy;
3033}
3034
3035/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3036QualType ASTContext::getAutoRRefDeductType() const {
3037 if (AutoRRefDeductTy.isNull())
3038 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3039 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3040 return AutoRRefDeductTy;
3041}
3042
Chris Lattnerfb072462007-01-23 05:45:31 +00003043/// getTagDeclType - Return the unique reference to the type for the
3044/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003045QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003046 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003047 // FIXME: What is the design on getTagDeclType when it requires casting
3048 // away const? mutable?
3049 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003050}
3051
Mike Stump11289f42009-09-09 15:08:12 +00003052/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3053/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3054/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003055CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003056 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003057}
Chris Lattnerfb072462007-01-23 05:45:31 +00003058
Hans Wennborg27541db2011-10-27 08:29:09 +00003059/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3060CanQualType ASTContext::getIntMaxType() const {
3061 return getFromTargetType(Target->getIntMaxType());
3062}
3063
3064/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3065CanQualType ASTContext::getUIntMaxType() const {
3066 return getFromTargetType(Target->getUIntMaxType());
3067}
3068
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003069/// getSignedWCharType - Return the type of "signed wchar_t".
3070/// Used when in C++, as a GCC extension.
3071QualType ASTContext::getSignedWCharType() const {
3072 // FIXME: derive from "Target" ?
3073 return WCharTy;
3074}
3075
3076/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3077/// Used when in C++, as a GCC extension.
3078QualType ASTContext::getUnsignedWCharType() const {
3079 // FIXME: derive from "Target" ?
3080 return UnsignedIntTy;
3081}
3082
Hans Wennborg27541db2011-10-27 08:29:09 +00003083/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003084/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3085QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003086 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003087}
3088
Chris Lattnera21ad802008-04-02 05:18:44 +00003089//===----------------------------------------------------------------------===//
3090// Type Operators
3091//===----------------------------------------------------------------------===//
3092
Jay Foad39c79802011-01-12 09:06:06 +00003093CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003094 // Push qualifiers into arrays, and then discard any remaining
3095 // qualifiers.
3096 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003097 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003098 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003099 QualType Result;
3100 if (isa<ArrayType>(Ty)) {
3101 Result = getArrayDecayedType(QualType(Ty,0));
3102 } else if (isa<FunctionType>(Ty)) {
3103 Result = getPointerType(QualType(Ty, 0));
3104 } else {
3105 Result = QualType(Ty, 0);
3106 }
3107
3108 return CanQualType::CreateUnsafe(Result);
3109}
3110
John McCall6c9dd522011-01-18 07:41:22 +00003111QualType ASTContext::getUnqualifiedArrayType(QualType type,
3112 Qualifiers &quals) {
3113 SplitQualType splitType = type.getSplitUnqualifiedType();
3114
3115 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3116 // the unqualified desugared type and then drops it on the floor.
3117 // We then have to strip that sugar back off with
3118 // getUnqualifiedDesugaredType(), which is silly.
3119 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003120 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003121
3122 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003123 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003124 quals = splitType.Quals;
3125 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003126 }
3127
John McCall6c9dd522011-01-18 07:41:22 +00003128 // Otherwise, recurse on the array's element type.
3129 QualType elementType = AT->getElementType();
3130 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3131
3132 // If that didn't change the element type, AT has no qualifiers, so we
3133 // can just use the results in splitType.
3134 if (elementType == unqualElementType) {
3135 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003136 quals = splitType.Quals;
3137 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003138 }
3139
3140 // Otherwise, add in the qualifiers from the outermost type, then
3141 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003142 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003143
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003144 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003145 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003146 CAT->getSizeModifier(), 0);
3147 }
3148
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003149 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003150 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003151 }
3152
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003153 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003154 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003155 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003156 VAT->getSizeModifier(),
3157 VAT->getIndexTypeCVRQualifiers(),
3158 VAT->getBracketsRange());
3159 }
3160
3161 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003162 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003163 DSAT->getSizeModifier(), 0,
3164 SourceRange());
3165}
3166
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003167/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3168/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3169/// they point to and return true. If T1 and T2 aren't pointer types
3170/// or pointer-to-member types, or if they are not similar at this
3171/// level, returns false and leaves T1 and T2 unchanged. Top-level
3172/// qualifiers on T1 and T2 are ignored. This function will typically
3173/// be called in a loop that successively "unwraps" pointer and
3174/// pointer-to-member types to compare them at each level.
3175bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3176 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3177 *T2PtrType = T2->getAs<PointerType>();
3178 if (T1PtrType && T2PtrType) {
3179 T1 = T1PtrType->getPointeeType();
3180 T2 = T2PtrType->getPointeeType();
3181 return true;
3182 }
3183
3184 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3185 *T2MPType = T2->getAs<MemberPointerType>();
3186 if (T1MPType && T2MPType &&
3187 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3188 QualType(T2MPType->getClass(), 0))) {
3189 T1 = T1MPType->getPointeeType();
3190 T2 = T2MPType->getPointeeType();
3191 return true;
3192 }
3193
David Blaikiebbafb8a2012-03-11 07:00:24 +00003194 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003195 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3196 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3197 if (T1OPType && T2OPType) {
3198 T1 = T1OPType->getPointeeType();
3199 T2 = T2OPType->getPointeeType();
3200 return true;
3201 }
3202 }
3203
3204 // FIXME: Block pointers, too?
3205
3206 return false;
3207}
3208
Jay Foad39c79802011-01-12 09:06:06 +00003209DeclarationNameInfo
3210ASTContext::getNameForTemplate(TemplateName Name,
3211 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003212 switch (Name.getKind()) {
3213 case TemplateName::QualifiedTemplate:
3214 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003215 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003216 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3217 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003218
John McCalld9dfe3a2011-06-30 08:33:18 +00003219 case TemplateName::OverloadedTemplate: {
3220 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3221 // DNInfo work in progress: CHECKME: what about DNLoc?
3222 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3223 }
3224
3225 case TemplateName::DependentTemplate: {
3226 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003227 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003228 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003229 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3230 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003231 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003232 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3233 // DNInfo work in progress: FIXME: source locations?
3234 DeclarationNameLoc DNLoc;
3235 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3236 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3237 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003238 }
3239 }
3240
John McCalld9dfe3a2011-06-30 08:33:18 +00003241 case TemplateName::SubstTemplateTemplateParm: {
3242 SubstTemplateTemplateParmStorage *subst
3243 = Name.getAsSubstTemplateTemplateParm();
3244 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3245 NameLoc);
3246 }
3247
3248 case TemplateName::SubstTemplateTemplateParmPack: {
3249 SubstTemplateTemplateParmPackStorage *subst
3250 = Name.getAsSubstTemplateTemplateParmPack();
3251 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3252 NameLoc);
3253 }
3254 }
3255
3256 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003257}
3258
Jay Foad39c79802011-01-12 09:06:06 +00003259TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003260 switch (Name.getKind()) {
3261 case TemplateName::QualifiedTemplate:
3262 case TemplateName::Template: {
3263 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003264 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003265 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003266 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3267
3268 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003269 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003270 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003271
John McCalld9dfe3a2011-06-30 08:33:18 +00003272 case TemplateName::OverloadedTemplate:
3273 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003274
John McCalld9dfe3a2011-06-30 08:33:18 +00003275 case TemplateName::DependentTemplate: {
3276 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3277 assert(DTN && "Non-dependent template names must refer to template decls.");
3278 return DTN->CanonicalTemplateName;
3279 }
3280
3281 case TemplateName::SubstTemplateTemplateParm: {
3282 SubstTemplateTemplateParmStorage *subst
3283 = Name.getAsSubstTemplateTemplateParm();
3284 return getCanonicalTemplateName(subst->getReplacement());
3285 }
3286
3287 case TemplateName::SubstTemplateTemplateParmPack: {
3288 SubstTemplateTemplateParmPackStorage *subst
3289 = Name.getAsSubstTemplateTemplateParmPack();
3290 TemplateTemplateParmDecl *canonParameter
3291 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3292 TemplateArgument canonArgPack
3293 = getCanonicalTemplateArgument(subst->getArgumentPack());
3294 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3295 }
3296 }
3297
3298 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003299}
3300
Douglas Gregoradee3e32009-11-11 23:06:43 +00003301bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3302 X = getCanonicalTemplateName(X);
3303 Y = getCanonicalTemplateName(Y);
3304 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3305}
3306
Mike Stump11289f42009-09-09 15:08:12 +00003307TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003308ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003309 switch (Arg.getKind()) {
3310 case TemplateArgument::Null:
3311 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003312
Douglas Gregora8e02e72009-07-28 23:00:59 +00003313 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003314 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003315
Douglas Gregora8e02e72009-07-28 23:00:59 +00003316 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003317 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003318
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003319 case TemplateArgument::Template:
3320 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003321
3322 case TemplateArgument::TemplateExpansion:
3323 return TemplateArgument(getCanonicalTemplateName(
3324 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003325 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003326
Douglas Gregora8e02e72009-07-28 23:00:59 +00003327 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003328 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003329 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003330
Douglas Gregora8e02e72009-07-28 23:00:59 +00003331 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003332 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003333
Douglas Gregora8e02e72009-07-28 23:00:59 +00003334 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003335 if (Arg.pack_size() == 0)
3336 return Arg;
3337
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003338 TemplateArgument *CanonArgs
3339 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003340 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003341 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003342 AEnd = Arg.pack_end();
3343 A != AEnd; (void)++A, ++Idx)
3344 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003345
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003346 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003347 }
3348 }
3349
3350 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003351 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003352}
3353
Douglas Gregor333489b2009-03-27 23:10:48 +00003354NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003355ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003356 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003357 return 0;
3358
3359 switch (NNS->getKind()) {
3360 case NestedNameSpecifier::Identifier:
3361 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003362 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003363 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3364 NNS->getAsIdentifier());
3365
3366 case NestedNameSpecifier::Namespace:
3367 // A namespace is canonical; build a nested-name-specifier with
3368 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003369 return NestedNameSpecifier::Create(*this, 0,
3370 NNS->getAsNamespace()->getOriginalNamespace());
3371
3372 case NestedNameSpecifier::NamespaceAlias:
3373 // A namespace is canonical; build a nested-name-specifier with
3374 // this namespace and no prefix.
3375 return NestedNameSpecifier::Create(*this, 0,
3376 NNS->getAsNamespaceAlias()->getNamespace()
3377 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003378
3379 case NestedNameSpecifier::TypeSpec:
3380 case NestedNameSpecifier::TypeSpecWithTemplate: {
3381 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003382
3383 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3384 // break it apart into its prefix and identifier, then reconsititute those
3385 // as the canonical nested-name-specifier. This is required to canonicalize
3386 // a dependent nested-name-specifier involving typedefs of dependent-name
3387 // types, e.g.,
3388 // typedef typename T::type T1;
3389 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003390 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3391 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003392 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003393
Eli Friedman5358a0a2012-03-03 04:09:56 +00003394 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3395 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3396 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003397 return NestedNameSpecifier::Create(*this, 0, false,
3398 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003399 }
3400
3401 case NestedNameSpecifier::Global:
3402 // The global specifier is canonical and unique.
3403 return NNS;
3404 }
3405
David Blaikie8a40f702012-01-17 06:56:22 +00003406 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003407}
3408
Chris Lattner7adf0762008-08-04 07:31:14 +00003409
Jay Foad39c79802011-01-12 09:06:06 +00003410const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003411 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003412 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003413 // Handle the common positive case fast.
3414 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3415 return AT;
3416 }
Mike Stump11289f42009-09-09 15:08:12 +00003417
John McCall8ccfcb52009-09-24 19:53:00 +00003418 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003419 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003420 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003421
John McCall8ccfcb52009-09-24 19:53:00 +00003422 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003423 // implements C99 6.7.3p8: "If the specification of an array type includes
3424 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003425
Chris Lattner7adf0762008-08-04 07:31:14 +00003426 // If we get here, we either have type qualifiers on the type, or we have
3427 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003428 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003429
John McCall33ddac02011-01-19 10:06:00 +00003430 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003431 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003432
Chris Lattner7adf0762008-08-04 07:31:14 +00003433 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003434 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003435 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003436 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003437
Chris Lattner7adf0762008-08-04 07:31:14 +00003438 // Otherwise, we have an array and we have qualifiers on it. Push the
3439 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003440 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003441
Chris Lattner7adf0762008-08-04 07:31:14 +00003442 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3443 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3444 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003445 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003446 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3447 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3448 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003449 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003450
Mike Stump11289f42009-09-09 15:08:12 +00003451 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003452 = dyn_cast<DependentSizedArrayType>(ATy))
3453 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003454 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003455 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003456 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003457 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003458 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003459
Chris Lattner7adf0762008-08-04 07:31:14 +00003460 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003461 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003462 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003463 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003464 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003465 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003466}
3467
Douglas Gregor84280642011-07-12 04:42:08 +00003468QualType ASTContext::getAdjustedParameterType(QualType T) {
3469 // C99 6.7.5.3p7:
3470 // A declaration of a parameter as "array of type" shall be
3471 // adjusted to "qualified pointer to type", where the type
3472 // qualifiers (if any) are those specified within the [ and ] of
3473 // the array type derivation.
3474 if (T->isArrayType())
3475 return getArrayDecayedType(T);
3476
3477 // C99 6.7.5.3p8:
3478 // A declaration of a parameter as "function returning type"
3479 // shall be adjusted to "pointer to function returning type", as
3480 // in 6.3.2.1.
3481 if (T->isFunctionType())
3482 return getPointerType(T);
3483
3484 return T;
3485}
3486
3487QualType ASTContext::getSignatureParameterType(QualType T) {
3488 T = getVariableArrayDecayedType(T);
3489 T = getAdjustedParameterType(T);
3490 return T.getUnqualifiedType();
3491}
3492
Chris Lattnera21ad802008-04-02 05:18:44 +00003493/// getArrayDecayedType - Return the properly qualified result of decaying the
3494/// specified array type to a pointer. This operation is non-trivial when
3495/// handling typedefs etc. The canonical type of "T" must be an array type,
3496/// this returns a pointer to a properly qualified element of the array.
3497///
3498/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003499QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003500 // Get the element type with 'getAsArrayType' so that we don't lose any
3501 // typedefs in the element type of the array. This also handles propagation
3502 // of type qualifiers from the array type into the element type if present
3503 // (C99 6.7.3p8).
3504 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3505 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003506
Chris Lattner7adf0762008-08-04 07:31:14 +00003507 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003508
3509 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003510 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003511}
3512
John McCall33ddac02011-01-19 10:06:00 +00003513QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3514 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003515}
3516
John McCall33ddac02011-01-19 10:06:00 +00003517QualType ASTContext::getBaseElementType(QualType type) const {
3518 Qualifiers qs;
3519 while (true) {
3520 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003521 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003522 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003523
John McCall33ddac02011-01-19 10:06:00 +00003524 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003525 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003526 }
Mike Stump11289f42009-09-09 15:08:12 +00003527
John McCall33ddac02011-01-19 10:06:00 +00003528 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003529}
3530
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003531/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003532uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003533ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3534 uint64_t ElementCount = 1;
3535 do {
3536 ElementCount *= CA->getSize().getZExtValue();
3537 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3538 } while (CA);
3539 return ElementCount;
3540}
3541
Steve Naroff0af91202007-04-27 21:51:21 +00003542/// getFloatingRank - Return a relative rank for floating point types.
3543/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003544static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003545 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003546 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003547
John McCall9dd450b2009-09-21 23:43:11 +00003548 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3549 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003550 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003551 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003552 case BuiltinType::Float: return FloatRank;
3553 case BuiltinType::Double: return DoubleRank;
3554 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003555 }
3556}
3557
Mike Stump11289f42009-09-09 15:08:12 +00003558/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3559/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003560/// 'typeDomain' is a real floating point or complex type.
3561/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003562QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3563 QualType Domain) const {
3564 FloatingRank EltRank = getFloatingRank(Size);
3565 if (Domain->isComplexType()) {
3566 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003567 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003568 case FloatRank: return FloatComplexTy;
3569 case DoubleRank: return DoubleComplexTy;
3570 case LongDoubleRank: return LongDoubleComplexTy;
3571 }
Steve Naroff0af91202007-04-27 21:51:21 +00003572 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003573
3574 assert(Domain->isRealFloatingType() && "Unknown domain!");
3575 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003576 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003577 case FloatRank: return FloatTy;
3578 case DoubleRank: return DoubleTy;
3579 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003580 }
David Blaikief47fa302012-01-17 02:30:50 +00003581 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003582}
3583
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003584/// getFloatingTypeOrder - Compare the rank of the two specified floating
3585/// point types, ignoring the domain of the type (i.e. 'double' ==
3586/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003587/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003588int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003589 FloatingRank LHSR = getFloatingRank(LHS);
3590 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003591
Chris Lattnerb90739d2008-04-06 23:38:49 +00003592 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003593 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003594 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003595 return 1;
3596 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003597}
3598
Chris Lattner76a00cf2008-04-06 22:59:24 +00003599/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3600/// routine will assert if passed a built-in type that isn't an integer or enum,
3601/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003602unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003603 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003604
Chris Lattner76a00cf2008-04-06 22:59:24 +00003605 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003606 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003607 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003608 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003609 case BuiltinType::Char_S:
3610 case BuiltinType::Char_U:
3611 case BuiltinType::SChar:
3612 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003613 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003614 case BuiltinType::Short:
3615 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003616 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003617 case BuiltinType::Int:
3618 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003619 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003620 case BuiltinType::Long:
3621 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003622 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003623 case BuiltinType::LongLong:
3624 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003625 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003626 case BuiltinType::Int128:
3627 case BuiltinType::UInt128:
3628 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003629 }
3630}
3631
Eli Friedman629ffb92009-08-20 04:21:42 +00003632/// \brief Whether this is a promotable bitfield reference according
3633/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3634///
3635/// \returns the type this bit-field will promote to, or NULL if no
3636/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003637QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003638 if (E->isTypeDependent() || E->isValueDependent())
3639 return QualType();
3640
Eli Friedman629ffb92009-08-20 04:21:42 +00003641 FieldDecl *Field = E->getBitField();
3642 if (!Field)
3643 return QualType();
3644
3645 QualType FT = Field->getType();
3646
Richard Smithcaf33902011-10-10 18:28:20 +00003647 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003648 uint64_t IntSize = getTypeSize(IntTy);
3649 // GCC extension compatibility: if the bit-field size is less than or equal
3650 // to the size of int, it gets promoted no matter what its type is.
3651 // For instance, unsigned long bf : 4 gets promoted to signed int.
3652 if (BitWidth < IntSize)
3653 return IntTy;
3654
3655 if (BitWidth == IntSize)
3656 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3657
3658 // Types bigger than int are not subject to promotions, and therefore act
3659 // like the base type.
3660 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3661 // is ridiculous.
3662 return QualType();
3663}
3664
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003665/// getPromotedIntegerType - Returns the type that Promotable will
3666/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3667/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003668QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003669 assert(!Promotable.isNull());
3670 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003671 if (const EnumType *ET = Promotable->getAs<EnumType>())
3672 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003673
3674 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3675 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3676 // (3.9.1) can be converted to a prvalue of the first of the following
3677 // types that can represent all the values of its underlying type:
3678 // int, unsigned int, long int, unsigned long int, long long int, or
3679 // unsigned long long int [...]
3680 // FIXME: Is there some better way to compute this?
3681 if (BT->getKind() == BuiltinType::WChar_S ||
3682 BT->getKind() == BuiltinType::WChar_U ||
3683 BT->getKind() == BuiltinType::Char16 ||
3684 BT->getKind() == BuiltinType::Char32) {
3685 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3686 uint64_t FromSize = getTypeSize(BT);
3687 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3688 LongLongTy, UnsignedLongLongTy };
3689 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3690 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3691 if (FromSize < ToSize ||
3692 (FromSize == ToSize &&
3693 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3694 return PromoteTypes[Idx];
3695 }
3696 llvm_unreachable("char type should fit into long long");
3697 }
3698 }
3699
3700 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003701 if (Promotable->isSignedIntegerType())
3702 return IntTy;
3703 uint64_t PromotableSize = getTypeSize(Promotable);
3704 uint64_t IntSize = getTypeSize(IntTy);
3705 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3706 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3707}
3708
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003709/// \brief Recurses in pointer/array types until it finds an objc retainable
3710/// type and returns its ownership.
3711Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3712 while (!T.isNull()) {
3713 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3714 return T.getObjCLifetime();
3715 if (T->isArrayType())
3716 T = getBaseElementType(T);
3717 else if (const PointerType *PT = T->getAs<PointerType>())
3718 T = PT->getPointeeType();
3719 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003720 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003721 else
3722 break;
3723 }
3724
3725 return Qualifiers::OCL_None;
3726}
3727
Mike Stump11289f42009-09-09 15:08:12 +00003728/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003729/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003730/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003731int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003732 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3733 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003734 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003735
Chris Lattner76a00cf2008-04-06 22:59:24 +00003736 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3737 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003738
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003739 unsigned LHSRank = getIntegerRank(LHSC);
3740 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003741
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003742 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3743 if (LHSRank == RHSRank) return 0;
3744 return LHSRank > RHSRank ? 1 : -1;
3745 }
Mike Stump11289f42009-09-09 15:08:12 +00003746
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003747 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3748 if (LHSUnsigned) {
3749 // If the unsigned [LHS] type is larger, return it.
3750 if (LHSRank >= RHSRank)
3751 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003752
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003753 // If the signed type can represent all values of the unsigned type, it
3754 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003755 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003756 return -1;
3757 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003758
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003759 // If the unsigned [RHS] type is larger, return it.
3760 if (RHSRank >= LHSRank)
3761 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003762
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003763 // If the signed type can represent all values of the unsigned type, it
3764 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003765 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003766 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003767}
Anders Carlsson98f07902007-08-17 05:31:46 +00003768
Anders Carlsson6d417272009-11-14 21:45:58 +00003769static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003770CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3771 DeclContext *DC, IdentifierInfo *Id) {
3772 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003773 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003774 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003775 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003776 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003777}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003778
Mike Stump11289f42009-09-09 15:08:12 +00003779// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003780QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003781 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003782 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003783 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003784 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003785 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003786
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003787 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003788
Anders Carlsson98f07902007-08-17 05:31:46 +00003789 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003790 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003791 // int flags;
3792 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003793 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003794 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003795 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003796 FieldTypes[3] = LongTy;
3797
Anders Carlsson98f07902007-08-17 05:31:46 +00003798 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003799 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003800 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003801 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003802 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003803 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003804 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003805 /*Mutable=*/false,
3806 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003807 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003808 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003809 }
3810
Douglas Gregord5058122010-02-11 01:19:42 +00003811 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003812 }
Mike Stump11289f42009-09-09 15:08:12 +00003813
Anders Carlsson98f07902007-08-17 05:31:46 +00003814 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003815}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003816
Douglas Gregor512b0772009-04-23 22:29:11 +00003817void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003818 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003819 assert(Rec && "Invalid CFConstantStringType");
3820 CFConstantStringTypeDecl = Rec->getDecl();
3821}
3822
Jay Foad39c79802011-01-12 09:06:06 +00003823QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003824 if (BlockDescriptorType)
3825 return getTagDeclType(BlockDescriptorType);
3826
3827 RecordDecl *T;
3828 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003829 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003830 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003831 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003832
3833 QualType FieldTypes[] = {
3834 UnsignedLongTy,
3835 UnsignedLongTy,
3836 };
3837
3838 const char *FieldNames[] = {
3839 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003840 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003841 };
3842
3843 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003844 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003845 SourceLocation(),
3846 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003847 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003848 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003849 /*Mutable=*/false,
3850 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003851 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003852 T->addDecl(Field);
3853 }
3854
Douglas Gregord5058122010-02-11 01:19:42 +00003855 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003856
3857 BlockDescriptorType = T;
3858
3859 return getTagDeclType(BlockDescriptorType);
3860}
3861
Jay Foad39c79802011-01-12 09:06:06 +00003862QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003863 if (BlockDescriptorExtendedType)
3864 return getTagDeclType(BlockDescriptorExtendedType);
3865
3866 RecordDecl *T;
3867 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003868 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003869 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003870 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003871
3872 QualType FieldTypes[] = {
3873 UnsignedLongTy,
3874 UnsignedLongTy,
3875 getPointerType(VoidPtrTy),
3876 getPointerType(VoidPtrTy)
3877 };
3878
3879 const char *FieldNames[] = {
3880 "reserved",
3881 "Size",
3882 "CopyFuncPtr",
3883 "DestroyFuncPtr"
3884 };
3885
3886 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003887 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003888 SourceLocation(),
3889 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003890 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003891 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003892 /*Mutable=*/false,
3893 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003894 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003895 T->addDecl(Field);
3896 }
3897
Douglas Gregord5058122010-02-11 01:19:42 +00003898 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003899
3900 BlockDescriptorExtendedType = T;
3901
3902 return getTagDeclType(BlockDescriptorExtendedType);
3903}
3904
Jay Foad39c79802011-01-12 09:06:06 +00003905bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003906 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003907 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003908 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003909 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3910 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003911 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003912
3913 }
3914 }
Mike Stump94967902009-10-21 18:16:27 +00003915 return false;
3916}
3917
Jay Foad39c79802011-01-12 09:06:06 +00003918QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003919ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003920 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003921 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003922 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003923 // unsigned int __flags;
3924 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003925 // void *__copy_helper; // as needed
3926 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003927 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003928 // } *
3929
Mike Stump94967902009-10-21 18:16:27 +00003930 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3931
3932 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003933 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003934 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3935 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003936 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003937 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003938 T->startDefinition();
3939 QualType Int32Ty = IntTy;
3940 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3941 QualType FieldTypes[] = {
3942 getPointerType(VoidPtrTy),
3943 getPointerType(getTagDeclType(T)),
3944 Int32Ty,
3945 Int32Ty,
3946 getPointerType(VoidPtrTy),
3947 getPointerType(VoidPtrTy),
3948 Ty
3949 };
3950
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003951 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003952 "__isa",
3953 "__forwarding",
3954 "__flags",
3955 "__size",
3956 "__copy_helper",
3957 "__destroy_helper",
3958 DeclName,
3959 };
3960
3961 for (size_t i = 0; i < 7; ++i) {
3962 if (!HasCopyAndDispose && i >=4 && i <= 5)
3963 continue;
3964 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003965 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003966 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003967 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003968 /*BitWidth=*/0, /*Mutable=*/false,
3969 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003970 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003971 T->addDecl(Field);
3972 }
3973
Douglas Gregord5058122010-02-11 01:19:42 +00003974 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003975
3976 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003977}
3978
Douglas Gregorbab8a962011-09-08 01:46:34 +00003979TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3980 if (!ObjCInstanceTypeDecl)
3981 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3982 getTranslationUnitDecl(),
3983 SourceLocation(),
3984 SourceLocation(),
3985 &Idents.get("instancetype"),
3986 getTrivialTypeSourceInfo(getObjCIdType()));
3987 return ObjCInstanceTypeDecl;
3988}
3989
Anders Carlsson18acd442007-10-29 06:33:42 +00003990// This returns true if a type has been typedefed to BOOL:
3991// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003992static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003993 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003994 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3995 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003996
Anders Carlssond8499822007-10-29 05:01:08 +00003997 return false;
3998}
3999
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004000/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004001/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004002CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004003 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4004 return CharUnits::Zero();
4005
Ken Dyck40775002010-01-11 17:06:35 +00004006 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004007
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004008 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004009 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004010 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004011 // Treat arrays as pointers, since that's how they're passed in.
4012 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004013 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004014 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004015}
4016
4017static inline
4018std::string charUnitsToString(const CharUnits &CU) {
4019 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004020}
4021
John McCall351762c2011-02-07 10:33:21 +00004022/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004023/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004024std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4025 std::string S;
4026
David Chisnall950a9512009-11-17 19:33:30 +00004027 const BlockDecl *Decl = Expr->getBlockDecl();
4028 QualType BlockTy =
4029 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4030 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004031 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004032 // Compute size of all parameters.
4033 // Start with computing size of a pointer in number of bytes.
4034 // FIXME: There might(should) be a better way of doing this computation!
4035 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004036 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4037 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004038 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004039 E = Decl->param_end(); PI != E; ++PI) {
4040 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004041 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00004042 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004043 ParmOffset += sz;
4044 }
4045 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004046 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004047 // Block pointer and offset.
4048 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004049
4050 // Argument types.
4051 ParmOffset = PtrSize;
4052 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4053 Decl->param_end(); PI != E; ++PI) {
4054 ParmVarDecl *PVDecl = *PI;
4055 QualType PType = PVDecl->getOriginalType();
4056 if (const ArrayType *AT =
4057 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4058 // Use array's original type only if it has known number of
4059 // elements.
4060 if (!isa<ConstantArrayType>(AT))
4061 PType = PVDecl->getType();
4062 } else if (PType->isFunctionType())
4063 PType = PVDecl->getType();
4064 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004065 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004066 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004067 }
John McCall351762c2011-02-07 10:33:21 +00004068
4069 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004070}
4071
Douglas Gregora9d84932011-05-27 01:19:52 +00004072bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004073 std::string& S) {
4074 // Encode result type.
4075 getObjCEncodingForType(Decl->getResultType(), S);
4076 CharUnits ParmOffset;
4077 // Compute size of all parameters.
4078 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4079 E = Decl->param_end(); PI != E; ++PI) {
4080 QualType PType = (*PI)->getType();
4081 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004082 if (sz.isZero())
4083 return true;
4084
David Chisnall50e4eba2010-12-30 14:05:53 +00004085 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004086 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004087 ParmOffset += sz;
4088 }
4089 S += charUnitsToString(ParmOffset);
4090 ParmOffset = CharUnits::Zero();
4091
4092 // Argument types.
4093 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4094 E = Decl->param_end(); PI != E; ++PI) {
4095 ParmVarDecl *PVDecl = *PI;
4096 QualType PType = PVDecl->getOriginalType();
4097 if (const ArrayType *AT =
4098 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4099 // Use array's original type only if it has known number of
4100 // elements.
4101 if (!isa<ConstantArrayType>(AT))
4102 PType = PVDecl->getType();
4103 } else if (PType->isFunctionType())
4104 PType = PVDecl->getType();
4105 getObjCEncodingForType(PType, S);
4106 S += charUnitsToString(ParmOffset);
4107 ParmOffset += getObjCEncodingTypeSize(PType);
4108 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004109
4110 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004111}
4112
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004113/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4114/// method parameter or return type. If Extended, include class names and
4115/// block object types.
4116void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4117 QualType T, std::string& S,
4118 bool Extended) const {
4119 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4120 getObjCEncodingForTypeQualifier(QT, S);
4121 // Encode parameter type.
4122 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4123 true /*OutermostType*/,
4124 false /*EncodingProperty*/,
4125 false /*StructField*/,
4126 Extended /*EncodeBlockParameters*/,
4127 Extended /*EncodeClassNames*/);
4128}
4129
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004130/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004131/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004132bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004133 std::string& S,
4134 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004135 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004136 // Encode return type.
4137 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4138 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004139 // Compute size of all parameters.
4140 // Start with computing size of a pointer in number of bytes.
4141 // FIXME: There might(should) be a better way of doing this computation!
4142 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004143 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004144 // The first two arguments (self and _cmd) are pointers; account for
4145 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004146 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004147 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004148 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004149 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004150 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004151 if (sz.isZero())
4152 return true;
4153
Ken Dyck40775002010-01-11 17:06:35 +00004154 assert (sz.isPositive() &&
4155 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004156 ParmOffset += sz;
4157 }
Ken Dyck40775002010-01-11 17:06:35 +00004158 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004159 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004160 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004161
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004162 // Argument types.
4163 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004164 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004165 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004166 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004167 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004168 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004169 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4170 // Use array's original type only if it has known number of
4171 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004172 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004173 PType = PVDecl->getType();
4174 } else if (PType->isFunctionType())
4175 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004176 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4177 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004178 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004179 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004180 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004181
4182 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004183}
4184
Daniel Dunbar4932b362008-08-28 04:38:10 +00004185/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004186/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004187/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4188/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004189/// Property attributes are stored as a comma-delimited C string. The simple
4190/// attributes readonly and bycopy are encoded as single characters. The
4191/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4192/// encoded as single characters, followed by an identifier. Property types
4193/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004194/// these attributes are defined by the following enumeration:
4195/// @code
4196/// enum PropertyAttributes {
4197/// kPropertyReadOnly = 'R', // property is read-only.
4198/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4199/// kPropertyByref = '&', // property is a reference to the value last assigned
4200/// kPropertyDynamic = 'D', // property is dynamic
4201/// kPropertyGetter = 'G', // followed by getter selector name
4202/// kPropertySetter = 'S', // followed by setter selector name
4203/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004204/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004205/// kPropertyWeak = 'W' // 'weak' property
4206/// kPropertyStrong = 'P' // property GC'able
4207/// kPropertyNonAtomic = 'N' // property non-atomic
4208/// };
4209/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004210void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004211 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004212 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004213 // Collect information from the property implementation decl(s).
4214 bool Dynamic = false;
4215 ObjCPropertyImplDecl *SynthesizePID = 0;
4216
4217 // FIXME: Duplicated code due to poor abstraction.
4218 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004219 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004220 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4221 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004222 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004223 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004224 ObjCPropertyImplDecl *PID = *i;
4225 if (PID->getPropertyDecl() == PD) {
4226 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4227 Dynamic = true;
4228 } else {
4229 SynthesizePID = PID;
4230 }
4231 }
4232 }
4233 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004234 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004235 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004236 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004237 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004238 ObjCPropertyImplDecl *PID = *i;
4239 if (PID->getPropertyDecl() == PD) {
4240 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4241 Dynamic = true;
4242 } else {
4243 SynthesizePID = PID;
4244 }
4245 }
Mike Stump11289f42009-09-09 15:08:12 +00004246 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004247 }
4248 }
4249
4250 // FIXME: This is not very efficient.
4251 S = "T";
4252
4253 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004254 // GCC has some special rules regarding encoding of properties which
4255 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004256 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004257 true /* outermost type */,
4258 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004259
4260 if (PD->isReadOnly()) {
4261 S += ",R";
4262 } else {
4263 switch (PD->getSetterKind()) {
4264 case ObjCPropertyDecl::Assign: break;
4265 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004266 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004267 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004268 }
4269 }
4270
4271 // It really isn't clear at all what this means, since properties
4272 // are "dynamic by default".
4273 if (Dynamic)
4274 S += ",D";
4275
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004276 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4277 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004278
Daniel Dunbar4932b362008-08-28 04:38:10 +00004279 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4280 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004281 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004282 }
4283
4284 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4285 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004286 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004287 }
4288
4289 if (SynthesizePID) {
4290 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4291 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004292 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004293 }
4294
4295 // FIXME: OBJCGC: weak & strong
4296}
4297
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004298/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004299/// Another legacy compatibility encoding: 32-bit longs are encoded as
4300/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004301/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4302///
4303void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004304 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004305 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004306 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004307 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004308 else
Jay Foad39c79802011-01-12 09:06:06 +00004309 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004310 PointeeTy = IntTy;
4311 }
4312 }
4313}
4314
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004315void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004316 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004317 // We follow the behavior of gcc, expanding structures which are
4318 // directly pointed to, and expanding embedded structures. Note that
4319 // these rules are sufficient to prevent recursive encoding of the
4320 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004321 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004322 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004323}
4324
David Chisnallb190a2c2010-06-04 01:10:52 +00004325static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4326 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004327 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004328 case BuiltinType::Void: return 'v';
4329 case BuiltinType::Bool: return 'B';
4330 case BuiltinType::Char_U:
4331 case BuiltinType::UChar: return 'C';
4332 case BuiltinType::UShort: return 'S';
4333 case BuiltinType::UInt: return 'I';
4334 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004335 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004336 case BuiltinType::UInt128: return 'T';
4337 case BuiltinType::ULongLong: return 'Q';
4338 case BuiltinType::Char_S:
4339 case BuiltinType::SChar: return 'c';
4340 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004341 case BuiltinType::WChar_S:
4342 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004343 case BuiltinType::Int: return 'i';
4344 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004345 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004346 case BuiltinType::LongLong: return 'q';
4347 case BuiltinType::Int128: return 't';
4348 case BuiltinType::Float: return 'f';
4349 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004350 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004351 }
4352}
4353
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004354static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4355 EnumDecl *Enum = ET->getDecl();
4356
4357 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4358 if (!Enum->isFixed())
4359 return 'i';
4360
4361 // The encoding of a fixed enum type matches its fixed underlying type.
4362 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4363}
4364
Jay Foad39c79802011-01-12 09:06:06 +00004365static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004366 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004367 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004368 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004369 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4370 // The GNU runtime requires more information; bitfields are encoded as b,
4371 // then the offset (in bits) of the first element, then the type of the
4372 // bitfield, then the size in bits. For example, in this structure:
4373 //
4374 // struct
4375 // {
4376 // int integer;
4377 // int flags:2;
4378 // };
4379 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4380 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4381 // information is not especially sensible, but we're stuck with it for
4382 // compatibility with GCC, although providing it breaks anything that
4383 // actually uses runtime introspection and wants to work on both runtimes...
David Blaikiebbafb8a2012-03-11 07:00:24 +00004384 if (!Ctx->getLangOpts().NeXTRuntime) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004385 const RecordDecl *RD = FD->getParent();
4386 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004387 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004388 if (const EnumType *ET = T->getAs<EnumType>())
4389 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004390 else
Jay Foad39c79802011-01-12 09:06:06 +00004391 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004392 }
Richard Smithcaf33902011-10-10 18:28:20 +00004393 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004394}
4395
Daniel Dunbar07d07852009-10-18 21:17:35 +00004396// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004397void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4398 bool ExpandPointedToStructures,
4399 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004400 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004401 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004402 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004403 bool StructField,
4404 bool EncodeBlockParameters,
4405 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004406 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004407 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004408 return EncodeBitField(this, S, T, FD);
4409 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004410 return;
4411 }
Mike Stump11289f42009-09-09 15:08:12 +00004412
John McCall9dd450b2009-09-21 23:43:11 +00004413 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004414 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004415 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004416 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004417 return;
4418 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004419
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004420 // encoding for pointer or r3eference types.
4421 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004422 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004423 if (PT->isObjCSelType()) {
4424 S += ':';
4425 return;
4426 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004427 PointeeTy = PT->getPointeeType();
4428 }
4429 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4430 PointeeTy = RT->getPointeeType();
4431 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004432 bool isReadOnly = false;
4433 // For historical/compatibility reasons, the read-only qualifier of the
4434 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4435 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004436 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004437 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004438 if (OutermostType && T.isConstQualified()) {
4439 isReadOnly = true;
4440 S += 'r';
4441 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004442 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004443 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004444 while (P->getAs<PointerType>())
4445 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004446 if (P.isConstQualified()) {
4447 isReadOnly = true;
4448 S += 'r';
4449 }
4450 }
4451 if (isReadOnly) {
4452 // Another legacy compatibility encoding. Some ObjC qualifier and type
4453 // combinations need to be rearranged.
4454 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004455 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004456 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004457 }
Mike Stump11289f42009-09-09 15:08:12 +00004458
Anders Carlssond8499822007-10-29 05:01:08 +00004459 if (PointeeTy->isCharType()) {
4460 // char pointer types should be encoded as '*' unless it is a
4461 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004462 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004463 S += '*';
4464 return;
4465 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004466 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004467 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4468 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4469 S += '#';
4470 return;
4471 }
4472 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4473 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4474 S += '@';
4475 return;
4476 }
4477 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004478 }
Anders Carlssond8499822007-10-29 05:01:08 +00004479 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004480 getLegacyIntegralTypeEncoding(PointeeTy);
4481
Mike Stump11289f42009-09-09 15:08:12 +00004482 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004483 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004484 return;
4485 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004486
Chris Lattnere7cabb92009-07-13 00:10:46 +00004487 if (const ArrayType *AT =
4488 // Ignore type qualifiers etc.
4489 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004490 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004491 // Incomplete arrays are encoded as a pointer to the array element.
4492 S += '^';
4493
Mike Stump11289f42009-09-09 15:08:12 +00004494 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004495 false, ExpandStructures, FD);
4496 } else {
4497 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004498
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004499 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4500 if (getTypeSize(CAT->getElementType()) == 0)
4501 S += '0';
4502 else
4503 S += llvm::utostr(CAT->getSize().getZExtValue());
4504 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004505 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004506 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4507 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004508 S += '0';
4509 }
Mike Stump11289f42009-09-09 15:08:12 +00004510
4511 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004512 false, ExpandStructures, FD);
4513 S += ']';
4514 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004515 return;
4516 }
Mike Stump11289f42009-09-09 15:08:12 +00004517
John McCall9dd450b2009-09-21 23:43:11 +00004518 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004519 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004520 return;
4521 }
Mike Stump11289f42009-09-09 15:08:12 +00004522
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004523 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004524 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004525 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004526 // Anonymous structures print as '?'
4527 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4528 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004529 if (ClassTemplateSpecializationDecl *Spec
4530 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4531 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4532 std::string TemplateArgsStr
4533 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004534 TemplateArgs.data(),
4535 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004536 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004537
4538 S += TemplateArgsStr;
4539 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004540 } else {
4541 S += '?';
4542 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004543 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004544 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004545 if (!RDecl->isUnion()) {
4546 getObjCEncodingForStructureImpl(RDecl, S, FD);
4547 } else {
4548 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4549 FieldEnd = RDecl->field_end();
4550 Field != FieldEnd; ++Field) {
4551 if (FD) {
4552 S += '"';
4553 S += Field->getNameAsString();
4554 S += '"';
4555 }
Mike Stump11289f42009-09-09 15:08:12 +00004556
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004557 // Special case bit-fields.
4558 if (Field->isBitField()) {
4559 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4560 (*Field));
4561 } else {
4562 QualType qt = Field->getType();
4563 getLegacyIntegralTypeEncoding(qt);
4564 getObjCEncodingForTypeImpl(qt, S, false, true,
4565 FD, /*OutermostType*/false,
4566 /*EncodingProperty*/false,
4567 /*StructField*/true);
4568 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004569 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004570 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004571 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004572 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004573 return;
4574 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004575
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004576 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004577 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004578 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004579 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004580 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004581 return;
4582 }
Mike Stump11289f42009-09-09 15:08:12 +00004583
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004584 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004585 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004586 if (EncodeBlockParameters) {
4587 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4588
4589 S += '<';
4590 // Block return type
4591 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4592 ExpandPointedToStructures, ExpandStructures,
4593 FD,
4594 false /* OutermostType */,
4595 EncodingProperty,
4596 false /* StructField */,
4597 EncodeBlockParameters,
4598 EncodeClassNames);
4599 // Block self
4600 S += "@?";
4601 // Block parameters
4602 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4603 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4604 E = FPT->arg_type_end(); I && (I != E); ++I) {
4605 getObjCEncodingForTypeImpl(*I, S,
4606 ExpandPointedToStructures,
4607 ExpandStructures,
4608 FD,
4609 false /* OutermostType */,
4610 EncodingProperty,
4611 false /* StructField */,
4612 EncodeBlockParameters,
4613 EncodeClassNames);
4614 }
4615 }
4616 S += '>';
4617 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004618 return;
4619 }
Mike Stump11289f42009-09-09 15:08:12 +00004620
John McCall8b07ec22010-05-15 11:32:37 +00004621 // Ignore protocol qualifiers when mangling at this level.
4622 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4623 T = OT->getBaseType();
4624
John McCall8ccfcb52009-09-24 19:53:00 +00004625 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004626 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004627 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004628 S += '{';
4629 const IdentifierInfo *II = OI->getIdentifier();
4630 S += II->getName();
4631 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004632 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004633 DeepCollectObjCIvars(OI, true, Ivars);
4634 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004635 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004636 if (Field->isBitField())
4637 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004638 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004639 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004640 }
4641 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004642 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004643 }
Mike Stump11289f42009-09-09 15:08:12 +00004644
John McCall9dd450b2009-09-21 23:43:11 +00004645 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004646 if (OPT->isObjCIdType()) {
4647 S += '@';
4648 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004649 }
Mike Stump11289f42009-09-09 15:08:12 +00004650
Steve Narofff0c86112009-10-28 22:03:49 +00004651 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4652 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4653 // Since this is a binary compatibility issue, need to consult with runtime
4654 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004655 S += '#';
4656 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004657 }
Mike Stump11289f42009-09-09 15:08:12 +00004658
Chris Lattnere7cabb92009-07-13 00:10:46 +00004659 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004660 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004661 ExpandPointedToStructures,
4662 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004663 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004664 // Note that we do extended encoding of protocol qualifer list
4665 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004666 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004667 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4668 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004669 S += '<';
4670 S += (*I)->getNameAsString();
4671 S += '>';
4672 }
4673 S += '"';
4674 }
4675 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004676 }
Mike Stump11289f42009-09-09 15:08:12 +00004677
Chris Lattnere7cabb92009-07-13 00:10:46 +00004678 QualType PointeeTy = OPT->getPointeeType();
4679 if (!EncodingProperty &&
4680 isa<TypedefType>(PointeeTy.getTypePtr())) {
4681 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004682 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004683 // {...};
4684 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004685 getObjCEncodingForTypeImpl(PointeeTy, S,
4686 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004687 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004688 return;
4689 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004690
4691 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004692 if (OPT->getInterfaceDecl() &&
4693 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004694 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004695 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004696 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4697 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004698 S += '<';
4699 S += (*I)->getNameAsString();
4700 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004701 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004702 S += '"';
4703 }
4704 return;
4705 }
Mike Stump11289f42009-09-09 15:08:12 +00004706
John McCalla9e6e8d2010-05-17 23:56:34 +00004707 // gcc just blithely ignores member pointers.
4708 // TODO: maybe there should be a mangling for these
4709 if (T->getAs<MemberPointerType>())
4710 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004711
4712 if (T->isVectorType()) {
4713 // This matches gcc's encoding, even though technically it is
4714 // insufficient.
4715 // FIXME. We should do a better job than gcc.
4716 return;
4717 }
4718
David Blaikie83d382b2011-09-23 05:06:16 +00004719 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004720}
4721
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004722void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4723 std::string &S,
4724 const FieldDecl *FD,
4725 bool includeVBases) const {
4726 assert(RDecl && "Expected non-null RecordDecl");
4727 assert(!RDecl->isUnion() && "Should not be called for unions");
4728 if (!RDecl->getDefinition())
4729 return;
4730
4731 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4732 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4733 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4734
4735 if (CXXRec) {
4736 for (CXXRecordDecl::base_class_iterator
4737 BI = CXXRec->bases_begin(),
4738 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4739 if (!BI->isVirtual()) {
4740 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004741 if (base->isEmpty())
4742 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004743 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4744 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4745 std::make_pair(offs, base));
4746 }
4747 }
4748 }
4749
4750 unsigned i = 0;
4751 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4752 FieldEnd = RDecl->field_end();
4753 Field != FieldEnd; ++Field, ++i) {
4754 uint64_t offs = layout.getFieldOffset(i);
4755 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4756 std::make_pair(offs, *Field));
4757 }
4758
4759 if (CXXRec && includeVBases) {
4760 for (CXXRecordDecl::base_class_iterator
4761 BI = CXXRec->vbases_begin(),
4762 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4763 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004764 if (base->isEmpty())
4765 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004766 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004767 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4768 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4769 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004770 }
4771 }
4772
4773 CharUnits size;
4774 if (CXXRec) {
4775 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4776 } else {
4777 size = layout.getSize();
4778 }
4779
4780 uint64_t CurOffs = 0;
4781 std::multimap<uint64_t, NamedDecl *>::iterator
4782 CurLayObj = FieldOrBaseOffsets.begin();
4783
Argyrios Kyrtzidisc7e50c52011-08-22 16:03:14 +00004784 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4785 (CurLayObj == FieldOrBaseOffsets.end() &&
4786 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004787 assert(CXXRec && CXXRec->isDynamicClass() &&
4788 "Offset 0 was empty but no VTable ?");
4789 if (FD) {
4790 S += "\"_vptr$";
4791 std::string recname = CXXRec->getNameAsString();
4792 if (recname.empty()) recname = "?";
4793 S += recname;
4794 S += '"';
4795 }
4796 S += "^^?";
4797 CurOffs += getTypeSize(VoidPtrTy);
4798 }
4799
4800 if (!RDecl->hasFlexibleArrayMember()) {
4801 // Mark the end of the structure.
4802 uint64_t offs = toBits(size);
4803 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4804 std::make_pair(offs, (NamedDecl*)0));
4805 }
4806
4807 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4808 assert(CurOffs <= CurLayObj->first);
4809
4810 if (CurOffs < CurLayObj->first) {
4811 uint64_t padding = CurLayObj->first - CurOffs;
4812 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4813 // packing/alignment of members is different that normal, in which case
4814 // the encoding will be out-of-sync with the real layout.
4815 // If the runtime switches to just consider the size of types without
4816 // taking into account alignment, we could make padding explicit in the
4817 // encoding (e.g. using arrays of chars). The encoding strings would be
4818 // longer then though.
4819 CurOffs += padding;
4820 }
4821
4822 NamedDecl *dcl = CurLayObj->second;
4823 if (dcl == 0)
4824 break; // reached end of structure.
4825
4826 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4827 // We expand the bases without their virtual bases since those are going
4828 // in the initial structure. Note that this differs from gcc which
4829 // expands virtual bases each time one is encountered in the hierarchy,
4830 // making the encoding type bigger than it really is.
4831 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004832 assert(!base->isEmpty());
4833 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004834 } else {
4835 FieldDecl *field = cast<FieldDecl>(dcl);
4836 if (FD) {
4837 S += '"';
4838 S += field->getNameAsString();
4839 S += '"';
4840 }
4841
4842 if (field->isBitField()) {
4843 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004844 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004845 } else {
4846 QualType qt = field->getType();
4847 getLegacyIntegralTypeEncoding(qt);
4848 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4849 /*OutermostType*/false,
4850 /*EncodingProperty*/false,
4851 /*StructField*/true);
4852 CurOffs += getTypeSize(field->getType());
4853 }
4854 }
4855 }
4856}
4857
Mike Stump11289f42009-09-09 15:08:12 +00004858void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004859 std::string& S) const {
4860 if (QT & Decl::OBJC_TQ_In)
4861 S += 'n';
4862 if (QT & Decl::OBJC_TQ_Inout)
4863 S += 'N';
4864 if (QT & Decl::OBJC_TQ_Out)
4865 S += 'o';
4866 if (QT & Decl::OBJC_TQ_Bycopy)
4867 S += 'O';
4868 if (QT & Decl::OBJC_TQ_Byref)
4869 S += 'R';
4870 if (QT & Decl::OBJC_TQ_Oneway)
4871 S += 'V';
4872}
4873
Chris Lattnere7cabb92009-07-13 00:10:46 +00004874void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004875 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004876
Anders Carlsson87c149b2007-10-11 01:00:40 +00004877 BuiltinVaListType = T;
4878}
4879
Douglas Gregor3ea72692011-08-12 05:46:01 +00004880TypedefDecl *ASTContext::getObjCIdDecl() const {
4881 if (!ObjCIdDecl) {
4882 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4883 T = getObjCObjectPointerType(T);
4884 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4885 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4886 getTranslationUnitDecl(),
4887 SourceLocation(), SourceLocation(),
4888 &Idents.get("id"), IdInfo);
4889 }
4890
4891 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004892}
4893
Douglas Gregor52e02802011-08-12 06:17:30 +00004894TypedefDecl *ASTContext::getObjCSelDecl() const {
4895 if (!ObjCSelDecl) {
4896 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4897 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4898 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4899 getTranslationUnitDecl(),
4900 SourceLocation(), SourceLocation(),
4901 &Idents.get("SEL"), SelInfo);
4902 }
4903 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004904}
4905
Douglas Gregor0a586182011-08-12 05:59:41 +00004906TypedefDecl *ASTContext::getObjCClassDecl() const {
4907 if (!ObjCClassDecl) {
4908 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4909 T = getObjCObjectPointerType(T);
4910 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4911 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4912 getTranslationUnitDecl(),
4913 SourceLocation(), SourceLocation(),
4914 &Idents.get("Class"), ClassInfo);
4915 }
4916
4917 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004918}
4919
Douglas Gregord53ae832012-01-17 18:09:05 +00004920ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4921 if (!ObjCProtocolClassDecl) {
4922 ObjCProtocolClassDecl
4923 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4924 SourceLocation(),
4925 &Idents.get("Protocol"),
4926 /*PrevDecl=*/0,
4927 SourceLocation(), true);
4928 }
4929
4930 return ObjCProtocolClassDecl;
4931}
4932
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004933void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004934 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004935 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004936
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004937 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004938}
4939
John McCalld28ae272009-12-02 08:04:21 +00004940/// \brief Retrieve the template name that corresponds to a non-empty
4941/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004942TemplateName
4943ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4944 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004945 unsigned size = End - Begin;
4946 assert(size > 1 && "set is not overloaded!");
4947
4948 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4949 size * sizeof(FunctionTemplateDecl*));
4950 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4951
4952 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004953 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004954 NamedDecl *D = *I;
4955 assert(isa<FunctionTemplateDecl>(D) ||
4956 (isa<UsingShadowDecl>(D) &&
4957 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4958 *Storage++ = D;
4959 }
4960
4961 return TemplateName(OT);
4962}
4963
Douglas Gregordc572a32009-03-30 22:58:21 +00004964/// \brief Retrieve the template name that represents a qualified
4965/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004966TemplateName
4967ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4968 bool TemplateKeyword,
4969 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004970 assert(NNS && "Missing nested-name-specifier in qualified template name");
4971
Douglas Gregorc42075a2010-02-04 18:10:26 +00004972 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004973 llvm::FoldingSetNodeID ID;
4974 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4975
4976 void *InsertPos = 0;
4977 QualifiedTemplateName *QTN =
4978 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4979 if (!QTN) {
4980 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4981 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4982 }
4983
4984 return TemplateName(QTN);
4985}
4986
4987/// \brief Retrieve the template name that represents a dependent
4988/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004989TemplateName
4990ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4991 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004992 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004993 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004994
4995 llvm::FoldingSetNodeID ID;
4996 DependentTemplateName::Profile(ID, NNS, Name);
4997
4998 void *InsertPos = 0;
4999 DependentTemplateName *QTN =
5000 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5001
5002 if (QTN)
5003 return TemplateName(QTN);
5004
5005 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5006 if (CanonNNS == NNS) {
5007 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5008 } else {
5009 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5010 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005011 DependentTemplateName *CheckQTN =
5012 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5013 assert(!CheckQTN && "Dependent type name canonicalization broken");
5014 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005015 }
5016
5017 DependentTemplateNames.InsertNode(QTN, InsertPos);
5018 return TemplateName(QTN);
5019}
5020
Douglas Gregor71395fa2009-11-04 00:56:37 +00005021/// \brief Retrieve the template name that represents a dependent
5022/// template name such as \c MetaFun::template operator+.
5023TemplateName
5024ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005025 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005026 assert((!NNS || NNS->isDependent()) &&
5027 "Nested name specifier must be dependent");
5028
5029 llvm::FoldingSetNodeID ID;
5030 DependentTemplateName::Profile(ID, NNS, Operator);
5031
5032 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005033 DependentTemplateName *QTN
5034 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005035
5036 if (QTN)
5037 return TemplateName(QTN);
5038
5039 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5040 if (CanonNNS == NNS) {
5041 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5042 } else {
5043 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5044 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005045
5046 DependentTemplateName *CheckQTN
5047 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5048 assert(!CheckQTN && "Dependent template name canonicalization broken");
5049 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005050 }
5051
5052 DependentTemplateNames.InsertNode(QTN, InsertPos);
5053 return TemplateName(QTN);
5054}
5055
Douglas Gregor5590be02011-01-15 06:45:20 +00005056TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005057ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5058 TemplateName replacement) const {
5059 llvm::FoldingSetNodeID ID;
5060 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5061
5062 void *insertPos = 0;
5063 SubstTemplateTemplateParmStorage *subst
5064 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5065
5066 if (!subst) {
5067 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5068 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5069 }
5070
5071 return TemplateName(subst);
5072}
5073
5074TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005075ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5076 const TemplateArgument &ArgPack) const {
5077 ASTContext &Self = const_cast<ASTContext &>(*this);
5078 llvm::FoldingSetNodeID ID;
5079 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5080
5081 void *InsertPos = 0;
5082 SubstTemplateTemplateParmPackStorage *Subst
5083 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5084
5085 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005086 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005087 ArgPack.pack_size(),
5088 ArgPack.pack_begin());
5089 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5090 }
5091
5092 return TemplateName(Subst);
5093}
5094
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005095/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005096/// TargetInfo, produce the corresponding type. The unsigned @p Type
5097/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005098CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005099 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005100 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005101 case TargetInfo::SignedShort: return ShortTy;
5102 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5103 case TargetInfo::SignedInt: return IntTy;
5104 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5105 case TargetInfo::SignedLong: return LongTy;
5106 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5107 case TargetInfo::SignedLongLong: return LongLongTy;
5108 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5109 }
5110
David Blaikie83d382b2011-09-23 05:06:16 +00005111 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005112}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005113
5114//===----------------------------------------------------------------------===//
5115// Type Predicates.
5116//===----------------------------------------------------------------------===//
5117
Fariborz Jahanian96207692009-02-18 21:49:28 +00005118/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5119/// garbage collection attribute.
5120///
John McCall553d45a2011-01-12 00:34:59 +00005121Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005122 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005123 return Qualifiers::GCNone;
5124
David Blaikiebbafb8a2012-03-11 07:00:24 +00005125 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005126 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5127
5128 // Default behaviour under objective-C's gc is for ObjC pointers
5129 // (or pointers to them) be treated as though they were declared
5130 // as __strong.
5131 if (GCAttrs == Qualifiers::GCNone) {
5132 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5133 return Qualifiers::Strong;
5134 else if (Ty->isPointerType())
5135 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5136 } else {
5137 // It's not valid to set GC attributes on anything that isn't a
5138 // pointer.
5139#ifndef NDEBUG
5140 QualType CT = Ty->getCanonicalTypeInternal();
5141 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5142 CT = AT->getElementType();
5143 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5144#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005145 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005146 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005147}
5148
Chris Lattner49af6a42008-04-07 06:51:04 +00005149//===----------------------------------------------------------------------===//
5150// Type Compatibility Testing
5151//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005152
Mike Stump11289f42009-09-09 15:08:12 +00005153/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005154/// compatible.
5155static bool areCompatVectorTypes(const VectorType *LHS,
5156 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005157 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005158 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005159 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005160}
5161
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005162bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5163 QualType SecondVec) {
5164 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5165 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5166
5167 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5168 return true;
5169
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005170 // Treat Neon vector types and most AltiVec vector types as if they are the
5171 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005172 const VectorType *First = FirstVec->getAs<VectorType>();
5173 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005174 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005175 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005176 First->getVectorKind() != VectorType::AltiVecPixel &&
5177 First->getVectorKind() != VectorType::AltiVecBool &&
5178 Second->getVectorKind() != VectorType::AltiVecPixel &&
5179 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005180 return true;
5181
5182 return false;
5183}
5184
Steve Naroff8e6aee52009-07-23 01:01:38 +00005185//===----------------------------------------------------------------------===//
5186// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5187//===----------------------------------------------------------------------===//
5188
5189/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5190/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005191bool
5192ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5193 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005194 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005195 return true;
5196 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5197 E = rProto->protocol_end(); PI != E; ++PI)
5198 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5199 return true;
5200 return false;
5201}
5202
Steve Naroff8e6aee52009-07-23 01:01:38 +00005203/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5204/// return true if lhs's protocols conform to rhs's protocol; false
5205/// otherwise.
5206bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5207 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5208 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5209 return false;
5210}
5211
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005212/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5213/// Class<p1, ...>.
5214bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5215 QualType rhs) {
5216 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5217 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5218 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5219
5220 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5221 E = lhsQID->qual_end(); I != E; ++I) {
5222 bool match = false;
5223 ObjCProtocolDecl *lhsProto = *I;
5224 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5225 E = rhsOPT->qual_end(); J != E; ++J) {
5226 ObjCProtocolDecl *rhsProto = *J;
5227 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5228 match = true;
5229 break;
5230 }
5231 }
5232 if (!match)
5233 return false;
5234 }
5235 return true;
5236}
5237
Steve Naroff8e6aee52009-07-23 01:01:38 +00005238/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5239/// ObjCQualifiedIDType.
5240bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5241 bool compare) {
5242 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005243 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005244 lhs->isObjCIdType() || lhs->isObjCClassType())
5245 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005246 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005247 rhs->isObjCIdType() || rhs->isObjCClassType())
5248 return true;
5249
5250 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005251 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005252
Steve Naroff8e6aee52009-07-23 01:01:38 +00005253 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005254
Steve Naroff8e6aee52009-07-23 01:01:38 +00005255 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005256 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005257 // make sure we check the class hierarchy.
5258 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5259 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5260 E = lhsQID->qual_end(); I != E; ++I) {
5261 // when comparing an id<P> on lhs with a static type on rhs,
5262 // see if static class implements all of id's protocols, directly or
5263 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005264 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005265 return false;
5266 }
5267 }
5268 // If there are no qualifiers and no interface, we have an 'id'.
5269 return true;
5270 }
Mike Stump11289f42009-09-09 15:08:12 +00005271 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005272 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5273 E = lhsQID->qual_end(); I != E; ++I) {
5274 ObjCProtocolDecl *lhsProto = *I;
5275 bool match = false;
5276
5277 // when comparing an id<P> on lhs with a static type on rhs,
5278 // see if static class implements all of id's protocols, directly or
5279 // through its super class and categories.
5280 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5281 E = rhsOPT->qual_end(); J != E; ++J) {
5282 ObjCProtocolDecl *rhsProto = *J;
5283 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5284 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5285 match = true;
5286 break;
5287 }
5288 }
Mike Stump11289f42009-09-09 15:08:12 +00005289 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005290 // make sure we check the class hierarchy.
5291 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5292 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5293 E = lhsQID->qual_end(); I != E; ++I) {
5294 // when comparing an id<P> on lhs with a static type on rhs,
5295 // see if static class implements all of id's protocols, directly or
5296 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005297 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005298 match = true;
5299 break;
5300 }
5301 }
5302 }
5303 if (!match)
5304 return false;
5305 }
Mike Stump11289f42009-09-09 15:08:12 +00005306
Steve Naroff8e6aee52009-07-23 01:01:38 +00005307 return true;
5308 }
Mike Stump11289f42009-09-09 15:08:12 +00005309
Steve Naroff8e6aee52009-07-23 01:01:38 +00005310 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5311 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5312
Mike Stump11289f42009-09-09 15:08:12 +00005313 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005314 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005315 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005316 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5317 E = lhsOPT->qual_end(); I != E; ++I) {
5318 ObjCProtocolDecl *lhsProto = *I;
5319 bool match = false;
5320
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005321 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005322 // see if static class implements all of id's protocols, directly or
5323 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005324 // First, lhs protocols in the qualifier list must be found, direct
5325 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005326 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5327 E = rhsQID->qual_end(); J != E; ++J) {
5328 ObjCProtocolDecl *rhsProto = *J;
5329 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5330 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5331 match = true;
5332 break;
5333 }
5334 }
5335 if (!match)
5336 return false;
5337 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005338
5339 // Static class's protocols, or its super class or category protocols
5340 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5341 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5342 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5343 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5344 // This is rather dubious but matches gcc's behavior. If lhs has
5345 // no type qualifier and its class has no static protocol(s)
5346 // assume that it is mismatch.
5347 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5348 return false;
5349 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5350 LHSInheritedProtocols.begin(),
5351 E = LHSInheritedProtocols.end(); I != E; ++I) {
5352 bool match = false;
5353 ObjCProtocolDecl *lhsProto = (*I);
5354 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5355 E = rhsQID->qual_end(); J != E; ++J) {
5356 ObjCProtocolDecl *rhsProto = *J;
5357 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5358 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5359 match = true;
5360 break;
5361 }
5362 }
5363 if (!match)
5364 return false;
5365 }
5366 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005367 return true;
5368 }
5369 return false;
5370}
5371
Eli Friedman47f77112008-08-22 00:56:42 +00005372/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005373/// compatible for assignment from RHS to LHS. This handles validation of any
5374/// protocol qualifiers on the LHS or RHS.
5375///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005376bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5377 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005378 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5379 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5380
Steve Naroff1329fa02009-07-15 18:40:39 +00005381 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005382 if (LHS->isObjCUnqualifiedIdOrClass() ||
5383 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005384 return true;
5385
John McCall8b07ec22010-05-15 11:32:37 +00005386 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005387 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5388 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005389 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005390
5391 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5392 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5393 QualType(RHSOPT,0));
5394
John McCall8b07ec22010-05-15 11:32:37 +00005395 // If we have 2 user-defined types, fall into that path.
5396 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005397 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005398
Steve Naroff8e6aee52009-07-23 01:01:38 +00005399 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005400}
5401
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005402/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005403/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005404/// arguments in block literals. When passed as arguments, passing 'A*' where
5405/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5406/// not OK. For the return type, the opposite is not OK.
5407bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5408 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005409 const ObjCObjectPointerType *RHSOPT,
5410 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005411 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005412 return true;
5413
5414 if (LHSOPT->isObjCBuiltinType()) {
5415 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5416 }
5417
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005418 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005419 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5420 QualType(RHSOPT,0),
5421 false);
5422
5423 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5424 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5425 if (LHS && RHS) { // We have 2 user-defined types.
5426 if (LHS != RHS) {
5427 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005428 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005429 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005430 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005431 }
5432 else
5433 return true;
5434 }
5435 return false;
5436}
5437
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005438/// getIntersectionOfProtocols - This routine finds the intersection of set
5439/// of protocols inherited from two distinct objective-c pointer objects.
5440/// It is used to build composite qualifier list of the composite type of
5441/// the conditional expression involving two objective-c pointer objects.
5442static
5443void getIntersectionOfProtocols(ASTContext &Context,
5444 const ObjCObjectPointerType *LHSOPT,
5445 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005446 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005447
John McCall8b07ec22010-05-15 11:32:37 +00005448 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5449 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5450 assert(LHS->getInterface() && "LHS must have an interface base");
5451 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005452
5453 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5454 unsigned LHSNumProtocols = LHS->getNumProtocols();
5455 if (LHSNumProtocols > 0)
5456 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5457 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005458 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005459 Context.CollectInheritedProtocols(LHS->getInterface(),
5460 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005461 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5462 LHSInheritedProtocols.end());
5463 }
5464
5465 unsigned RHSNumProtocols = RHS->getNumProtocols();
5466 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005467 ObjCProtocolDecl **RHSProtocols =
5468 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005469 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5470 if (InheritedProtocolSet.count(RHSProtocols[i]))
5471 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005472 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005473 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005474 Context.CollectInheritedProtocols(RHS->getInterface(),
5475 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005476 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5477 RHSInheritedProtocols.begin(),
5478 E = RHSInheritedProtocols.end(); I != E; ++I)
5479 if (InheritedProtocolSet.count((*I)))
5480 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005481 }
5482}
5483
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005484/// areCommonBaseCompatible - Returns common base class of the two classes if
5485/// one found. Note that this is O'2 algorithm. But it will be called as the
5486/// last type comparison in a ?-exp of ObjC pointer types before a
5487/// warning is issued. So, its invokation is extremely rare.
5488QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005489 const ObjCObjectPointerType *Lptr,
5490 const ObjCObjectPointerType *Rptr) {
5491 const ObjCObjectType *LHS = Lptr->getObjectType();
5492 const ObjCObjectType *RHS = Rptr->getObjectType();
5493 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5494 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005495 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005496 return QualType();
5497
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005498 do {
John McCall8b07ec22010-05-15 11:32:37 +00005499 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005500 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005501 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005502 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5503
5504 QualType Result = QualType(LHS, 0);
5505 if (!Protocols.empty())
5506 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5507 Result = getObjCObjectPointerType(Result);
5508 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005509 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005510 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005511
5512 return QualType();
5513}
5514
John McCall8b07ec22010-05-15 11:32:37 +00005515bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5516 const ObjCObjectType *RHS) {
5517 assert(LHS->getInterface() && "LHS is not an interface type");
5518 assert(RHS->getInterface() && "RHS is not an interface type");
5519
Chris Lattner49af6a42008-04-07 06:51:04 +00005520 // Verify that the base decls are compatible: the RHS must be a subclass of
5521 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005522 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005523 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005524
Chris Lattner49af6a42008-04-07 06:51:04 +00005525 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5526 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005527 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005528 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005529
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005530 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5531 // more detailed analysis is required.
5532 if (RHS->getNumProtocols() == 0) {
5533 // OK, if LHS is a superclass of RHS *and*
5534 // this superclass is assignment compatible with LHS.
5535 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005536 bool IsSuperClass =
5537 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5538 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005539 // OK if conversion of LHS to SuperClass results in narrowing of types
5540 // ; i.e., SuperClass may implement at least one of the protocols
5541 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5542 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5543 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005544 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005545 // If super class has no protocols, it is not a match.
5546 if (SuperClassInheritedProtocols.empty())
5547 return false;
5548
5549 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5550 LHSPE = LHS->qual_end();
5551 LHSPI != LHSPE; LHSPI++) {
5552 bool SuperImplementsProtocol = false;
5553 ObjCProtocolDecl *LHSProto = (*LHSPI);
5554
5555 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5556 SuperClassInheritedProtocols.begin(),
5557 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5558 ObjCProtocolDecl *SuperClassProto = (*I);
5559 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5560 SuperImplementsProtocol = true;
5561 break;
5562 }
5563 }
5564 if (!SuperImplementsProtocol)
5565 return false;
5566 }
5567 return true;
5568 }
5569 return false;
5570 }
Mike Stump11289f42009-09-09 15:08:12 +00005571
John McCall8b07ec22010-05-15 11:32:37 +00005572 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5573 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005574 LHSPI != LHSPE; LHSPI++) {
5575 bool RHSImplementsProtocol = false;
5576
5577 // If the RHS doesn't implement the protocol on the left, the types
5578 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005579 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5580 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005581 RHSPI != RHSPE; RHSPI++) {
5582 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005583 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005584 break;
5585 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005586 }
5587 // FIXME: For better diagnostics, consider passing back the protocol name.
5588 if (!RHSImplementsProtocol)
5589 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005590 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005591 // The RHS implements all protocols listed on the LHS.
5592 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005593}
5594
Steve Naroffb7605152009-02-12 17:52:19 +00005595bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5596 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005597 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5598 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005599
Steve Naroff7cae42b2009-07-10 23:34:53 +00005600 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005601 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005602
5603 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5604 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005605}
5606
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005607bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5608 return canAssignObjCInterfaces(
5609 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5610 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5611}
5612
Mike Stump11289f42009-09-09 15:08:12 +00005613/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005614/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005615/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005616/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005617bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5618 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005619 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00005620 return hasSameType(LHS, RHS);
5621
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005622 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005623}
5624
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005625bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005626 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005627}
5628
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005629bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5630 return !mergeTypes(LHS, RHS, true).isNull();
5631}
5632
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005633/// mergeTransparentUnionType - if T is a transparent union type and a member
5634/// of T is compatible with SubType, return the merged type, else return
5635/// QualType()
5636QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5637 bool OfBlockPointer,
5638 bool Unqualified) {
5639 if (const RecordType *UT = T->getAsUnionType()) {
5640 RecordDecl *UD = UT->getDecl();
5641 if (UD->hasAttr<TransparentUnionAttr>()) {
5642 for (RecordDecl::field_iterator it = UD->field_begin(),
5643 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005644 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005645 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5646 if (!MT.isNull())
5647 return MT;
5648 }
5649 }
5650 }
5651
5652 return QualType();
5653}
5654
5655/// mergeFunctionArgumentTypes - merge two types which appear as function
5656/// argument types
5657QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5658 bool OfBlockPointer,
5659 bool Unqualified) {
5660 // GNU extension: two types are compatible if they appear as a function
5661 // argument, one of the types is a transparent union type and the other
5662 // type is compatible with a union member
5663 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5664 Unqualified);
5665 if (!lmerge.isNull())
5666 return lmerge;
5667
5668 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5669 Unqualified);
5670 if (!rmerge.isNull())
5671 return rmerge;
5672
5673 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5674}
5675
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005676QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005677 bool OfBlockPointer,
5678 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005679 const FunctionType *lbase = lhs->getAs<FunctionType>();
5680 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005681 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5682 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005683 bool allLTypes = true;
5684 bool allRTypes = true;
5685
5686 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005687 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005688 if (OfBlockPointer) {
5689 QualType RHS = rbase->getResultType();
5690 QualType LHS = lbase->getResultType();
5691 bool UnqualifiedResult = Unqualified;
5692 if (!UnqualifiedResult)
5693 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005694 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005695 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005696 else
John McCall8c6b56f2010-12-15 01:06:38 +00005697 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5698 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005699 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005700
5701 if (Unqualified)
5702 retType = retType.getUnqualifiedType();
5703
5704 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5705 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5706 if (Unqualified) {
5707 LRetType = LRetType.getUnqualifiedType();
5708 RRetType = RRetType.getUnqualifiedType();
5709 }
5710
5711 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005712 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005713 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005714 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005715
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005716 // FIXME: double check this
5717 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5718 // rbase->getRegParmAttr() != 0 &&
5719 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005720 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5721 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005722
Douglas Gregor8c940862010-01-18 17:14:39 +00005723 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005724 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005725 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005726
John McCall8c6b56f2010-12-15 01:06:38 +00005727 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005728 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5729 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005730 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5731 return QualType();
5732
John McCall31168b02011-06-15 23:02:42 +00005733 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5734 return QualType();
5735
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005736 // functypes which return are preferred over those that do not.
5737 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5738 allLTypes = false;
5739 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5740 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005741 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5742 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00005743
John McCall31168b02011-06-15 23:02:42 +00005744 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005745
Eli Friedman47f77112008-08-22 00:56:42 +00005746 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005747 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5748 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005749 unsigned lproto_nargs = lproto->getNumArgs();
5750 unsigned rproto_nargs = rproto->getNumArgs();
5751
5752 // Compatible functions must have the same number of arguments
5753 if (lproto_nargs != rproto_nargs)
5754 return QualType();
5755
5756 // Variadic and non-variadic functions aren't compatible
5757 if (lproto->isVariadic() != rproto->isVariadic())
5758 return QualType();
5759
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005760 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5761 return QualType();
5762
Fariborz Jahanian97676972011-09-28 21:52:05 +00005763 if (LangOpts.ObjCAutoRefCount &&
5764 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5765 return QualType();
5766
Eli Friedman47f77112008-08-22 00:56:42 +00005767 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005768 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00005769 for (unsigned i = 0; i < lproto_nargs; i++) {
5770 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5771 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005772 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5773 OfBlockPointer,
5774 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005775 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005776
5777 if (Unqualified)
5778 argtype = argtype.getUnqualifiedType();
5779
Eli Friedman47f77112008-08-22 00:56:42 +00005780 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005781 if (Unqualified) {
5782 largtype = largtype.getUnqualifiedType();
5783 rargtype = rargtype.getUnqualifiedType();
5784 }
5785
Chris Lattner465fa322008-10-05 17:34:18 +00005786 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5787 allLTypes = false;
5788 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5789 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005790 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00005791
Eli Friedman47f77112008-08-22 00:56:42 +00005792 if (allLTypes) return lhs;
5793 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005794
5795 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5796 EPI.ExtInfo = einfo;
5797 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005798 }
5799
5800 if (lproto) allRTypes = false;
5801 if (rproto) allLTypes = false;
5802
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005803 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005804 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005805 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005806 if (proto->isVariadic()) return QualType();
5807 // Check that the types are compatible with the types that
5808 // would result from default argument promotions (C99 6.7.5.3p15).
5809 // The only types actually affected are promotable integer
5810 // types and floats, which would be passed as a different
5811 // type depending on whether the prototype is visible.
5812 unsigned proto_nargs = proto->getNumArgs();
5813 for (unsigned i = 0; i < proto_nargs; ++i) {
5814 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005815
5816 // Look at the promotion type of enum types, since that is the type used
5817 // to pass enum values.
5818 if (const EnumType *Enum = argTy->getAs<EnumType>())
5819 argTy = Enum->getDecl()->getPromotionType();
5820
Eli Friedman47f77112008-08-22 00:56:42 +00005821 if (argTy->isPromotableIntegerType() ||
5822 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5823 return QualType();
5824 }
5825
5826 if (allLTypes) return lhs;
5827 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005828
5829 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5830 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005831 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005832 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005833 }
5834
5835 if (allLTypes) return lhs;
5836 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005837 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005838}
5839
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005840QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005841 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005842 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005843 // C++ [expr]: If an expression initially has the type "reference to T", the
5844 // type is adjusted to "T" prior to any further analysis, the expression
5845 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005846 // expression is an lvalue unless the reference is an rvalue reference and
5847 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005848 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5849 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005850
5851 if (Unqualified) {
5852 LHS = LHS.getUnqualifiedType();
5853 RHS = RHS.getUnqualifiedType();
5854 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005855
Eli Friedman47f77112008-08-22 00:56:42 +00005856 QualType LHSCan = getCanonicalType(LHS),
5857 RHSCan = getCanonicalType(RHS);
5858
5859 // If two types are identical, they are compatible.
5860 if (LHSCan == RHSCan)
5861 return LHS;
5862
John McCall8ccfcb52009-09-24 19:53:00 +00005863 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005864 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5865 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005866 if (LQuals != RQuals) {
5867 // If any of these qualifiers are different, we have a type
5868 // mismatch.
5869 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005870 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5871 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005872 return QualType();
5873
5874 // Exactly one GC qualifier difference is allowed: __strong is
5875 // okay if the other type has no GC qualifier but is an Objective
5876 // C object pointer (i.e. implicitly strong by default). We fix
5877 // this by pretending that the unqualified type was actually
5878 // qualified __strong.
5879 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5880 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5881 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5882
5883 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5884 return QualType();
5885
5886 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5887 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5888 }
5889 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5890 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5891 }
Eli Friedman47f77112008-08-22 00:56:42 +00005892 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005893 }
5894
5895 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005896
Eli Friedmandcca6332009-06-01 01:22:52 +00005897 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5898 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005899
Chris Lattnerfd652912008-01-14 05:45:46 +00005900 // We want to consider the two function types to be the same for these
5901 // comparisons, just force one to the other.
5902 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5903 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005904
5905 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005906 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5907 LHSClass = Type::ConstantArray;
5908 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5909 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005910
John McCall8b07ec22010-05-15 11:32:37 +00005911 // ObjCInterfaces are just specialized ObjCObjects.
5912 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5913 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5914
Nate Begemance4d7fc2008-04-18 23:10:10 +00005915 // Canonicalize ExtVector -> Vector.
5916 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5917 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005918
Chris Lattner95554662008-04-07 05:43:21 +00005919 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005920 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005921 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005922 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005923 // Compatibility is based on the underlying type, not the promotion
5924 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005925 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00005926 QualType TINT = ETy->getDecl()->getIntegerType();
5927 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00005928 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005929 }
John McCall9dd450b2009-09-21 23:43:11 +00005930 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00005931 QualType TINT = ETy->getDecl()->getIntegerType();
5932 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00005933 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005934 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00005935 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00005936 if (OfBlockPointer && !BlockReturnType) {
5937 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5938 return LHS;
5939 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5940 return RHS;
5941 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00005942
Eli Friedman47f77112008-08-22 00:56:42 +00005943 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005944 }
Eli Friedman47f77112008-08-22 00:56:42 +00005945
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005946 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005947 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005948#define TYPE(Class, Base)
5949#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005950#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005951#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5952#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5953#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00005954 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005955
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005956 case Type::LValueReference:
5957 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005958 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00005959 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005960
John McCall8b07ec22010-05-15 11:32:37 +00005961 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005962 case Type::IncompleteArray:
5963 case Type::VariableArray:
5964 case Type::FunctionProto:
5965 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00005966 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005967
Chris Lattnerfd652912008-01-14 05:45:46 +00005968 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005969 {
5970 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005971 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5972 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005973 if (Unqualified) {
5974 LHSPointee = LHSPointee.getUnqualifiedType();
5975 RHSPointee = RHSPointee.getUnqualifiedType();
5976 }
5977 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5978 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005979 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005980 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005981 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005982 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005983 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005984 return getPointerType(ResultType);
5985 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005986 case Type::BlockPointer:
5987 {
5988 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005989 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5990 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005991 if (Unqualified) {
5992 LHSPointee = LHSPointee.getUnqualifiedType();
5993 RHSPointee = RHSPointee.getUnqualifiedType();
5994 }
5995 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5996 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005997 if (ResultType.isNull()) return QualType();
5998 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5999 return LHS;
6000 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6001 return RHS;
6002 return getBlockPointerType(ResultType);
6003 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006004 case Type::Atomic:
6005 {
6006 // Merge two pointer types, while trying to preserve typedef info
6007 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6008 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6009 if (Unqualified) {
6010 LHSValue = LHSValue.getUnqualifiedType();
6011 RHSValue = RHSValue.getUnqualifiedType();
6012 }
6013 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6014 Unqualified);
6015 if (ResultType.isNull()) return QualType();
6016 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6017 return LHS;
6018 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6019 return RHS;
6020 return getAtomicType(ResultType);
6021 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006022 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006023 {
6024 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6025 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6026 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6027 return QualType();
6028
6029 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6030 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006031 if (Unqualified) {
6032 LHSElem = LHSElem.getUnqualifiedType();
6033 RHSElem = RHSElem.getUnqualifiedType();
6034 }
6035
6036 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006037 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006038 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6039 return LHS;
6040 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6041 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006042 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6043 ArrayType::ArraySizeModifier(), 0);
6044 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6045 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006046 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6047 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006048 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6049 return LHS;
6050 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6051 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006052 if (LVAT) {
6053 // FIXME: This isn't correct! But tricky to implement because
6054 // the array's size has to be the size of LHS, but the type
6055 // has to be different.
6056 return LHS;
6057 }
6058 if (RVAT) {
6059 // FIXME: This isn't correct! But tricky to implement because
6060 // the array's size has to be the size of RHS, but the type
6061 // has to be different.
6062 return RHS;
6063 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006064 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6065 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006066 return getIncompleteArrayType(ResultType,
6067 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006068 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006069 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006070 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006071 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006072 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006073 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006074 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006075 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006076 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006077 case Type::Complex:
6078 // Distinct complex types are incompatible.
6079 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006080 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006081 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006082 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6083 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006084 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006085 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006086 case Type::ObjCObject: {
6087 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006088 // FIXME: This should be type compatibility, e.g. whether
6089 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006090 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6091 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6092 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006093 return LHS;
6094
Eli Friedman47f77112008-08-22 00:56:42 +00006095 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006096 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006097 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006098 if (OfBlockPointer) {
6099 if (canAssignObjCInterfacesInBlockPointer(
6100 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006101 RHS->getAs<ObjCObjectPointerType>(),
6102 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006103 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006104 return QualType();
6105 }
John McCall9dd450b2009-09-21 23:43:11 +00006106 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6107 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006108 return LHS;
6109
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006110 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006111 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006112 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006113
David Blaikie8a40f702012-01-17 06:56:22 +00006114 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006115}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006116
Fariborz Jahanian97676972011-09-28 21:52:05 +00006117bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6118 const FunctionProtoType *FromFunctionType,
6119 const FunctionProtoType *ToFunctionType) {
6120 if (FromFunctionType->hasAnyConsumedArgs() !=
6121 ToFunctionType->hasAnyConsumedArgs())
6122 return false;
6123 FunctionProtoType::ExtProtoInfo FromEPI =
6124 FromFunctionType->getExtProtoInfo();
6125 FunctionProtoType::ExtProtoInfo ToEPI =
6126 ToFunctionType->getExtProtoInfo();
6127 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6128 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6129 ArgIdx != NumArgs; ++ArgIdx) {
6130 if (FromEPI.ConsumedArguments[ArgIdx] !=
6131 ToEPI.ConsumedArguments[ArgIdx])
6132 return false;
6133 }
6134 return true;
6135}
6136
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006137/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6138/// 'RHS' attributes and returns the merged version; including for function
6139/// return types.
6140QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6141 QualType LHSCan = getCanonicalType(LHS),
6142 RHSCan = getCanonicalType(RHS);
6143 // If two types are identical, they are compatible.
6144 if (LHSCan == RHSCan)
6145 return LHS;
6146 if (RHSCan->isFunctionType()) {
6147 if (!LHSCan->isFunctionType())
6148 return QualType();
6149 QualType OldReturnType =
6150 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6151 QualType NewReturnType =
6152 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6153 QualType ResReturnType =
6154 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6155 if (ResReturnType.isNull())
6156 return QualType();
6157 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6158 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6159 // In either case, use OldReturnType to build the new function type.
6160 const FunctionType *F = LHS->getAs<FunctionType>();
6161 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006162 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6163 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006164 QualType ResultType
6165 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006166 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006167 return ResultType;
6168 }
6169 }
6170 return QualType();
6171 }
6172
6173 // If the qualifiers are different, the types can still be merged.
6174 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6175 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6176 if (LQuals != RQuals) {
6177 // If any of these qualifiers are different, we have a type mismatch.
6178 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6179 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6180 return QualType();
6181
6182 // Exactly one GC qualifier difference is allowed: __strong is
6183 // okay if the other type has no GC qualifier but is an Objective
6184 // C object pointer (i.e. implicitly strong by default). We fix
6185 // this by pretending that the unqualified type was actually
6186 // qualified __strong.
6187 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6188 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6189 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6190
6191 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6192 return QualType();
6193
6194 if (GC_L == Qualifiers::Strong)
6195 return LHS;
6196 if (GC_R == Qualifiers::Strong)
6197 return RHS;
6198 return QualType();
6199 }
6200
6201 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6202 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6203 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6204 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6205 if (ResQT == LHSBaseQT)
6206 return LHS;
6207 if (ResQT == RHSBaseQT)
6208 return RHS;
6209 }
6210 return QualType();
6211}
6212
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006213//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006214// Integer Predicates
6215//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006216
Jay Foad39c79802011-01-12 09:06:06 +00006217unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006218 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006219 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006220 if (T->isBooleanType())
6221 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006222 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006223 return (unsigned)getTypeSize(T);
6224}
6225
6226QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006227 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006228
6229 // Turn <4 x signed int> -> <4 x unsigned int>
6230 if (const VectorType *VTy = T->getAs<VectorType>())
6231 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006232 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006233
6234 // For enums, we return the unsigned version of the base type.
6235 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006236 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006237
6238 const BuiltinType *BTy = T->getAs<BuiltinType>();
6239 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006240 switch (BTy->getKind()) {
6241 case BuiltinType::Char_S:
6242 case BuiltinType::SChar:
6243 return UnsignedCharTy;
6244 case BuiltinType::Short:
6245 return UnsignedShortTy;
6246 case BuiltinType::Int:
6247 return UnsignedIntTy;
6248 case BuiltinType::Long:
6249 return UnsignedLongTy;
6250 case BuiltinType::LongLong:
6251 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006252 case BuiltinType::Int128:
6253 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006254 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006255 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006256 }
6257}
6258
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006259ASTMutationListener::~ASTMutationListener() { }
6260
Chris Lattnerecd79c62009-06-14 00:45:47 +00006261
6262//===----------------------------------------------------------------------===//
6263// Builtin Type Computation
6264//===----------------------------------------------------------------------===//
6265
6266/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006267/// pointer over the consumed characters. This returns the resultant type. If
6268/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6269/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6270/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006271///
6272/// RequiresICE is filled in on return to indicate whether the value is required
6273/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006274static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006275 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006276 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006277 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006278 // Modifiers.
6279 int HowLong = 0;
6280 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006281 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006282
Chris Lattnerdc226c22010-10-01 22:42:38 +00006283 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006284 bool Done = false;
6285 while (!Done) {
6286 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006287 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006288 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006289 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006290 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006291 case 'S':
6292 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6293 assert(!Signed && "Can't use 'S' modifier multiple times!");
6294 Signed = true;
6295 break;
6296 case 'U':
6297 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6298 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6299 Unsigned = true;
6300 break;
6301 case 'L':
6302 assert(HowLong <= 2 && "Can't have LLLL modifier");
6303 ++HowLong;
6304 break;
6305 }
6306 }
6307
6308 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006309
Chris Lattnerecd79c62009-06-14 00:45:47 +00006310 // Read the base type.
6311 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006312 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006313 case 'v':
6314 assert(HowLong == 0 && !Signed && !Unsigned &&
6315 "Bad modifiers used with 'v'!");
6316 Type = Context.VoidTy;
6317 break;
6318 case 'f':
6319 assert(HowLong == 0 && !Signed && !Unsigned &&
6320 "Bad modifiers used with 'f'!");
6321 Type = Context.FloatTy;
6322 break;
6323 case 'd':
6324 assert(HowLong < 2 && !Signed && !Unsigned &&
6325 "Bad modifiers used with 'd'!");
6326 if (HowLong)
6327 Type = Context.LongDoubleTy;
6328 else
6329 Type = Context.DoubleTy;
6330 break;
6331 case 's':
6332 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6333 if (Unsigned)
6334 Type = Context.UnsignedShortTy;
6335 else
6336 Type = Context.ShortTy;
6337 break;
6338 case 'i':
6339 if (HowLong == 3)
6340 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6341 else if (HowLong == 2)
6342 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6343 else if (HowLong == 1)
6344 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6345 else
6346 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6347 break;
6348 case 'c':
6349 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6350 if (Signed)
6351 Type = Context.SignedCharTy;
6352 else if (Unsigned)
6353 Type = Context.UnsignedCharTy;
6354 else
6355 Type = Context.CharTy;
6356 break;
6357 case 'b': // boolean
6358 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6359 Type = Context.BoolTy;
6360 break;
6361 case 'z': // size_t.
6362 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6363 Type = Context.getSizeType();
6364 break;
6365 case 'F':
6366 Type = Context.getCFConstantStringType();
6367 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006368 case 'G':
6369 Type = Context.getObjCIdType();
6370 break;
6371 case 'H':
6372 Type = Context.getObjCSelType();
6373 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006374 case 'a':
6375 Type = Context.getBuiltinVaListType();
6376 assert(!Type.isNull() && "builtin va list type not initialized!");
6377 break;
6378 case 'A':
6379 // This is a "reference" to a va_list; however, what exactly
6380 // this means depends on how va_list is defined. There are two
6381 // different kinds of va_list: ones passed by value, and ones
6382 // passed by reference. An example of a by-value va_list is
6383 // x86, where va_list is a char*. An example of by-ref va_list
6384 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6385 // we want this argument to be a char*&; for x86-64, we want
6386 // it to be a __va_list_tag*.
6387 Type = Context.getBuiltinVaListType();
6388 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006389 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006390 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006391 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006392 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006393 break;
6394 case 'V': {
6395 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006396 unsigned NumElements = strtoul(Str, &End, 10);
6397 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006398 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006399
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006400 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6401 RequiresICE, false);
6402 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006403
6404 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006405 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006406 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006407 break;
6408 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006409 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006410 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6411 false);
6412 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006413 Type = Context.getComplexType(ElementType);
6414 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006415 }
6416 case 'Y' : {
6417 Type = Context.getPointerDiffType();
6418 break;
6419 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006420 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006421 Type = Context.getFILEType();
6422 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006423 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006424 return QualType();
6425 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006426 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006427 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006428 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006429 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006430 else
6431 Type = Context.getjmp_bufType();
6432
Mike Stump2adb4da2009-07-28 23:47:15 +00006433 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006434 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006435 return QualType();
6436 }
6437 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006438 case 'K':
6439 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6440 Type = Context.getucontext_tType();
6441
6442 if (Type.isNull()) {
6443 Error = ASTContext::GE_Missing_ucontext;
6444 return QualType();
6445 }
6446 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006447 }
Mike Stump11289f42009-09-09 15:08:12 +00006448
Chris Lattnerdc226c22010-10-01 22:42:38 +00006449 // If there are modifiers and if we're allowed to parse them, go for it.
6450 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006451 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006452 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006453 default: Done = true; --Str; break;
6454 case '*':
6455 case '&': {
6456 // Both pointers and references can have their pointee types
6457 // qualified with an address space.
6458 char *End;
6459 unsigned AddrSpace = strtoul(Str, &End, 10);
6460 if (End != Str && AddrSpace != 0) {
6461 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6462 Str = End;
6463 }
6464 if (c == '*')
6465 Type = Context.getPointerType(Type);
6466 else
6467 Type = Context.getLValueReferenceType(Type);
6468 break;
6469 }
6470 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6471 case 'C':
6472 Type = Type.withConst();
6473 break;
6474 case 'D':
6475 Type = Context.getVolatileType(Type);
6476 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006477 case 'R':
6478 Type = Type.withRestrict();
6479 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006480 }
6481 }
Chris Lattner84733392010-10-01 07:13:18 +00006482
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006483 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006484 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006485
Chris Lattnerecd79c62009-06-14 00:45:47 +00006486 return Type;
6487}
6488
6489/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006490QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006491 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006492 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006493 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006494
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006495 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006496
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006497 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006498 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006499 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6500 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006501 if (Error != GE_None)
6502 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006503
6504 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6505
Chris Lattnerecd79c62009-06-14 00:45:47 +00006506 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006507 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006508 if (Error != GE_None)
6509 return QualType();
6510
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006511 // If this argument is required to be an IntegerConstantExpression and the
6512 // caller cares, fill in the bitmask we return.
6513 if (RequiresICE && IntegerConstantArgs)
6514 *IntegerConstantArgs |= 1 << ArgTypes.size();
6515
Chris Lattnerecd79c62009-06-14 00:45:47 +00006516 // Do array -> pointer decay. The builtin should use the decayed type.
6517 if (Ty->isArrayType())
6518 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006519
Chris Lattnerecd79c62009-06-14 00:45:47 +00006520 ArgTypes.push_back(Ty);
6521 }
6522
6523 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6524 "'.' should only occur at end of builtin type list!");
6525
John McCall991eb4b2010-12-21 00:44:39 +00006526 FunctionType::ExtInfo EI;
6527 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6528
6529 bool Variadic = (TypeStr[0] == '.');
6530
6531 // We really shouldn't be making a no-proto type here, especially in C++.
6532 if (ArgTypes.empty() && Variadic)
6533 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006534
John McCalldb40c7f2010-12-14 08:05:40 +00006535 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006536 EPI.ExtInfo = EI;
6537 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006538
6539 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006540}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006541
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006542GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6543 GVALinkage External = GVA_StrongExternal;
6544
6545 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006546 switch (L) {
6547 case NoLinkage:
6548 case InternalLinkage:
6549 case UniqueExternalLinkage:
6550 return GVA_Internal;
6551
6552 case ExternalLinkage:
6553 switch (FD->getTemplateSpecializationKind()) {
6554 case TSK_Undeclared:
6555 case TSK_ExplicitSpecialization:
6556 External = GVA_StrongExternal;
6557 break;
6558
6559 case TSK_ExplicitInstantiationDefinition:
6560 return GVA_ExplicitTemplateInstantiation;
6561
6562 case TSK_ExplicitInstantiationDeclaration:
6563 case TSK_ImplicitInstantiation:
6564 External = GVA_TemplateInstantiation;
6565 break;
6566 }
6567 }
6568
6569 if (!FD->isInlined())
6570 return External;
6571
David Blaikiebbafb8a2012-03-11 07:00:24 +00006572 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006573 // GNU or C99 inline semantics. Determine whether this symbol should be
6574 // externally visible.
6575 if (FD->isInlineDefinitionExternallyVisible())
6576 return External;
6577
6578 // C99 inline semantics, where the symbol is not externally visible.
6579 return GVA_C99Inline;
6580 }
6581
6582 // C++0x [temp.explicit]p9:
6583 // [ Note: The intent is that an inline function that is the subject of
6584 // an explicit instantiation declaration will still be implicitly
6585 // instantiated when used so that the body can be considered for
6586 // inlining, but that no out-of-line copy of the inline function would be
6587 // generated in the translation unit. -- end note ]
6588 if (FD->getTemplateSpecializationKind()
6589 == TSK_ExplicitInstantiationDeclaration)
6590 return GVA_C99Inline;
6591
6592 return GVA_CXXInline;
6593}
6594
6595GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6596 // If this is a static data member, compute the kind of template
6597 // specialization. Otherwise, this variable is not part of a
6598 // template.
6599 TemplateSpecializationKind TSK = TSK_Undeclared;
6600 if (VD->isStaticDataMember())
6601 TSK = VD->getTemplateSpecializationKind();
6602
6603 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006604 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006605 VD->getType()->getLinkage() == UniqueExternalLinkage)
6606 L = UniqueExternalLinkage;
6607
6608 switch (L) {
6609 case NoLinkage:
6610 case InternalLinkage:
6611 case UniqueExternalLinkage:
6612 return GVA_Internal;
6613
6614 case ExternalLinkage:
6615 switch (TSK) {
6616 case TSK_Undeclared:
6617 case TSK_ExplicitSpecialization:
6618 return GVA_StrongExternal;
6619
6620 case TSK_ExplicitInstantiationDeclaration:
6621 llvm_unreachable("Variable should not be instantiated");
6622 // Fall through to treat this like any other instantiation.
6623
6624 case TSK_ExplicitInstantiationDefinition:
6625 return GVA_ExplicitTemplateInstantiation;
6626
6627 case TSK_ImplicitInstantiation:
6628 return GVA_TemplateInstantiation;
6629 }
6630 }
6631
David Blaikie8a40f702012-01-17 06:56:22 +00006632 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006633}
6634
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006635bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006636 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6637 if (!VD->isFileVarDecl())
6638 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006639 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006640 return false;
6641
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006642 // Weak references don't produce any output by themselves.
6643 if (D->hasAttr<WeakRefAttr>())
6644 return false;
6645
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006646 // Aliases and used decls are required.
6647 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6648 return true;
6649
6650 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6651 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006652 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006653 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006654
6655 // Constructors and destructors are required.
6656 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6657 return true;
6658
6659 // The key function for a class is required.
6660 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6661 const CXXRecordDecl *RD = MD->getParent();
6662 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6663 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6664 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6665 return true;
6666 }
6667 }
6668
6669 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6670
6671 // static, static inline, always_inline, and extern inline functions can
6672 // always be deferred. Normal inline functions can be deferred in C99/C++.
6673 // Implicit template instantiations can also be deferred in C++.
6674 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00006675 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006676 return false;
6677 return true;
6678 }
Douglas Gregor87d81242011-09-10 00:22:34 +00006679
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006680 const VarDecl *VD = cast<VarDecl>(D);
6681 assert(VD->isFileVarDecl() && "Expected file scoped var");
6682
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006683 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6684 return false;
6685
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006686 // Structs that have non-trivial constructors or destructors are required.
6687
6688 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006689 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006690 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6691 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006692 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6693 RD->hasTrivialCopyConstructor() &&
6694 RD->hasTrivialMoveConstructor() &&
6695 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006696 return true;
6697 }
6698 }
6699
6700 GVALinkage L = GetGVALinkageForVariable(VD);
6701 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6702 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6703 return false;
6704 }
6705
6706 return true;
6707}
Charles Davis53c59df2010-08-16 03:33:14 +00006708
Charles Davis99202b32010-11-09 18:04:24 +00006709CallingConv ASTContext::getDefaultMethodCallConv() {
6710 // Pass through to the C++ ABI object
6711 return ABI->getDefaultMethodCallConv();
6712}
6713
Jay Foad39c79802011-01-12 09:06:06 +00006714bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006715 // Pass through to the C++ ABI object
6716 return ABI->isNearlyEmpty(RD);
6717}
6718
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006719MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00006720 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006721 case CXXABI_ARM:
6722 case CXXABI_Itanium:
6723 return createItaniumMangleContext(*this, getDiagnostics());
6724 case CXXABI_Microsoft:
6725 return createMicrosoftMangleContext(*this, getDiagnostics());
6726 }
David Blaikie83d382b2011-09-23 05:06:16 +00006727 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006728}
6729
Charles Davis53c59df2010-08-16 03:33:14 +00006730CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006731
6732size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00006733 return ASTRecordLayouts.getMemorySize()
6734 + llvm::capacity_in_bytes(ObjCLayouts)
6735 + llvm::capacity_in_bytes(KeyFunctions)
6736 + llvm::capacity_in_bytes(ObjCImpls)
6737 + llvm::capacity_in_bytes(BlockVarCopyInits)
6738 + llvm::capacity_in_bytes(DeclAttrs)
6739 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6740 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6741 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6742 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6743 + llvm::capacity_in_bytes(OverriddenMethods)
6744 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006745 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00006746 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006747}
Ted Kremenek540017e2011-10-06 05:00:56 +00006748
Douglas Gregor63798542012-02-20 19:44:39 +00006749unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
6750 CXXRecordDecl *Lambda = CallOperator->getParent();
6751 return LambdaMangleContexts[Lambda->getDeclContext()]
6752 .getManglingNumber(CallOperator);
6753}
6754
6755
Ted Kremenek540017e2011-10-06 05:00:56 +00006756void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6757 ParamIndices[D] = index;
6758}
6759
6760unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6761 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6762 assert(I != ParamIndices.end() &&
6763 "ParmIndices lacks entry set by ParmVarDecl");
6764 return I->second;
6765}