blob: 887beac4b0b2a3838f5da73086323052c7c0a48d [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
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000484 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
485 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000486
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000487 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000488
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000489 // void * type
490 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000491
492 // nullptr type (C++0x 2.14.7)
493 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000494
495 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
496 InitBuiltinType(HalfTy, BuiltinType::Half);
Chris Lattner970e54e2006-11-12 00:37:36 +0000497}
498
David Blaikie9c902b52011-09-25 23:23:43 +0000499DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000500 return SourceMgr.getDiagnostics();
501}
502
Douglas Gregor561eceb2010-08-30 16:49:28 +0000503AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
504 AttrVec *&Result = DeclAttrs[D];
505 if (!Result) {
506 void *Mem = Allocate(sizeof(AttrVec));
507 Result = new (Mem) AttrVec;
508 }
509
510 return *Result;
511}
512
513/// \brief Erase the attributes corresponding to the given declaration.
514void ASTContext::eraseDeclAttrs(const Decl *D) {
515 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
516 if (Pos != DeclAttrs.end()) {
517 Pos->second->~AttrVec();
518 DeclAttrs.erase(Pos);
519 }
520}
521
Douglas Gregor86d142a2009-10-08 07:24:58 +0000522MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000523ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000524 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000525 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000526 = InstantiatedFromStaticDataMember.find(Var);
527 if (Pos == InstantiatedFromStaticDataMember.end())
528 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000529
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000530 return Pos->second;
531}
532
Mike Stump11289f42009-09-09 15:08:12 +0000533void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000534ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000535 TemplateSpecializationKind TSK,
536 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000537 assert(Inst->isStaticDataMember() && "Not a static data member");
538 assert(Tmpl->isStaticDataMember() && "Not a static data member");
539 assert(!InstantiatedFromStaticDataMember[Inst] &&
540 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000541 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000542 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000543}
544
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000545FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
546 const FunctionDecl *FD){
547 assert(FD && "Specialization is 0");
548 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000549 = ClassScopeSpecializationPattern.find(FD);
550 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000551 return 0;
552
553 return Pos->second;
554}
555
556void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
557 FunctionDecl *Pattern) {
558 assert(FD && "Specialization is 0");
559 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000560 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000561}
562
John McCalle61f2ba2009-11-18 02:36:19 +0000563NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000564ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000565 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000566 = InstantiatedFromUsingDecl.find(UUD);
567 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000568 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000569
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000570 return Pos->second;
571}
572
573void
John McCallb96ec562009-12-04 22:46:56 +0000574ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
575 assert((isa<UsingDecl>(Pattern) ||
576 isa<UnresolvedUsingValueDecl>(Pattern) ||
577 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
578 "pattern decl is not a using decl");
579 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
580 InstantiatedFromUsingDecl[Inst] = Pattern;
581}
582
583UsingShadowDecl *
584ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
585 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
586 = InstantiatedFromUsingShadowDecl.find(Inst);
587 if (Pos == InstantiatedFromUsingShadowDecl.end())
588 return 0;
589
590 return Pos->second;
591}
592
593void
594ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
595 UsingShadowDecl *Pattern) {
596 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
597 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000598}
599
Anders Carlsson5da84842009-09-01 04:26:58 +0000600FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
601 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
602 = InstantiatedFromUnnamedFieldDecl.find(Field);
603 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
604 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000605
Anders Carlsson5da84842009-09-01 04:26:58 +0000606 return Pos->second;
607}
608
609void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
610 FieldDecl *Tmpl) {
611 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
612 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
613 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
614 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000615
Anders Carlsson5da84842009-09-01 04:26:58 +0000616 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
617}
618
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000619bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
620 const FieldDecl *LastFD) const {
621 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000622 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000623}
624
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000625bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
626 const FieldDecl *LastFD) const {
627 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000628 FD->getBitWidthValue(*this) == 0 &&
629 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000630}
631
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000632bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
633 const FieldDecl *LastFD) const {
634 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000635 FD->getBitWidthValue(*this) &&
636 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000637}
638
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000639bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000640 const FieldDecl *LastFD) const {
641 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000642 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000643}
644
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000645bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000646 const FieldDecl *LastFD) const {
647 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000648 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000649}
650
Douglas Gregor832940b2010-03-02 23:58:15 +0000651ASTContext::overridden_cxx_method_iterator
652ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
653 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
654 = OverriddenMethods.find(Method);
655 if (Pos == OverriddenMethods.end())
656 return 0;
657
658 return Pos->second.begin();
659}
660
661ASTContext::overridden_cxx_method_iterator
662ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
663 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
664 = OverriddenMethods.find(Method);
665 if (Pos == OverriddenMethods.end())
666 return 0;
667
668 return Pos->second.end();
669}
670
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000671unsigned
672ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
673 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
674 = OverriddenMethods.find(Method);
675 if (Pos == OverriddenMethods.end())
676 return 0;
677
678 return Pos->second.size();
679}
680
Douglas Gregor832940b2010-03-02 23:58:15 +0000681void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
682 const CXXMethodDecl *Overridden) {
683 OverriddenMethods[Method].push_back(Overridden);
684}
685
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000686void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
687 assert(!Import->NextLocalImport && "Import declaration already in the chain");
688 assert(!Import->isFromASTFile() && "Non-local import declaration");
689 if (!FirstLocalImport) {
690 FirstLocalImport = Import;
691 LastLocalImport = Import;
692 return;
693 }
694
695 LastLocalImport->NextLocalImport = Import;
696 LastLocalImport = Import;
697}
698
Chris Lattner53cfe802007-07-18 17:52:12 +0000699//===----------------------------------------------------------------------===//
700// Type Sizing and Analysis
701//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000702
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000703/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
704/// scalar floating point type.
705const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000706 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000707 assert(BT && "Not a floating point type!");
708 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000709 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000710 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000711 case BuiltinType::Float: return Target->getFloatFormat();
712 case BuiltinType::Double: return Target->getDoubleFormat();
713 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000714 }
715}
716
Ken Dyck160146e2010-01-27 17:10:57 +0000717/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000718/// specified decl. Note that bitfields do not have a valid alignment, so
719/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000720/// If @p RefAsPointee, references are treated like their underlying type
721/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000722CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000723 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000724
John McCall94268702010-10-08 18:24:19 +0000725 bool UseAlignAttrOnly = false;
726 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
727 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000728
John McCall94268702010-10-08 18:24:19 +0000729 // __attribute__((aligned)) can increase or decrease alignment
730 // *except* on a struct or struct member, where it only increases
731 // alignment unless 'packed' is also specified.
732 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000733 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000734 // ignore that possibility; Sema should diagnose it.
735 if (isa<FieldDecl>(D)) {
736 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
737 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
738 } else {
739 UseAlignAttrOnly = true;
740 }
741 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000742 else if (isa<FieldDecl>(D))
743 UseAlignAttrOnly =
744 D->hasAttr<PackedAttr>() ||
745 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000746
John McCall4e819612011-01-20 07:57:12 +0000747 // If we're using the align attribute only, just ignore everything
748 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000749 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000750 // do nothing
751
John McCall94268702010-10-08 18:24:19 +0000752 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000753 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000754 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000755 if (RefAsPointee)
756 T = RT->getPointeeType();
757 else
758 T = getPointerType(RT->getPointeeType());
759 }
760 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000761 // Adjust alignments of declarations with array type by the
762 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000763 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000764 const ArrayType *arrayType;
765 if (MinWidth && (arrayType = getAsArrayType(T))) {
766 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000767 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000768 else if (isa<ConstantArrayType>(arrayType) &&
769 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000770 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000771
John McCall33ddac02011-01-19 10:06:00 +0000772 // Walk through any array types while we're at it.
773 T = getBaseElementType(arrayType);
774 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000775 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000776 }
John McCall4e819612011-01-20 07:57:12 +0000777
778 // Fields can be subject to extra alignment constraints, like if
779 // the field is packed, the struct is packed, or the struct has a
780 // a max-field-alignment constraint (#pragma pack). So calculate
781 // the actual alignment of the field within the struct, and then
782 // (as we're expected to) constrain that by the alignment of the type.
783 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
784 // So calculate the alignment of the field.
785 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
786
787 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000788 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000789
790 // Use the GCD of that and the offset within the record.
791 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
792 if (offset > 0) {
793 // Alignment is always a power of 2, so the GCD will be a power of 2,
794 // which means we get to do this crazy thing instead of Euclid's.
795 uint64_t lowBitOfOffset = offset & (~offset + 1);
796 if (lowBitOfOffset < fieldAlign)
797 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
798 }
799
800 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000801 }
Chris Lattner68061312009-01-24 21:53:27 +0000802 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000803
Ken Dyckcc56c542011-01-15 18:38:59 +0000804 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000805}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000806
John McCall87fe5d52010-05-20 01:18:31 +0000807std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000808ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000809 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000810 return std::make_pair(toCharUnitsFromBits(Info.first),
811 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000812}
813
814std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000815ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000816 return getTypeInfoInChars(T.getTypePtr());
817}
818
Daniel Dunbarc6475872012-03-09 04:12:54 +0000819std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
820 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
821 if (it != MemoizedTypeInfo.end())
822 return it->second;
823
824 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
825 MemoizedTypeInfo.insert(std::make_pair(T, Info));
826 return Info;
827}
828
829/// getTypeInfoImpl - Return the size of the specified type, in bits. This
830/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000831///
832/// FIXME: Pointers into different addr spaces could have different sizes and
833/// alignment requirements: getPointerInfo should take an AddrSpace, this
834/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000835std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +0000836ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000837 uint64_t Width=0;
838 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000839 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000840#define TYPE(Class, Base)
841#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000842#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000843#define DEPENDENT_TYPE(Class, Base) case Type::Class:
844#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000845 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000846
Chris Lattner355332d2007-07-13 22:27:08 +0000847 case Type::FunctionNoProto:
848 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000849 // GCC extension: alignof(function) = 32 bits
850 Width = 0;
851 Align = 32;
852 break;
853
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000854 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000855 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000856 Width = 0;
857 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
858 break;
859
Steve Naroff5c131802007-08-30 01:06:46 +0000860 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000861 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000862
Chris Lattner37e05872008-03-05 18:54:05 +0000863 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000864 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +0000865 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
866 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000867 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000868 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000869 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000870 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000871 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000872 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000873 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000874 const VectorType *VT = cast<VectorType>(T);
875 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
876 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000877 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000878 // If the alignment is not a power of 2, round up to the next power of 2.
879 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000880 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000881 Align = llvm::NextPowerOf2(Align);
882 Width = llvm::RoundUpToAlignment(Width, Align);
883 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000884 break;
885 }
Chris Lattner647fb222007-07-18 18:26:58 +0000886
Chris Lattner7570e9c2008-03-08 08:52:55 +0000887 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000888 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000889 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000890 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000891 // GCC extension: alignof(void) = 8 bits.
892 Width = 0;
893 Align = 8;
894 break;
895
Chris Lattner6a4f7452007-12-19 19:23:28 +0000896 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000897 Width = Target->getBoolWidth();
898 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000899 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000900 case BuiltinType::Char_S:
901 case BuiltinType::Char_U:
902 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000903 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000904 Width = Target->getCharWidth();
905 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000906 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000907 case BuiltinType::WChar_S:
908 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000909 Width = Target->getWCharWidth();
910 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000911 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000912 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000913 Width = Target->getChar16Width();
914 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000915 break;
916 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000917 Width = Target->getChar32Width();
918 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000919 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000920 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000921 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000922 Width = Target->getShortWidth();
923 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000924 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000925 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000926 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000927 Width = Target->getIntWidth();
928 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000929 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000930 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000931 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000932 Width = Target->getLongWidth();
933 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000934 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000935 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000936 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000937 Width = Target->getLongLongWidth();
938 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000939 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000940 case BuiltinType::Int128:
941 case BuiltinType::UInt128:
942 Width = 128;
943 Align = 128; // int128_t is 128-bit aligned on all targets.
944 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000945 case BuiltinType::Half:
946 Width = Target->getHalfWidth();
947 Align = Target->getHalfAlign();
948 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000949 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000950 Width = Target->getFloatWidth();
951 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000952 break;
953 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000954 Width = Target->getDoubleWidth();
955 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000956 break;
957 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000958 Width = Target->getLongDoubleWidth();
959 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000960 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000961 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000962 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
963 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000964 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000965 case BuiltinType::ObjCId:
966 case BuiltinType::ObjCClass:
967 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000968 Width = Target->getPointerWidth(0);
969 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000970 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000971 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000972 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000973 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000974 Width = Target->getPointerWidth(0);
975 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000976 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000977 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000978 unsigned AS = getTargetAddressSpace(
979 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000980 Width = Target->getPointerWidth(AS);
981 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +0000982 break;
983 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000984 case Type::LValueReference:
985 case Type::RValueReference: {
986 // alignof and sizeof should never enter this code path here, so we go
987 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000988 unsigned AS = getTargetAddressSpace(
989 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000990 Width = Target->getPointerWidth(AS);
991 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000992 break;
993 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000994 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000995 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000996 Width = Target->getPointerWidth(AS);
997 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000998 break;
999 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001000 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001001 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001002 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001003 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001004 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001005 Align = PtrDiffInfo.second;
1006 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001007 }
Chris Lattner647fb222007-07-18 18:26:58 +00001008 case Type::Complex: {
1009 // Complex types have the same alignment as their elements, but twice the
1010 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001011 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001012 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001013 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001014 Align = EltInfo.second;
1015 break;
1016 }
John McCall8b07ec22010-05-15 11:32:37 +00001017 case Type::ObjCObject:
1018 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001019 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001020 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001021 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001022 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001023 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001024 break;
1025 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001026 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001027 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001028 const TagType *TT = cast<TagType>(T);
1029
1030 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001031 Width = 8;
1032 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001033 break;
1034 }
Mike Stump11289f42009-09-09 15:08:12 +00001035
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001036 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001037 return getTypeInfo(ET->getDecl()->getIntegerType());
1038
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001039 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001040 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001041 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001042 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001043 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001044 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001045
Chris Lattner63d2b362009-10-22 05:17:15 +00001046 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001047 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1048 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001049
Richard Smith30482bc2011-02-20 03:19:35 +00001050 case Type::Auto: {
1051 const AutoType *A = cast<AutoType>(T);
1052 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001053 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001054 }
1055
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001056 case Type::Paren:
1057 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1058
Douglas Gregoref462e62009-04-30 17:32:17 +00001059 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001060 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001061 std::pair<uint64_t, unsigned> Info
1062 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001063 // If the typedef has an aligned attribute on it, it overrides any computed
1064 // alignment we have. This violates the GCC documentation (which says that
1065 // attribute(aligned) can only round up) but matches its implementation.
1066 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1067 Align = AttrAlign;
1068 else
1069 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001070 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001071 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001072 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001073
1074 case Type::TypeOfExpr:
1075 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1076 .getTypePtr());
1077
1078 case Type::TypeOf:
1079 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1080
Anders Carlsson81df7b82009-06-24 19:06:50 +00001081 case Type::Decltype:
1082 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1083 .getTypePtr());
1084
Alexis Hunte852b102011-05-24 22:41:36 +00001085 case Type::UnaryTransform:
1086 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1087
Abramo Bagnara6150c882010-05-11 21:36:43 +00001088 case Type::Elaborated:
1089 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001090
John McCall81904512011-01-06 01:58:22 +00001091 case Type::Attributed:
1092 return getTypeInfo(
1093 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1094
Richard Smith3f1b5d02011-05-05 21:57:07 +00001095 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001096 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001097 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001098 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1099 // A type alias template specialization may refer to a typedef with the
1100 // aligned attribute on it.
1101 if (TST->isTypeAlias())
1102 return getTypeInfo(TST->getAliasedType().getTypePtr());
1103 else
1104 return getTypeInfo(getCanonicalType(T));
1105 }
1106
Eli Friedman0dfb8892011-10-06 23:00:33 +00001107 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001108 std::pair<uint64_t, unsigned> Info
1109 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1110 Width = Info.first;
1111 Align = Info.second;
1112 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1113 llvm::isPowerOf2_64(Width)) {
1114 // We can potentially perform lock-free atomic operations for this
1115 // type; promote the alignment appropriately.
1116 // FIXME: We could potentially promote the width here as well...
1117 // is that worthwhile? (Non-struct atomic types generally have
1118 // power-of-two size anyway, but structs might not. Requires a bit
1119 // of implementation work to make sure we zero out the extra bits.)
1120 Align = static_cast<unsigned>(Width);
1121 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001122 }
1123
Douglas Gregoref462e62009-04-30 17:32:17 +00001124 }
Mike Stump11289f42009-09-09 15:08:12 +00001125
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001126 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001127 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001128}
1129
Ken Dyckcc56c542011-01-15 18:38:59 +00001130/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1131CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1132 return CharUnits::fromQuantity(BitSize / getCharWidth());
1133}
1134
Ken Dyckb0fcc592011-02-11 01:54:29 +00001135/// toBits - Convert a size in characters to a size in characters.
1136int64_t ASTContext::toBits(CharUnits CharSize) const {
1137 return CharSize.getQuantity() * getCharWidth();
1138}
1139
Ken Dyck8c89d592009-12-22 14:23:30 +00001140/// getTypeSizeInChars - Return the size of the specified type, in characters.
1141/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001142CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001143 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001144}
Jay Foad39c79802011-01-12 09:06:06 +00001145CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001146 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001147}
1148
Ken Dycka6046ab2010-01-26 17:25:18 +00001149/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001150/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001151CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001152 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001153}
Jay Foad39c79802011-01-12 09:06:06 +00001154CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001155 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001156}
1157
Chris Lattnera3402cd2009-01-27 18:08:34 +00001158/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1159/// type for the current target in bits. This can be different than the ABI
1160/// alignment in cases where it is beneficial for performance to overalign
1161/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001162unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001163 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001164
1165 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001166 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001167 T = CT->getElementType().getTypePtr();
1168 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001169 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1170 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001171 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1172
Chris Lattnera3402cd2009-01-27 18:08:34 +00001173 return ABIAlign;
1174}
1175
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001176/// DeepCollectObjCIvars -
1177/// This routine first collects all declared, but not synthesized, ivars in
1178/// super class and then collects all ivars, including those synthesized for
1179/// current class. This routine is used for implementation of current class
1180/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001181///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001182void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1183 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001184 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001185 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1186 DeepCollectObjCIvars(SuperClass, false, Ivars);
1187 if (!leafClass) {
1188 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1189 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001190 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001191 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001192 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001193 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001194 Iv= Iv->getNextIvar())
1195 Ivars.push_back(Iv);
1196 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001197}
1198
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001199/// CollectInheritedProtocols - Collect all protocols in current class and
1200/// those inherited by it.
1201void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001202 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001203 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001204 // We can use protocol_iterator here instead of
1205 // all_referenced_protocol_iterator since we are walking all categories.
1206 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1207 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001208 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001209 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001210 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001211 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001212 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001213 CollectInheritedProtocols(*P, Protocols);
1214 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001215 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001216
1217 // Categories of this Interface.
1218 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1219 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1220 CollectInheritedProtocols(CDeclChain, Protocols);
1221 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1222 while (SD) {
1223 CollectInheritedProtocols(SD, Protocols);
1224 SD = SD->getSuperClass();
1225 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001226 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001227 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001228 PE = OC->protocol_end(); P != PE; ++P) {
1229 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001230 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001231 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1232 PE = Proto->protocol_end(); P != PE; ++P)
1233 CollectInheritedProtocols(*P, Protocols);
1234 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001235 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001236 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1237 PE = OP->protocol_end(); P != PE; ++P) {
1238 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001239 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001240 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1241 PE = Proto->protocol_end(); P != PE; ++P)
1242 CollectInheritedProtocols(*P, Protocols);
1243 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001244 }
1245}
1246
Jay Foad39c79802011-01-12 09:06:06 +00001247unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001248 unsigned count = 0;
1249 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001250 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1251 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001252 count += CDecl->ivar_size();
1253
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001254 // Count ivar defined in this class's implementation. This
1255 // includes synthesized ivars.
1256 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001257 count += ImplDecl->ivar_size();
1258
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001259 return count;
1260}
1261
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001262bool ASTContext::isSentinelNullExpr(const Expr *E) {
1263 if (!E)
1264 return false;
1265
1266 // nullptr_t is always treated as null.
1267 if (E->getType()->isNullPtrType()) return true;
1268
1269 if (E->getType()->isAnyPointerType() &&
1270 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1271 Expr::NPC_ValueDependentIsNull))
1272 return true;
1273
1274 // Unfortunately, __null has type 'int'.
1275 if (isa<GNUNullExpr>(E)) return true;
1276
1277 return false;
1278}
1279
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001280/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1281ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1282 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1283 I = ObjCImpls.find(D);
1284 if (I != ObjCImpls.end())
1285 return cast<ObjCImplementationDecl>(I->second);
1286 return 0;
1287}
1288/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1289ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1290 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1291 I = ObjCImpls.find(D);
1292 if (I != ObjCImpls.end())
1293 return cast<ObjCCategoryImplDecl>(I->second);
1294 return 0;
1295}
1296
1297/// \brief Set the implementation of ObjCInterfaceDecl.
1298void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1299 ObjCImplementationDecl *ImplD) {
1300 assert(IFaceD && ImplD && "Passed null params");
1301 ObjCImpls[IFaceD] = ImplD;
1302}
1303/// \brief Set the implementation of ObjCCategoryDecl.
1304void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1305 ObjCCategoryImplDecl *ImplD) {
1306 assert(CatD && ImplD && "Passed null params");
1307 ObjCImpls[CatD] = ImplD;
1308}
1309
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001310ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1311 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1312 return ID;
1313 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1314 return CD->getClassInterface();
1315 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1316 return IMD->getClassInterface();
1317
1318 return 0;
1319}
1320
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001321/// \brief Get the copy initialization expression of VarDecl,or NULL if
1322/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001323Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001324 assert(VD && "Passed null params");
1325 assert(VD->hasAttr<BlocksAttr>() &&
1326 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001327 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001328 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001329 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1330}
1331
1332/// \brief Set the copy inialization expression of a block var decl.
1333void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1334 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001335 assert(VD->hasAttr<BlocksAttr>() &&
1336 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001337 BlockVarCopyInits[VD] = Init;
1338}
1339
John McCallbcd03502009-12-07 02:54:59 +00001340/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001341///
John McCallbcd03502009-12-07 02:54:59 +00001342/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001343/// the TypeLoc wrappers.
1344///
1345/// \param T the type that will be the basis for type source info. This type
1346/// should refer to how the declarator was written in source code, not to
1347/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001348TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001349 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001350 if (!DataSize)
1351 DataSize = TypeLoc::getFullDataSizeForType(T);
1352 else
1353 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001354 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001355
John McCallbcd03502009-12-07 02:54:59 +00001356 TypeSourceInfo *TInfo =
1357 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1358 new (TInfo) TypeSourceInfo(T);
1359 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001360}
1361
John McCallbcd03502009-12-07 02:54:59 +00001362TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001363 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001364 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001365 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001366 return DI;
1367}
1368
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001369const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001370ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001371 return getObjCLayout(D, 0);
1372}
1373
1374const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001375ASTContext::getASTObjCImplementationLayout(
1376 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001377 return getObjCLayout(D->getClassInterface(), D);
1378}
1379
Chris Lattner983a8bb2007-07-13 22:13:22 +00001380//===----------------------------------------------------------------------===//
1381// Type creation/memoization methods
1382//===----------------------------------------------------------------------===//
1383
Jay Foad39c79802011-01-12 09:06:06 +00001384QualType
John McCall33ddac02011-01-19 10:06:00 +00001385ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1386 unsigned fastQuals = quals.getFastQualifiers();
1387 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001388
1389 // Check if we've already instantiated this type.
1390 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001391 ExtQuals::Profile(ID, baseType, quals);
1392 void *insertPos = 0;
1393 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1394 assert(eq->getQualifiers() == quals);
1395 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001396 }
1397
John McCall33ddac02011-01-19 10:06:00 +00001398 // If the base type is not canonical, make the appropriate canonical type.
1399 QualType canon;
1400 if (!baseType->isCanonicalUnqualified()) {
1401 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001402 canonSplit.Quals.addConsistentQualifiers(quals);
1403 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001404
1405 // Re-find the insert position.
1406 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1407 }
1408
1409 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1410 ExtQualNodes.InsertNode(eq, insertPos);
1411 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001412}
1413
Jay Foad39c79802011-01-12 09:06:06 +00001414QualType
1415ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001416 QualType CanT = getCanonicalType(T);
1417 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001418 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001419
John McCall8ccfcb52009-09-24 19:53:00 +00001420 // If we are composing extended qualifiers together, merge together
1421 // into one ExtQuals node.
1422 QualifierCollector Quals;
1423 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001424
John McCall8ccfcb52009-09-24 19:53:00 +00001425 // If this type already has an address space specified, it cannot get
1426 // another one.
1427 assert(!Quals.hasAddressSpace() &&
1428 "Type cannot be in multiple addr spaces!");
1429 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001430
John McCall8ccfcb52009-09-24 19:53:00 +00001431 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001432}
1433
Chris Lattnerd60183d2009-02-18 22:53:11 +00001434QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001435 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001436 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001437 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001438 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001439
John McCall53fa7142010-12-24 02:08:15 +00001440 if (const PointerType *ptr = T->getAs<PointerType>()) {
1441 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001442 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001443 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1444 return getPointerType(ResultType);
1445 }
1446 }
Mike Stump11289f42009-09-09 15:08:12 +00001447
John McCall8ccfcb52009-09-24 19:53:00 +00001448 // If we are composing extended qualifiers together, merge together
1449 // into one ExtQuals node.
1450 QualifierCollector Quals;
1451 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001452
John McCall8ccfcb52009-09-24 19:53:00 +00001453 // If this type already has an ObjCGC specified, it cannot get
1454 // another one.
1455 assert(!Quals.hasObjCGCAttr() &&
1456 "Type cannot have multiple ObjCGCs!");
1457 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001458
John McCall8ccfcb52009-09-24 19:53:00 +00001459 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001460}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001461
John McCall4f5019e2010-12-19 02:44:49 +00001462const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1463 FunctionType::ExtInfo Info) {
1464 if (T->getExtInfo() == Info)
1465 return T;
1466
1467 QualType Result;
1468 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1469 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1470 } else {
1471 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1472 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1473 EPI.ExtInfo = Info;
1474 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1475 FPT->getNumArgs(), EPI);
1476 }
1477
1478 return cast<FunctionType>(Result.getTypePtr());
1479}
1480
Chris Lattnerc6395932007-06-22 20:56:16 +00001481/// getComplexType - Return the uniqued reference to the type for a complex
1482/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001483QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001484 // Unique pointers, to guarantee there is only one pointer of a particular
1485 // structure.
1486 llvm::FoldingSetNodeID ID;
1487 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001488
Chris Lattnerc6395932007-06-22 20:56:16 +00001489 void *InsertPos = 0;
1490 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1491 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001492
Chris Lattnerc6395932007-06-22 20:56:16 +00001493 // If the pointee type isn't canonical, this won't be a canonical type either,
1494 // so fill in the canonical type field.
1495 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001496 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001497 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001498
Chris Lattnerc6395932007-06-22 20:56:16 +00001499 // Get the new insert position for the node we care about.
1500 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001501 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001502 }
John McCall90d1c2d2009-09-24 23:30:46 +00001503 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001504 Types.push_back(New);
1505 ComplexTypes.InsertNode(New, InsertPos);
1506 return QualType(New, 0);
1507}
1508
Chris Lattner970e54e2006-11-12 00:37:36 +00001509/// getPointerType - Return the uniqued reference to the type for a pointer to
1510/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001511QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001512 // Unique pointers, to guarantee there is only one pointer of a particular
1513 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001514 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001515 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001516
Chris Lattner67521df2007-01-27 01:29:36 +00001517 void *InsertPos = 0;
1518 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001519 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001520
Chris Lattner7ccecb92006-11-12 08:50:50 +00001521 // If the pointee type isn't canonical, this won't be a canonical type either,
1522 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001523 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001524 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001525 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001526
Chris Lattner67521df2007-01-27 01:29:36 +00001527 // Get the new insert position for the node we care about.
1528 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001529 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001530 }
John McCall90d1c2d2009-09-24 23:30:46 +00001531 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001532 Types.push_back(New);
1533 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001534 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001535}
1536
Mike Stump11289f42009-09-09 15:08:12 +00001537/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001538/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001539QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001540 assert(T->isFunctionType() && "block of function types only");
1541 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001542 // structure.
1543 llvm::FoldingSetNodeID ID;
1544 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001545
Steve Naroffec33ed92008-08-27 16:04:49 +00001546 void *InsertPos = 0;
1547 if (BlockPointerType *PT =
1548 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1549 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001550
1551 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001552 // type either so fill in the canonical type field.
1553 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001554 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001555 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001556
Steve Naroffec33ed92008-08-27 16:04:49 +00001557 // Get the new insert position for the node we care about.
1558 BlockPointerType *NewIP =
1559 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001560 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001561 }
John McCall90d1c2d2009-09-24 23:30:46 +00001562 BlockPointerType *New
1563 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001564 Types.push_back(New);
1565 BlockPointerTypes.InsertNode(New, InsertPos);
1566 return QualType(New, 0);
1567}
1568
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001569/// getLValueReferenceType - Return the uniqued reference to the type for an
1570/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001571QualType
1572ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001573 assert(getCanonicalType(T) != OverloadTy &&
1574 "Unresolved overloaded function type");
1575
Bill Wendling3708c182007-05-27 10:15:43 +00001576 // Unique pointers, to guarantee there is only one pointer of a particular
1577 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001578 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001579 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001580
1581 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001582 if (LValueReferenceType *RT =
1583 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001584 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001585
John McCallfc93cf92009-10-22 22:37:11 +00001586 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1587
Bill Wendling3708c182007-05-27 10:15:43 +00001588 // If the referencee type isn't canonical, this won't be a canonical type
1589 // either, so fill in the canonical type field.
1590 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001591 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1592 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1593 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001594
Bill Wendling3708c182007-05-27 10:15:43 +00001595 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001596 LValueReferenceType *NewIP =
1597 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001598 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001599 }
1600
John McCall90d1c2d2009-09-24 23:30:46 +00001601 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001602 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1603 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001604 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001605 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001606
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001607 return QualType(New, 0);
1608}
1609
1610/// getRValueReferenceType - Return the uniqued reference to the type for an
1611/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001612QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001613 // Unique pointers, to guarantee there is only one pointer of a particular
1614 // structure.
1615 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001616 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001617
1618 void *InsertPos = 0;
1619 if (RValueReferenceType *RT =
1620 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1621 return QualType(RT, 0);
1622
John McCallfc93cf92009-10-22 22:37:11 +00001623 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1624
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001625 // If the referencee type isn't canonical, this won't be a canonical type
1626 // either, so fill in the canonical type field.
1627 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001628 if (InnerRef || !T.isCanonical()) {
1629 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1630 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001631
1632 // Get the new insert position for the node we care about.
1633 RValueReferenceType *NewIP =
1634 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001635 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001636 }
1637
John McCall90d1c2d2009-09-24 23:30:46 +00001638 RValueReferenceType *New
1639 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001640 Types.push_back(New);
1641 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001642 return QualType(New, 0);
1643}
1644
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001645/// getMemberPointerType - Return the uniqued reference to the type for a
1646/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001647QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001648 // Unique pointers, to guarantee there is only one pointer of a particular
1649 // structure.
1650 llvm::FoldingSetNodeID ID;
1651 MemberPointerType::Profile(ID, T, Cls);
1652
1653 void *InsertPos = 0;
1654 if (MemberPointerType *PT =
1655 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1656 return QualType(PT, 0);
1657
1658 // If the pointee or class type isn't canonical, this won't be a canonical
1659 // type either, so fill in the canonical type field.
1660 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001661 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001662 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1663
1664 // Get the new insert position for the node we care about.
1665 MemberPointerType *NewIP =
1666 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001667 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001668 }
John McCall90d1c2d2009-09-24 23:30:46 +00001669 MemberPointerType *New
1670 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001671 Types.push_back(New);
1672 MemberPointerTypes.InsertNode(New, InsertPos);
1673 return QualType(New, 0);
1674}
1675
Mike Stump11289f42009-09-09 15:08:12 +00001676/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001677/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001678QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001679 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001680 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001681 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001682 assert((EltTy->isDependentType() ||
1683 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001684 "Constant array of VLAs is illegal!");
1685
Chris Lattnere2df3f92009-05-13 04:12:56 +00001686 // Convert the array size into a canonical width matching the pointer size for
1687 // the target.
1688 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001689 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001690 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001691
Chris Lattner23b7eb62007-06-15 23:05:46 +00001692 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001693 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001694
Chris Lattner36f8e652007-01-27 08:31:04 +00001695 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001696 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001697 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001698 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001699
John McCall33ddac02011-01-19 10:06:00 +00001700 // If the element type isn't canonical or has qualifiers, this won't
1701 // be a canonical type either, so fill in the canonical type field.
1702 QualType Canon;
1703 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1704 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001705 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001706 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001707 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001708
Chris Lattner36f8e652007-01-27 08:31:04 +00001709 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001710 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001711 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001712 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001713 }
Mike Stump11289f42009-09-09 15:08:12 +00001714
John McCall90d1c2d2009-09-24 23:30:46 +00001715 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001716 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001717 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001718 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001719 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001720}
1721
John McCall06549462011-01-18 08:40:38 +00001722/// getVariableArrayDecayedType - Turns the given type, which may be
1723/// variably-modified, into the corresponding type with all the known
1724/// sizes replaced with [*].
1725QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1726 // Vastly most common case.
1727 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001728
John McCall06549462011-01-18 08:40:38 +00001729 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001730
John McCall06549462011-01-18 08:40:38 +00001731 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001732 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001733 switch (ty->getTypeClass()) {
1734#define TYPE(Class, Base)
1735#define ABSTRACT_TYPE(Class, Base)
1736#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1737#include "clang/AST/TypeNodes.def"
1738 llvm_unreachable("didn't desugar past all non-canonical types?");
1739
1740 // These types should never be variably-modified.
1741 case Type::Builtin:
1742 case Type::Complex:
1743 case Type::Vector:
1744 case Type::ExtVector:
1745 case Type::DependentSizedExtVector:
1746 case Type::ObjCObject:
1747 case Type::ObjCInterface:
1748 case Type::ObjCObjectPointer:
1749 case Type::Record:
1750 case Type::Enum:
1751 case Type::UnresolvedUsing:
1752 case Type::TypeOfExpr:
1753 case Type::TypeOf:
1754 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001755 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001756 case Type::DependentName:
1757 case Type::InjectedClassName:
1758 case Type::TemplateSpecialization:
1759 case Type::DependentTemplateSpecialization:
1760 case Type::TemplateTypeParm:
1761 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001762 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001763 case Type::PackExpansion:
1764 llvm_unreachable("type should never be variably-modified");
1765
1766 // These types can be variably-modified but should never need to
1767 // further decay.
1768 case Type::FunctionNoProto:
1769 case Type::FunctionProto:
1770 case Type::BlockPointer:
1771 case Type::MemberPointer:
1772 return type;
1773
1774 // These types can be variably-modified. All these modifications
1775 // preserve structure except as noted by comments.
1776 // TODO: if we ever care about optimizing VLAs, there are no-op
1777 // optimizations available here.
1778 case Type::Pointer:
1779 result = getPointerType(getVariableArrayDecayedType(
1780 cast<PointerType>(ty)->getPointeeType()));
1781 break;
1782
1783 case Type::LValueReference: {
1784 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1785 result = getLValueReferenceType(
1786 getVariableArrayDecayedType(lv->getPointeeType()),
1787 lv->isSpelledAsLValue());
1788 break;
1789 }
1790
1791 case Type::RValueReference: {
1792 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1793 result = getRValueReferenceType(
1794 getVariableArrayDecayedType(lv->getPointeeType()));
1795 break;
1796 }
1797
Eli Friedman0dfb8892011-10-06 23:00:33 +00001798 case Type::Atomic: {
1799 const AtomicType *at = cast<AtomicType>(ty);
1800 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1801 break;
1802 }
1803
John McCall06549462011-01-18 08:40:38 +00001804 case Type::ConstantArray: {
1805 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1806 result = getConstantArrayType(
1807 getVariableArrayDecayedType(cat->getElementType()),
1808 cat->getSize(),
1809 cat->getSizeModifier(),
1810 cat->getIndexTypeCVRQualifiers());
1811 break;
1812 }
1813
1814 case Type::DependentSizedArray: {
1815 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1816 result = getDependentSizedArrayType(
1817 getVariableArrayDecayedType(dat->getElementType()),
1818 dat->getSizeExpr(),
1819 dat->getSizeModifier(),
1820 dat->getIndexTypeCVRQualifiers(),
1821 dat->getBracketsRange());
1822 break;
1823 }
1824
1825 // Turn incomplete types into [*] types.
1826 case Type::IncompleteArray: {
1827 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1828 result = getVariableArrayType(
1829 getVariableArrayDecayedType(iat->getElementType()),
1830 /*size*/ 0,
1831 ArrayType::Normal,
1832 iat->getIndexTypeCVRQualifiers(),
1833 SourceRange());
1834 break;
1835 }
1836
1837 // Turn VLA types into [*] types.
1838 case Type::VariableArray: {
1839 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1840 result = getVariableArrayType(
1841 getVariableArrayDecayedType(vat->getElementType()),
1842 /*size*/ 0,
1843 ArrayType::Star,
1844 vat->getIndexTypeCVRQualifiers(),
1845 vat->getBracketsRange());
1846 break;
1847 }
1848 }
1849
1850 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00001851 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00001852}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001853
Steve Naroffcadebd02007-08-30 18:14:25 +00001854/// getVariableArrayType - Returns a non-unique reference to the type for a
1855/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001856QualType ASTContext::getVariableArrayType(QualType EltTy,
1857 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001858 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001859 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001860 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001861 // Since we don't unique expressions, it isn't possible to unique VLA's
1862 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001863 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001864
John McCall33ddac02011-01-19 10:06:00 +00001865 // Be sure to pull qualifiers off the element type.
1866 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1867 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001868 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001869 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00001870 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001871 }
1872
John McCall90d1c2d2009-09-24 23:30:46 +00001873 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001874 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001875
1876 VariableArrayTypes.push_back(New);
1877 Types.push_back(New);
1878 return QualType(New, 0);
1879}
1880
Douglas Gregor4619e432008-12-05 23:32:09 +00001881/// getDependentSizedArrayType - Returns a non-unique reference to
1882/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001883/// type.
John McCall33ddac02011-01-19 10:06:00 +00001884QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1885 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001886 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001887 unsigned elementTypeQuals,
1888 SourceRange brackets) const {
1889 assert((!numElements || numElements->isTypeDependent() ||
1890 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001891 "Size must be type- or value-dependent!");
1892
John McCall33ddac02011-01-19 10:06:00 +00001893 // Dependently-sized array types that do not have a specified number
1894 // of elements will have their sizes deduced from a dependent
1895 // initializer. We do no canonicalization here at all, which is okay
1896 // because they can't be used in most locations.
1897 if (!numElements) {
1898 DependentSizedArrayType *newType
1899 = new (*this, TypeAlignment)
1900 DependentSizedArrayType(*this, elementType, QualType(),
1901 numElements, ASM, elementTypeQuals,
1902 brackets);
1903 Types.push_back(newType);
1904 return QualType(newType, 0);
1905 }
1906
1907 // Otherwise, we actually build a new type every time, but we
1908 // also build a canonical type.
1909
1910 SplitQualType canonElementType = getCanonicalType(elementType).split();
1911
1912 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001913 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001914 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00001915 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001916 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001917
John McCall33ddac02011-01-19 10:06:00 +00001918 // Look for an existing type with these properties.
1919 DependentSizedArrayType *canonTy =
1920 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001921
John McCall33ddac02011-01-19 10:06:00 +00001922 // If we don't have one, build one.
1923 if (!canonTy) {
1924 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00001925 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001926 QualType(), numElements, ASM, elementTypeQuals,
1927 brackets);
1928 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1929 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001930 }
1931
John McCall33ddac02011-01-19 10:06:00 +00001932 // Apply qualifiers from the element type to the array.
1933 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00001934 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00001935
John McCall33ddac02011-01-19 10:06:00 +00001936 // If we didn't need extra canonicalization for the element type,
1937 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00001938 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00001939 return canon;
1940
1941 // Otherwise, we need to build a type which follows the spelling
1942 // of the element type.
1943 DependentSizedArrayType *sugaredType
1944 = new (*this, TypeAlignment)
1945 DependentSizedArrayType(*this, elementType, canon, numElements,
1946 ASM, elementTypeQuals, brackets);
1947 Types.push_back(sugaredType);
1948 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001949}
1950
John McCall33ddac02011-01-19 10:06:00 +00001951QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001952 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001953 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001954 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001955 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001956
John McCall33ddac02011-01-19 10:06:00 +00001957 void *insertPos = 0;
1958 if (IncompleteArrayType *iat =
1959 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1960 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001961
1962 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001963 // either, so fill in the canonical type field. We also have to pull
1964 // qualifiers off the element type.
1965 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001966
John McCall33ddac02011-01-19 10:06:00 +00001967 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1968 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00001969 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001970 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001971 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001972
1973 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001974 IncompleteArrayType *existing =
1975 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1976 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001977 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001978
John McCall33ddac02011-01-19 10:06:00 +00001979 IncompleteArrayType *newType = new (*this, TypeAlignment)
1980 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001981
John McCall33ddac02011-01-19 10:06:00 +00001982 IncompleteArrayTypes.InsertNode(newType, insertPos);
1983 Types.push_back(newType);
1984 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001985}
1986
Steve Naroff91fcddb2007-07-18 18:00:27 +00001987/// getVectorType - Return the unique reference to a vector type of
1988/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001989QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001990 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001991 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001992
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001993 // Check if we've already instantiated a vector of this type.
1994 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001995 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001996
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001997 void *InsertPos = 0;
1998 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1999 return QualType(VTP, 0);
2000
2001 // If the element type isn't canonical, this won't be a canonical type either,
2002 // so fill in the canonical type field.
2003 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002004 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002005 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002006
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002007 // Get the new insert position for the node we care about.
2008 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002009 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002010 }
John McCall90d1c2d2009-09-24 23:30:46 +00002011 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002012 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002013 VectorTypes.InsertNode(New, InsertPos);
2014 Types.push_back(New);
2015 return QualType(New, 0);
2016}
2017
Nate Begemance4d7fc2008-04-18 23:10:10 +00002018/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002019/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002020QualType
2021ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002022 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002023
Steve Naroff91fcddb2007-07-18 18:00:27 +00002024 // Check if we've already instantiated a vector of this type.
2025 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002026 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002027 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002028 void *InsertPos = 0;
2029 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2030 return QualType(VTP, 0);
2031
2032 // If the element type isn't canonical, this won't be a canonical type either,
2033 // so fill in the canonical type field.
2034 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002035 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002036 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002037
Steve Naroff91fcddb2007-07-18 18:00:27 +00002038 // Get the new insert position for the node we care about.
2039 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002040 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002041 }
John McCall90d1c2d2009-09-24 23:30:46 +00002042 ExtVectorType *New = new (*this, TypeAlignment)
2043 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002044 VectorTypes.InsertNode(New, InsertPos);
2045 Types.push_back(New);
2046 return QualType(New, 0);
2047}
2048
Jay Foad39c79802011-01-12 09:06:06 +00002049QualType
2050ASTContext::getDependentSizedExtVectorType(QualType vecType,
2051 Expr *SizeExpr,
2052 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002053 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002054 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002055 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002056
Douglas Gregor352169a2009-07-31 03:54:25 +00002057 void *InsertPos = 0;
2058 DependentSizedExtVectorType *Canon
2059 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2060 DependentSizedExtVectorType *New;
2061 if (Canon) {
2062 // We already have a canonical version of this array type; use it as
2063 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002064 New = new (*this, TypeAlignment)
2065 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2066 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002067 } else {
2068 QualType CanonVecTy = getCanonicalType(vecType);
2069 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002070 New = new (*this, TypeAlignment)
2071 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2072 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002073
2074 DependentSizedExtVectorType *CanonCheck
2075 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2076 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2077 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002078 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2079 } else {
2080 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2081 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002082 New = new (*this, TypeAlignment)
2083 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002084 }
2085 }
Mike Stump11289f42009-09-09 15:08:12 +00002086
Douglas Gregor758a8692009-06-17 21:51:59 +00002087 Types.push_back(New);
2088 return QualType(New, 0);
2089}
2090
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002091/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002092///
Jay Foad39c79802011-01-12 09:06:06 +00002093QualType
2094ASTContext::getFunctionNoProtoType(QualType ResultTy,
2095 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002096 const CallingConv DefaultCC = Info.getCC();
2097 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2098 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002099 // Unique functions, to guarantee there is only one function of a particular
2100 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002101 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002102 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002103
Chris Lattner47955de2007-01-27 08:37:20 +00002104 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002105 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002106 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002107 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002108
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002109 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002110 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002111 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002112 Canonical =
2113 getFunctionNoProtoType(getCanonicalType(ResultTy),
2114 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002115
Chris Lattner47955de2007-01-27 08:37:20 +00002116 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002117 FunctionNoProtoType *NewIP =
2118 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002119 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002120 }
Mike Stump11289f42009-09-09 15:08:12 +00002121
Roman Divacky65b88cd2011-03-01 17:40:53 +00002122 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002123 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002124 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002125 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002126 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002127 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002128}
2129
2130/// getFunctionType - Return a normal function type with a typed argument
2131/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002132QualType
2133ASTContext::getFunctionType(QualType ResultTy,
2134 const QualType *ArgArray, unsigned NumArgs,
2135 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002136 // Unique functions, to guarantee there is only one function of a particular
2137 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002138 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002139 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002140
2141 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002142 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002143 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002144 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002145
2146 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002147 bool isCanonical =
2148 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2149 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002150 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002151 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002152 isCanonical = false;
2153
Roman Divacky65b88cd2011-03-01 17:40:53 +00002154 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2155 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2156 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002157
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002158 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002159 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002160 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002161 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002162 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002163 CanonicalArgs.reserve(NumArgs);
2164 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002165 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002166
John McCalldb40c7f2010-12-14 08:05:40 +00002167 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002168 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002169 CanonicalEPI.ExceptionSpecType = EST_None;
2170 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002171 CanonicalEPI.ExtInfo
2172 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2173
Chris Lattner76a00cf2008-04-06 22:59:24 +00002174 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002175 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002176 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002177
Chris Lattnerfd4de792007-01-27 01:15:32 +00002178 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002179 FunctionProtoType *NewIP =
2180 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002181 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002182 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002183
John McCall31168b02011-06-15 23:02:42 +00002184 // FunctionProtoType objects are allocated with extra bytes after
2185 // them for three variable size arrays at the end:
2186 // - parameter types
2187 // - exception types
2188 // - consumed-arguments flags
2189 // Instead of the exception types, there could be a noexcept
2190 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002191 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002192 NumArgs * sizeof(QualType);
2193 if (EPI.ExceptionSpecType == EST_Dynamic)
2194 Size += EPI.NumExceptions * sizeof(QualType);
2195 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002196 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002197 }
John McCall31168b02011-06-15 23:02:42 +00002198 if (EPI.ConsumedArguments)
2199 Size += NumArgs * sizeof(bool);
2200
John McCalldb40c7f2010-12-14 08:05:40 +00002201 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002202 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2203 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002204 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002205 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002206 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002207 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002208}
Chris Lattneref51c202006-11-10 07:17:23 +00002209
John McCalle78aac42010-03-10 03:28:59 +00002210#ifndef NDEBUG
2211static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2212 if (!isa<CXXRecordDecl>(D)) return false;
2213 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2214 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2215 return true;
2216 if (RD->getDescribedClassTemplate() &&
2217 !isa<ClassTemplateSpecializationDecl>(RD))
2218 return true;
2219 return false;
2220}
2221#endif
2222
2223/// getInjectedClassNameType - Return the unique reference to the
2224/// injected class name type for the specified templated declaration.
2225QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002226 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002227 assert(NeedsInjectedClassNameType(Decl));
2228 if (Decl->TypeForDecl) {
2229 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002230 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002231 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2232 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2233 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2234 } else {
John McCall424cec92011-01-19 06:33:43 +00002235 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002236 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002237 Decl->TypeForDecl = newType;
2238 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002239 }
2240 return QualType(Decl->TypeForDecl, 0);
2241}
2242
Douglas Gregor83a586e2008-04-13 21:07:44 +00002243/// getTypeDeclType - Return the unique reference to the type for the
2244/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002245QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002246 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002247 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002248
Richard Smithdda56e42011-04-15 14:24:37 +00002249 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002250 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002251
John McCall96f0b5f2010-03-10 06:48:02 +00002252 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2253 "Template type parameter types are always available.");
2254
John McCall81e38502010-02-16 03:57:14 +00002255 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002256 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002257 "struct/union has previous declaration");
2258 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002259 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002260 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002261 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002262 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002263 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002264 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002265 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002266 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2267 Decl->TypeForDecl = newType;
2268 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002269 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002270 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002271
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002272 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002273}
2274
Chris Lattner32d920b2007-01-26 02:01:53 +00002275/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002276/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002277QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002278ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2279 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002280 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002281
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002282 if (Canonical.isNull())
2283 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002284 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002285 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002286 Decl->TypeForDecl = newType;
2287 Types.push_back(newType);
2288 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002289}
2290
Jay Foad39c79802011-01-12 09:06:06 +00002291QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002292 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2293
Douglas Gregorec9fd132012-01-14 16:38:05 +00002294 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002295 if (PrevDecl->TypeForDecl)
2296 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2297
John McCall424cec92011-01-19 06:33:43 +00002298 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2299 Decl->TypeForDecl = newType;
2300 Types.push_back(newType);
2301 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002302}
2303
Jay Foad39c79802011-01-12 09:06:06 +00002304QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002305 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2306
Douglas Gregorec9fd132012-01-14 16:38:05 +00002307 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002308 if (PrevDecl->TypeForDecl)
2309 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2310
John McCall424cec92011-01-19 06:33:43 +00002311 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2312 Decl->TypeForDecl = newType;
2313 Types.push_back(newType);
2314 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002315}
2316
John McCall81904512011-01-06 01:58:22 +00002317QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2318 QualType modifiedType,
2319 QualType equivalentType) {
2320 llvm::FoldingSetNodeID id;
2321 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2322
2323 void *insertPos = 0;
2324 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2325 if (type) return QualType(type, 0);
2326
2327 QualType canon = getCanonicalType(equivalentType);
2328 type = new (*this, TypeAlignment)
2329 AttributedType(canon, attrKind, modifiedType, equivalentType);
2330
2331 Types.push_back(type);
2332 AttributedTypes.InsertNode(type, insertPos);
2333
2334 return QualType(type, 0);
2335}
2336
2337
John McCallcebee162009-10-18 09:09:24 +00002338/// \brief Retrieve a substitution-result type.
2339QualType
2340ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002341 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002342 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002343 && "replacement types must always be canonical");
2344
2345 llvm::FoldingSetNodeID ID;
2346 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2347 void *InsertPos = 0;
2348 SubstTemplateTypeParmType *SubstParm
2349 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2350
2351 if (!SubstParm) {
2352 SubstParm = new (*this, TypeAlignment)
2353 SubstTemplateTypeParmType(Parm, Replacement);
2354 Types.push_back(SubstParm);
2355 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2356 }
2357
2358 return QualType(SubstParm, 0);
2359}
2360
Douglas Gregorada4b792011-01-14 02:55:32 +00002361/// \brief Retrieve a
2362QualType ASTContext::getSubstTemplateTypeParmPackType(
2363 const TemplateTypeParmType *Parm,
2364 const TemplateArgument &ArgPack) {
2365#ifndef NDEBUG
2366 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2367 PEnd = ArgPack.pack_end();
2368 P != PEnd; ++P) {
2369 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2370 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2371 }
2372#endif
2373
2374 llvm::FoldingSetNodeID ID;
2375 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2376 void *InsertPos = 0;
2377 if (SubstTemplateTypeParmPackType *SubstParm
2378 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2379 return QualType(SubstParm, 0);
2380
2381 QualType Canon;
2382 if (!Parm->isCanonicalUnqualified()) {
2383 Canon = getCanonicalType(QualType(Parm, 0));
2384 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2385 ArgPack);
2386 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2387 }
2388
2389 SubstTemplateTypeParmPackType *SubstParm
2390 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2391 ArgPack);
2392 Types.push_back(SubstParm);
2393 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2394 return QualType(SubstParm, 0);
2395}
2396
Douglas Gregoreff93e02009-02-05 23:33:38 +00002397/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002398/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002399/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002400QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002401 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002402 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002403 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002404 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002405 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002406 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002407 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2408
2409 if (TypeParm)
2410 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002411
Chandler Carruth08836322011-05-01 00:51:33 +00002412 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002413 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002414 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002415
2416 TemplateTypeParmType *TypeCheck
2417 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2418 assert(!TypeCheck && "Template type parameter canonical type broken");
2419 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002420 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002421 TypeParm = new (*this, TypeAlignment)
2422 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002423
2424 Types.push_back(TypeParm);
2425 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2426
2427 return QualType(TypeParm, 0);
2428}
2429
John McCalle78aac42010-03-10 03:28:59 +00002430TypeSourceInfo *
2431ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2432 SourceLocation NameLoc,
2433 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002434 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002435 assert(!Name.getAsDependentTemplateName() &&
2436 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002437 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002438
2439 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2440 TemplateSpecializationTypeLoc TL
2441 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002442 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002443 TL.setTemplateNameLoc(NameLoc);
2444 TL.setLAngleLoc(Args.getLAngleLoc());
2445 TL.setRAngleLoc(Args.getRAngleLoc());
2446 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2447 TL.setArgLocInfo(i, Args[i].getLocInfo());
2448 return DI;
2449}
2450
Mike Stump11289f42009-09-09 15:08:12 +00002451QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002452ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002453 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002454 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002455 assert(!Template.getAsDependentTemplateName() &&
2456 "No dependent template names here!");
2457
John McCall6b51f282009-11-23 01:53:49 +00002458 unsigned NumArgs = Args.size();
2459
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002460 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002461 ArgVec.reserve(NumArgs);
2462 for (unsigned i = 0; i != NumArgs; ++i)
2463 ArgVec.push_back(Args[i].getArgument());
2464
John McCall2408e322010-04-27 00:57:59 +00002465 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002466 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002467}
2468
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002469#ifndef NDEBUG
2470static bool hasAnyPackExpansions(const TemplateArgument *Args,
2471 unsigned NumArgs) {
2472 for (unsigned I = 0; I != NumArgs; ++I)
2473 if (Args[I].isPackExpansion())
2474 return true;
2475
2476 return true;
2477}
2478#endif
2479
John McCall0ad16662009-10-29 08:12:44 +00002480QualType
2481ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002482 const TemplateArgument *Args,
2483 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002484 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002485 assert(!Template.getAsDependentTemplateName() &&
2486 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002487 // Look through qualified template names.
2488 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2489 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002490
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002491 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002492 Template.getAsTemplateDecl() &&
2493 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002494 QualType CanonType;
2495 if (!Underlying.isNull())
2496 CanonType = getCanonicalType(Underlying);
2497 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002498 // We can get here with an alias template when the specialization contains
2499 // a pack expansion that does not match up with a parameter pack.
2500 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2501 "Caller must compute aliased type");
2502 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002503 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2504 NumArgs);
2505 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002506
Douglas Gregora8e02e72009-07-28 23:00:59 +00002507 // Allocate the (non-canonical) template specialization type, but don't
2508 // try to unique it: these types typically have location information that
2509 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002510 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2511 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002512 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002513 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002514 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002515 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2516 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002517
Douglas Gregor8bf42052009-02-09 18:46:07 +00002518 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002519 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002520}
2521
Mike Stump11289f42009-09-09 15:08:12 +00002522QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002523ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2524 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002525 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002526 assert(!Template.getAsDependentTemplateName() &&
2527 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002528
Douglas Gregore29139c2011-03-03 17:04:51 +00002529 // Look through qualified template names.
2530 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2531 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002532
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002533 // Build the canonical template specialization type.
2534 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002535 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002536 CanonArgs.reserve(NumArgs);
2537 for (unsigned I = 0; I != NumArgs; ++I)
2538 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2539
2540 // Determine whether this canonical template specialization type already
2541 // exists.
2542 llvm::FoldingSetNodeID ID;
2543 TemplateSpecializationType::Profile(ID, CanonTemplate,
2544 CanonArgs.data(), NumArgs, *this);
2545
2546 void *InsertPos = 0;
2547 TemplateSpecializationType *Spec
2548 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2549
2550 if (!Spec) {
2551 // Allocate a new canonical template specialization type.
2552 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2553 sizeof(TemplateArgument) * NumArgs),
2554 TypeAlignment);
2555 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2556 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002557 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002558 Types.push_back(Spec);
2559 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2560 }
2561
2562 assert(Spec->isDependentType() &&
2563 "Non-dependent template-id type must have a canonical type");
2564 return QualType(Spec, 0);
2565}
2566
2567QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002568ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2569 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002570 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002571 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002572 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002573
2574 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002575 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002576 if (T)
2577 return QualType(T, 0);
2578
Douglas Gregorc42075a2010-02-04 18:10:26 +00002579 QualType Canon = NamedType;
2580 if (!Canon.isCanonical()) {
2581 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002582 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2583 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002584 (void)CheckT;
2585 }
2586
Abramo Bagnara6150c882010-05-11 21:36:43 +00002587 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002588 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002589 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002590 return QualType(T, 0);
2591}
2592
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002593QualType
Jay Foad39c79802011-01-12 09:06:06 +00002594ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002595 llvm::FoldingSetNodeID ID;
2596 ParenType::Profile(ID, InnerType);
2597
2598 void *InsertPos = 0;
2599 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2600 if (T)
2601 return QualType(T, 0);
2602
2603 QualType Canon = InnerType;
2604 if (!Canon.isCanonical()) {
2605 Canon = getCanonicalType(InnerType);
2606 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2607 assert(!CheckT && "Paren canonical type broken");
2608 (void)CheckT;
2609 }
2610
2611 T = new (*this) ParenType(InnerType, Canon);
2612 Types.push_back(T);
2613 ParenTypes.InsertNode(T, InsertPos);
2614 return QualType(T, 0);
2615}
2616
Douglas Gregor02085352010-03-31 20:19:30 +00002617QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2618 NestedNameSpecifier *NNS,
2619 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002620 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002621 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2622
2623 if (Canon.isNull()) {
2624 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002625 ElaboratedTypeKeyword CanonKeyword = Keyword;
2626 if (Keyword == ETK_None)
2627 CanonKeyword = ETK_Typename;
2628
2629 if (CanonNNS != NNS || CanonKeyword != Keyword)
2630 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002631 }
2632
2633 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002634 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002635
2636 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002637 DependentNameType *T
2638 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002639 if (T)
2640 return QualType(T, 0);
2641
Douglas Gregor02085352010-03-31 20:19:30 +00002642 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002643 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002644 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002645 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002646}
2647
Mike Stump11289f42009-09-09 15:08:12 +00002648QualType
John McCallc392f372010-06-11 00:33:02 +00002649ASTContext::getDependentTemplateSpecializationType(
2650 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002651 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002652 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002653 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002654 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002655 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002656 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2657 ArgCopy.push_back(Args[I].getArgument());
2658 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2659 ArgCopy.size(),
2660 ArgCopy.data());
2661}
2662
2663QualType
2664ASTContext::getDependentTemplateSpecializationType(
2665 ElaboratedTypeKeyword Keyword,
2666 NestedNameSpecifier *NNS,
2667 const IdentifierInfo *Name,
2668 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002669 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002670 assert((!NNS || NNS->isDependent()) &&
2671 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002672
Douglas Gregorc42075a2010-02-04 18:10:26 +00002673 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002674 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2675 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002676
2677 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002678 DependentTemplateSpecializationType *T
2679 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002680 if (T)
2681 return QualType(T, 0);
2682
John McCallc392f372010-06-11 00:33:02 +00002683 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002684
John McCallc392f372010-06-11 00:33:02 +00002685 ElaboratedTypeKeyword CanonKeyword = Keyword;
2686 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2687
2688 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002689 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002690 for (unsigned I = 0; I != NumArgs; ++I) {
2691 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2692 if (!CanonArgs[I].structurallyEquals(Args[I]))
2693 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002694 }
2695
John McCallc392f372010-06-11 00:33:02 +00002696 QualType Canon;
2697 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2698 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2699 Name, NumArgs,
2700 CanonArgs.data());
2701
2702 // Find the insert position again.
2703 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2704 }
2705
2706 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2707 sizeof(TemplateArgument) * NumArgs),
2708 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002709 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002710 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002711 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002712 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002713 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002714}
2715
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002716QualType ASTContext::getPackExpansionType(QualType Pattern,
2717 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002718 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002719 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002720
2721 assert(Pattern->containsUnexpandedParameterPack() &&
2722 "Pack expansions must expand one or more parameter packs");
2723 void *InsertPos = 0;
2724 PackExpansionType *T
2725 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2726 if (T)
2727 return QualType(T, 0);
2728
2729 QualType Canon;
2730 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002731 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002732
2733 // Find the insert position again.
2734 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2735 }
2736
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002737 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002738 Types.push_back(T);
2739 PackExpansionTypes.InsertNode(T, InsertPos);
2740 return QualType(T, 0);
2741}
2742
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002743/// CmpProtocolNames - Comparison predicate for sorting protocols
2744/// alphabetically.
2745static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2746 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002747 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002748}
2749
John McCall8b07ec22010-05-15 11:32:37 +00002750static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002751 unsigned NumProtocols) {
2752 if (NumProtocols == 0) return true;
2753
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002754 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2755 return false;
2756
John McCallfc93cf92009-10-22 22:37:11 +00002757 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002758 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2759 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002760 return false;
2761 return true;
2762}
2763
2764static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002765 unsigned &NumProtocols) {
2766 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002767
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002768 // Sort protocols, keyed by name.
2769 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2770
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002771 // Canonicalize.
2772 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2773 Protocols[I] = Protocols[I]->getCanonicalDecl();
2774
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002775 // Remove duplicates.
2776 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2777 NumProtocols = ProtocolsEnd-Protocols;
2778}
2779
John McCall8b07ec22010-05-15 11:32:37 +00002780QualType ASTContext::getObjCObjectType(QualType BaseType,
2781 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002782 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002783 // If the base type is an interface and there aren't any protocols
2784 // to add, then the interface type will do just fine.
2785 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2786 return BaseType;
2787
2788 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002789 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002790 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002791 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002792 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2793 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002794
John McCall8b07ec22010-05-15 11:32:37 +00002795 // Build the canonical type, which has the canonical base type and
2796 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002797 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002798 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2799 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2800 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002801 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002802 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002803 unsigned UniqueCount = NumProtocols;
2804
John McCallfc93cf92009-10-22 22:37:11 +00002805 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002806 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2807 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002808 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002809 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2810 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002811 }
2812
2813 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002814 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2815 }
2816
2817 unsigned Size = sizeof(ObjCObjectTypeImpl);
2818 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2819 void *Mem = Allocate(Size, TypeAlignment);
2820 ObjCObjectTypeImpl *T =
2821 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2822
2823 Types.push_back(T);
2824 ObjCObjectTypes.InsertNode(T, InsertPos);
2825 return QualType(T, 0);
2826}
2827
2828/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2829/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002830QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002831 llvm::FoldingSetNodeID ID;
2832 ObjCObjectPointerType::Profile(ID, ObjectT);
2833
2834 void *InsertPos = 0;
2835 if (ObjCObjectPointerType *QT =
2836 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2837 return QualType(QT, 0);
2838
2839 // Find the canonical object type.
2840 QualType Canonical;
2841 if (!ObjectT.isCanonical()) {
2842 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2843
2844 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002845 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2846 }
2847
Douglas Gregorf85bee62010-02-08 22:59:26 +00002848 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002849 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2850 ObjCObjectPointerType *QType =
2851 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002852
Steve Narofffb4330f2009-06-17 22:40:22 +00002853 Types.push_back(QType);
2854 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002855 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002856}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002857
Douglas Gregor1c283312010-08-11 12:19:30 +00002858/// getObjCInterfaceType - Return the unique reference to the type for the
2859/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002860QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2861 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002862 if (Decl->TypeForDecl)
2863 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002864
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002865 if (PrevDecl) {
2866 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2867 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2868 return QualType(PrevDecl->TypeForDecl, 0);
2869 }
2870
Douglas Gregor7671e532011-12-16 16:34:57 +00002871 // Prefer the definition, if there is one.
2872 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2873 Decl = Def;
2874
Douglas Gregor1c283312010-08-11 12:19:30 +00002875 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2876 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2877 Decl->TypeForDecl = T;
2878 Types.push_back(T);
2879 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002880}
2881
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002882/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2883/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002884/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002885/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002886/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002887QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002888 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002889 if (tofExpr->isTypeDependent()) {
2890 llvm::FoldingSetNodeID ID;
2891 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002892
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002893 void *InsertPos = 0;
2894 DependentTypeOfExprType *Canon
2895 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2896 if (Canon) {
2897 // We already have a "canonical" version of an identical, dependent
2898 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002899 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002900 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002901 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002902 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002903 Canon
2904 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002905 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2906 toe = Canon;
2907 }
2908 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002909 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002910 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002911 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002912 Types.push_back(toe);
2913 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002914}
2915
Steve Naroffa773cd52007-08-01 18:02:17 +00002916/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2917/// TypeOfType AST's. The only motivation to unique these nodes would be
2918/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002919/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002920/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002921QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002922 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002923 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002924 Types.push_back(tot);
2925 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002926}
2927
Anders Carlssonad6bd352009-06-24 21:24:56 +00002928
Anders Carlsson81df7b82009-06-24 19:06:50 +00002929/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2930/// DecltypeType AST's. The only motivation to unique these nodes would be
2931/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002932/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00002933/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00002934QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002935 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002936
2937 // C++0x [temp.type]p2:
2938 // If an expression e involves a template parameter, decltype(e) denotes a
2939 // unique dependent type. Two such decltype-specifiers refer to the same
2940 // type only if their expressions are equivalent (14.5.6.1).
2941 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002942 llvm::FoldingSetNodeID ID;
2943 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002944
Douglas Gregora21f6c32009-07-30 23:36:40 +00002945 void *InsertPos = 0;
2946 DependentDecltypeType *Canon
2947 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2948 if (Canon) {
2949 // We already have a "canonical" version of an equivalent, dependent
2950 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002951 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002952 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002953 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002954 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002955 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002956 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2957 dt = Canon;
2958 }
2959 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00002960 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
2961 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00002962 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002963 Types.push_back(dt);
2964 return QualType(dt, 0);
2965}
2966
Alexis Hunte852b102011-05-24 22:41:36 +00002967/// getUnaryTransformationType - We don't unique these, since the memory
2968/// savings are minimal and these are rare.
2969QualType ASTContext::getUnaryTransformType(QualType BaseType,
2970 QualType UnderlyingType,
2971 UnaryTransformType::UTTKind Kind)
2972 const {
2973 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002974 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2975 Kind,
2976 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00002977 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00002978 Types.push_back(Ty);
2979 return QualType(Ty, 0);
2980}
2981
Richard Smithb2bc2e62011-02-21 20:05:19 +00002982/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002983QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002984 void *InsertPos = 0;
2985 if (!DeducedType.isNull()) {
2986 // Look in the folding set for an existing type.
2987 llvm::FoldingSetNodeID ID;
2988 AutoType::Profile(ID, DeducedType);
2989 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2990 return QualType(AT, 0);
2991 }
2992
2993 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2994 Types.push_back(AT);
2995 if (InsertPos)
2996 AutoTypes.InsertNode(AT, InsertPos);
2997 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002998}
2999
Eli Friedman0dfb8892011-10-06 23:00:33 +00003000/// getAtomicType - Return the uniqued reference to the atomic type for
3001/// the given value type.
3002QualType ASTContext::getAtomicType(QualType T) const {
3003 // Unique pointers, to guarantee there is only one pointer of a particular
3004 // structure.
3005 llvm::FoldingSetNodeID ID;
3006 AtomicType::Profile(ID, T);
3007
3008 void *InsertPos = 0;
3009 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3010 return QualType(AT, 0);
3011
3012 // If the atomic value type isn't canonical, this won't be a canonical type
3013 // either, so fill in the canonical type field.
3014 QualType Canonical;
3015 if (!T.isCanonical()) {
3016 Canonical = getAtomicType(getCanonicalType(T));
3017
3018 // Get the new insert position for the node we care about.
3019 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3020 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3021 }
3022 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3023 Types.push_back(New);
3024 AtomicTypes.InsertNode(New, InsertPos);
3025 return QualType(New, 0);
3026}
3027
Richard Smith02e85f32011-04-14 22:09:26 +00003028/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3029QualType ASTContext::getAutoDeductType() const {
3030 if (AutoDeductTy.isNull())
3031 AutoDeductTy = getAutoType(QualType());
3032 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3033 return AutoDeductTy;
3034}
3035
3036/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3037QualType ASTContext::getAutoRRefDeductType() const {
3038 if (AutoRRefDeductTy.isNull())
3039 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3040 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3041 return AutoRRefDeductTy;
3042}
3043
Chris Lattnerfb072462007-01-23 05:45:31 +00003044/// getTagDeclType - Return the unique reference to the type for the
3045/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003046QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003047 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003048 // FIXME: What is the design on getTagDeclType when it requires casting
3049 // away const? mutable?
3050 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003051}
3052
Mike Stump11289f42009-09-09 15:08:12 +00003053/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3054/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3055/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003056CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003057 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003058}
Chris Lattnerfb072462007-01-23 05:45:31 +00003059
Hans Wennborg27541db2011-10-27 08:29:09 +00003060/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3061CanQualType ASTContext::getIntMaxType() const {
3062 return getFromTargetType(Target->getIntMaxType());
3063}
3064
3065/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3066CanQualType ASTContext::getUIntMaxType() const {
3067 return getFromTargetType(Target->getUIntMaxType());
3068}
3069
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003070/// getSignedWCharType - Return the type of "signed wchar_t".
3071/// Used when in C++, as a GCC extension.
3072QualType ASTContext::getSignedWCharType() const {
3073 // FIXME: derive from "Target" ?
3074 return WCharTy;
3075}
3076
3077/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3078/// Used when in C++, as a GCC extension.
3079QualType ASTContext::getUnsignedWCharType() const {
3080 // FIXME: derive from "Target" ?
3081 return UnsignedIntTy;
3082}
3083
Hans Wennborg27541db2011-10-27 08:29:09 +00003084/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003085/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3086QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003087 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003088}
3089
Chris Lattnera21ad802008-04-02 05:18:44 +00003090//===----------------------------------------------------------------------===//
3091// Type Operators
3092//===----------------------------------------------------------------------===//
3093
Jay Foad39c79802011-01-12 09:06:06 +00003094CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003095 // Push qualifiers into arrays, and then discard any remaining
3096 // qualifiers.
3097 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003098 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003099 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003100 QualType Result;
3101 if (isa<ArrayType>(Ty)) {
3102 Result = getArrayDecayedType(QualType(Ty,0));
3103 } else if (isa<FunctionType>(Ty)) {
3104 Result = getPointerType(QualType(Ty, 0));
3105 } else {
3106 Result = QualType(Ty, 0);
3107 }
3108
3109 return CanQualType::CreateUnsafe(Result);
3110}
3111
John McCall6c9dd522011-01-18 07:41:22 +00003112QualType ASTContext::getUnqualifiedArrayType(QualType type,
3113 Qualifiers &quals) {
3114 SplitQualType splitType = type.getSplitUnqualifiedType();
3115
3116 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3117 // the unqualified desugared type and then drops it on the floor.
3118 // We then have to strip that sugar back off with
3119 // getUnqualifiedDesugaredType(), which is silly.
3120 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003121 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003122
3123 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003124 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003125 quals = splitType.Quals;
3126 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003127 }
3128
John McCall6c9dd522011-01-18 07:41:22 +00003129 // Otherwise, recurse on the array's element type.
3130 QualType elementType = AT->getElementType();
3131 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3132
3133 // If that didn't change the element type, AT has no qualifiers, so we
3134 // can just use the results in splitType.
3135 if (elementType == unqualElementType) {
3136 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003137 quals = splitType.Quals;
3138 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003139 }
3140
3141 // Otherwise, add in the qualifiers from the outermost type, then
3142 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003143 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003144
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003145 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003146 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003147 CAT->getSizeModifier(), 0);
3148 }
3149
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003150 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003151 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003152 }
3153
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003154 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003155 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003156 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003157 VAT->getSizeModifier(),
3158 VAT->getIndexTypeCVRQualifiers(),
3159 VAT->getBracketsRange());
3160 }
3161
3162 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003163 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003164 DSAT->getSizeModifier(), 0,
3165 SourceRange());
3166}
3167
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003168/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3169/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3170/// they point to and return true. If T1 and T2 aren't pointer types
3171/// or pointer-to-member types, or if they are not similar at this
3172/// level, returns false and leaves T1 and T2 unchanged. Top-level
3173/// qualifiers on T1 and T2 are ignored. This function will typically
3174/// be called in a loop that successively "unwraps" pointer and
3175/// pointer-to-member types to compare them at each level.
3176bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3177 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3178 *T2PtrType = T2->getAs<PointerType>();
3179 if (T1PtrType && T2PtrType) {
3180 T1 = T1PtrType->getPointeeType();
3181 T2 = T2PtrType->getPointeeType();
3182 return true;
3183 }
3184
3185 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3186 *T2MPType = T2->getAs<MemberPointerType>();
3187 if (T1MPType && T2MPType &&
3188 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3189 QualType(T2MPType->getClass(), 0))) {
3190 T1 = T1MPType->getPointeeType();
3191 T2 = T2MPType->getPointeeType();
3192 return true;
3193 }
3194
David Blaikiebbafb8a2012-03-11 07:00:24 +00003195 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003196 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3197 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3198 if (T1OPType && T2OPType) {
3199 T1 = T1OPType->getPointeeType();
3200 T2 = T2OPType->getPointeeType();
3201 return true;
3202 }
3203 }
3204
3205 // FIXME: Block pointers, too?
3206
3207 return false;
3208}
3209
Jay Foad39c79802011-01-12 09:06:06 +00003210DeclarationNameInfo
3211ASTContext::getNameForTemplate(TemplateName Name,
3212 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003213 switch (Name.getKind()) {
3214 case TemplateName::QualifiedTemplate:
3215 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003216 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003217 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3218 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003219
John McCalld9dfe3a2011-06-30 08:33:18 +00003220 case TemplateName::OverloadedTemplate: {
3221 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3222 // DNInfo work in progress: CHECKME: what about DNLoc?
3223 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3224 }
3225
3226 case TemplateName::DependentTemplate: {
3227 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003228 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003229 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003230 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3231 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003232 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003233 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3234 // DNInfo work in progress: FIXME: source locations?
3235 DeclarationNameLoc DNLoc;
3236 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3237 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3238 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003239 }
3240 }
3241
John McCalld9dfe3a2011-06-30 08:33:18 +00003242 case TemplateName::SubstTemplateTemplateParm: {
3243 SubstTemplateTemplateParmStorage *subst
3244 = Name.getAsSubstTemplateTemplateParm();
3245 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3246 NameLoc);
3247 }
3248
3249 case TemplateName::SubstTemplateTemplateParmPack: {
3250 SubstTemplateTemplateParmPackStorage *subst
3251 = Name.getAsSubstTemplateTemplateParmPack();
3252 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3253 NameLoc);
3254 }
3255 }
3256
3257 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003258}
3259
Jay Foad39c79802011-01-12 09:06:06 +00003260TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003261 switch (Name.getKind()) {
3262 case TemplateName::QualifiedTemplate:
3263 case TemplateName::Template: {
3264 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003265 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003266 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003267 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3268
3269 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003270 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003271 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003272
John McCalld9dfe3a2011-06-30 08:33:18 +00003273 case TemplateName::OverloadedTemplate:
3274 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003275
John McCalld9dfe3a2011-06-30 08:33:18 +00003276 case TemplateName::DependentTemplate: {
3277 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3278 assert(DTN && "Non-dependent template names must refer to template decls.");
3279 return DTN->CanonicalTemplateName;
3280 }
3281
3282 case TemplateName::SubstTemplateTemplateParm: {
3283 SubstTemplateTemplateParmStorage *subst
3284 = Name.getAsSubstTemplateTemplateParm();
3285 return getCanonicalTemplateName(subst->getReplacement());
3286 }
3287
3288 case TemplateName::SubstTemplateTemplateParmPack: {
3289 SubstTemplateTemplateParmPackStorage *subst
3290 = Name.getAsSubstTemplateTemplateParmPack();
3291 TemplateTemplateParmDecl *canonParameter
3292 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3293 TemplateArgument canonArgPack
3294 = getCanonicalTemplateArgument(subst->getArgumentPack());
3295 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3296 }
3297 }
3298
3299 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003300}
3301
Douglas Gregoradee3e32009-11-11 23:06:43 +00003302bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3303 X = getCanonicalTemplateName(X);
3304 Y = getCanonicalTemplateName(Y);
3305 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3306}
3307
Mike Stump11289f42009-09-09 15:08:12 +00003308TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003309ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003310 switch (Arg.getKind()) {
3311 case TemplateArgument::Null:
3312 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003313
Douglas Gregora8e02e72009-07-28 23:00:59 +00003314 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003315 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003316
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003317 case TemplateArgument::Declaration: {
3318 if (Decl *D = Arg.getAsDecl())
3319 return TemplateArgument(D->getCanonicalDecl());
3320 return TemplateArgument((Decl*)0);
3321 }
Mike Stump11289f42009-09-09 15:08:12 +00003322
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003323 case TemplateArgument::Template:
3324 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003325
3326 case TemplateArgument::TemplateExpansion:
3327 return TemplateArgument(getCanonicalTemplateName(
3328 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003329 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003330
Douglas Gregora8e02e72009-07-28 23:00:59 +00003331 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003332 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003333 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003334
Douglas Gregora8e02e72009-07-28 23:00:59 +00003335 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003336 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003337
Douglas Gregora8e02e72009-07-28 23:00:59 +00003338 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003339 if (Arg.pack_size() == 0)
3340 return Arg;
3341
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003342 TemplateArgument *CanonArgs
3343 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003344 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003345 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003346 AEnd = Arg.pack_end();
3347 A != AEnd; (void)++A, ++Idx)
3348 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003349
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003350 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003351 }
3352 }
3353
3354 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003355 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003356}
3357
Douglas Gregor333489b2009-03-27 23:10:48 +00003358NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003359ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003360 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003361 return 0;
3362
3363 switch (NNS->getKind()) {
3364 case NestedNameSpecifier::Identifier:
3365 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003366 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003367 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3368 NNS->getAsIdentifier());
3369
3370 case NestedNameSpecifier::Namespace:
3371 // A namespace is canonical; build a nested-name-specifier with
3372 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003373 return NestedNameSpecifier::Create(*this, 0,
3374 NNS->getAsNamespace()->getOriginalNamespace());
3375
3376 case NestedNameSpecifier::NamespaceAlias:
3377 // A namespace is canonical; build a nested-name-specifier with
3378 // this namespace and no prefix.
3379 return NestedNameSpecifier::Create(*this, 0,
3380 NNS->getAsNamespaceAlias()->getNamespace()
3381 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003382
3383 case NestedNameSpecifier::TypeSpec:
3384 case NestedNameSpecifier::TypeSpecWithTemplate: {
3385 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003386
3387 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3388 // break it apart into its prefix and identifier, then reconsititute those
3389 // as the canonical nested-name-specifier. This is required to canonicalize
3390 // a dependent nested-name-specifier involving typedefs of dependent-name
3391 // types, e.g.,
3392 // typedef typename T::type T1;
3393 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003394 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3395 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003396 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003397
Eli Friedman5358a0a2012-03-03 04:09:56 +00003398 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3399 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3400 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003401 return NestedNameSpecifier::Create(*this, 0, false,
3402 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003403 }
3404
3405 case NestedNameSpecifier::Global:
3406 // The global specifier is canonical and unique.
3407 return NNS;
3408 }
3409
David Blaikie8a40f702012-01-17 06:56:22 +00003410 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003411}
3412
Chris Lattner7adf0762008-08-04 07:31:14 +00003413
Jay Foad39c79802011-01-12 09:06:06 +00003414const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003415 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003416 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003417 // Handle the common positive case fast.
3418 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3419 return AT;
3420 }
Mike Stump11289f42009-09-09 15:08:12 +00003421
John McCall8ccfcb52009-09-24 19:53:00 +00003422 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003423 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003424 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003425
John McCall8ccfcb52009-09-24 19:53:00 +00003426 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003427 // implements C99 6.7.3p8: "If the specification of an array type includes
3428 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003429
Chris Lattner7adf0762008-08-04 07:31:14 +00003430 // If we get here, we either have type qualifiers on the type, or we have
3431 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003432 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003433
John McCall33ddac02011-01-19 10:06:00 +00003434 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003435 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003436
Chris Lattner7adf0762008-08-04 07:31:14 +00003437 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003438 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003439 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003440 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003441
Chris Lattner7adf0762008-08-04 07:31:14 +00003442 // Otherwise, we have an array and we have qualifiers on it. Push the
3443 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003444 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003445
Chris Lattner7adf0762008-08-04 07:31:14 +00003446 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3447 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3448 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003449 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003450 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3451 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3452 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003453 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003454
Mike Stump11289f42009-09-09 15:08:12 +00003455 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003456 = dyn_cast<DependentSizedArrayType>(ATy))
3457 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003458 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003459 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003460 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003461 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003462 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003463
Chris Lattner7adf0762008-08-04 07:31:14 +00003464 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003465 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003466 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003467 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003468 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003469 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003470}
3471
Douglas Gregor84280642011-07-12 04:42:08 +00003472QualType ASTContext::getAdjustedParameterType(QualType T) {
3473 // C99 6.7.5.3p7:
3474 // A declaration of a parameter as "array of type" shall be
3475 // adjusted to "qualified pointer to type", where the type
3476 // qualifiers (if any) are those specified within the [ and ] of
3477 // the array type derivation.
3478 if (T->isArrayType())
3479 return getArrayDecayedType(T);
3480
3481 // C99 6.7.5.3p8:
3482 // A declaration of a parameter as "function returning type"
3483 // shall be adjusted to "pointer to function returning type", as
3484 // in 6.3.2.1.
3485 if (T->isFunctionType())
3486 return getPointerType(T);
3487
3488 return T;
3489}
3490
3491QualType ASTContext::getSignatureParameterType(QualType T) {
3492 T = getVariableArrayDecayedType(T);
3493 T = getAdjustedParameterType(T);
3494 return T.getUnqualifiedType();
3495}
3496
Chris Lattnera21ad802008-04-02 05:18:44 +00003497/// getArrayDecayedType - Return the properly qualified result of decaying the
3498/// specified array type to a pointer. This operation is non-trivial when
3499/// handling typedefs etc. The canonical type of "T" must be an array type,
3500/// this returns a pointer to a properly qualified element of the array.
3501///
3502/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003503QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003504 // Get the element type with 'getAsArrayType' so that we don't lose any
3505 // typedefs in the element type of the array. This also handles propagation
3506 // of type qualifiers from the array type into the element type if present
3507 // (C99 6.7.3p8).
3508 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3509 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003510
Chris Lattner7adf0762008-08-04 07:31:14 +00003511 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003512
3513 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003514 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003515}
3516
John McCall33ddac02011-01-19 10:06:00 +00003517QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3518 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003519}
3520
John McCall33ddac02011-01-19 10:06:00 +00003521QualType ASTContext::getBaseElementType(QualType type) const {
3522 Qualifiers qs;
3523 while (true) {
3524 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003525 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003526 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003527
John McCall33ddac02011-01-19 10:06:00 +00003528 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003529 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003530 }
Mike Stump11289f42009-09-09 15:08:12 +00003531
John McCall33ddac02011-01-19 10:06:00 +00003532 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003533}
3534
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003535/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003536uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003537ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3538 uint64_t ElementCount = 1;
3539 do {
3540 ElementCount *= CA->getSize().getZExtValue();
3541 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3542 } while (CA);
3543 return ElementCount;
3544}
3545
Steve Naroff0af91202007-04-27 21:51:21 +00003546/// getFloatingRank - Return a relative rank for floating point types.
3547/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003548static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003549 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003550 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003551
John McCall9dd450b2009-09-21 23:43:11 +00003552 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3553 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003554 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003555 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003556 case BuiltinType::Float: return FloatRank;
3557 case BuiltinType::Double: return DoubleRank;
3558 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003559 }
3560}
3561
Mike Stump11289f42009-09-09 15:08:12 +00003562/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3563/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003564/// 'typeDomain' is a real floating point or complex type.
3565/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003566QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3567 QualType Domain) const {
3568 FloatingRank EltRank = getFloatingRank(Size);
3569 if (Domain->isComplexType()) {
3570 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003571 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003572 case FloatRank: return FloatComplexTy;
3573 case DoubleRank: return DoubleComplexTy;
3574 case LongDoubleRank: return LongDoubleComplexTy;
3575 }
Steve Naroff0af91202007-04-27 21:51:21 +00003576 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003577
3578 assert(Domain->isRealFloatingType() && "Unknown domain!");
3579 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003580 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003581 case FloatRank: return FloatTy;
3582 case DoubleRank: return DoubleTy;
3583 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003584 }
David Blaikief47fa302012-01-17 02:30:50 +00003585 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003586}
3587
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003588/// getFloatingTypeOrder - Compare the rank of the two specified floating
3589/// point types, ignoring the domain of the type (i.e. 'double' ==
3590/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003591/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003592int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003593 FloatingRank LHSR = getFloatingRank(LHS);
3594 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003595
Chris Lattnerb90739d2008-04-06 23:38:49 +00003596 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003597 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003598 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003599 return 1;
3600 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003601}
3602
Chris Lattner76a00cf2008-04-06 22:59:24 +00003603/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3604/// routine will assert if passed a built-in type that isn't an integer or enum,
3605/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003606unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003607 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003608
Chris Lattner76a00cf2008-04-06 22:59:24 +00003609 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003610 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003611 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003612 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003613 case BuiltinType::Char_S:
3614 case BuiltinType::Char_U:
3615 case BuiltinType::SChar:
3616 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003617 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003618 case BuiltinType::Short:
3619 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003620 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003621 case BuiltinType::Int:
3622 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003623 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003624 case BuiltinType::Long:
3625 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003626 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003627 case BuiltinType::LongLong:
3628 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003629 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003630 case BuiltinType::Int128:
3631 case BuiltinType::UInt128:
3632 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003633 }
3634}
3635
Eli Friedman629ffb92009-08-20 04:21:42 +00003636/// \brief Whether this is a promotable bitfield reference according
3637/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3638///
3639/// \returns the type this bit-field will promote to, or NULL if no
3640/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003641QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003642 if (E->isTypeDependent() || E->isValueDependent())
3643 return QualType();
3644
Eli Friedman629ffb92009-08-20 04:21:42 +00003645 FieldDecl *Field = E->getBitField();
3646 if (!Field)
3647 return QualType();
3648
3649 QualType FT = Field->getType();
3650
Richard Smithcaf33902011-10-10 18:28:20 +00003651 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003652 uint64_t IntSize = getTypeSize(IntTy);
3653 // GCC extension compatibility: if the bit-field size is less than or equal
3654 // to the size of int, it gets promoted no matter what its type is.
3655 // For instance, unsigned long bf : 4 gets promoted to signed int.
3656 if (BitWidth < IntSize)
3657 return IntTy;
3658
3659 if (BitWidth == IntSize)
3660 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3661
3662 // Types bigger than int are not subject to promotions, and therefore act
3663 // like the base type.
3664 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3665 // is ridiculous.
3666 return QualType();
3667}
3668
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003669/// getPromotedIntegerType - Returns the type that Promotable will
3670/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3671/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003672QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003673 assert(!Promotable.isNull());
3674 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003675 if (const EnumType *ET = Promotable->getAs<EnumType>())
3676 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003677
3678 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3679 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3680 // (3.9.1) can be converted to a prvalue of the first of the following
3681 // types that can represent all the values of its underlying type:
3682 // int, unsigned int, long int, unsigned long int, long long int, or
3683 // unsigned long long int [...]
3684 // FIXME: Is there some better way to compute this?
3685 if (BT->getKind() == BuiltinType::WChar_S ||
3686 BT->getKind() == BuiltinType::WChar_U ||
3687 BT->getKind() == BuiltinType::Char16 ||
3688 BT->getKind() == BuiltinType::Char32) {
3689 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3690 uint64_t FromSize = getTypeSize(BT);
3691 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3692 LongLongTy, UnsignedLongLongTy };
3693 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3694 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3695 if (FromSize < ToSize ||
3696 (FromSize == ToSize &&
3697 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3698 return PromoteTypes[Idx];
3699 }
3700 llvm_unreachable("char type should fit into long long");
3701 }
3702 }
3703
3704 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003705 if (Promotable->isSignedIntegerType())
3706 return IntTy;
3707 uint64_t PromotableSize = getTypeSize(Promotable);
3708 uint64_t IntSize = getTypeSize(IntTy);
3709 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3710 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3711}
3712
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003713/// \brief Recurses in pointer/array types until it finds an objc retainable
3714/// type and returns its ownership.
3715Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3716 while (!T.isNull()) {
3717 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3718 return T.getObjCLifetime();
3719 if (T->isArrayType())
3720 T = getBaseElementType(T);
3721 else if (const PointerType *PT = T->getAs<PointerType>())
3722 T = PT->getPointeeType();
3723 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003724 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003725 else
3726 break;
3727 }
3728
3729 return Qualifiers::OCL_None;
3730}
3731
Mike Stump11289f42009-09-09 15:08:12 +00003732/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003733/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003734/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003735int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003736 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3737 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003738 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003739
Chris Lattner76a00cf2008-04-06 22:59:24 +00003740 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3741 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003742
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003743 unsigned LHSRank = getIntegerRank(LHSC);
3744 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003745
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003746 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3747 if (LHSRank == RHSRank) return 0;
3748 return LHSRank > RHSRank ? 1 : -1;
3749 }
Mike Stump11289f42009-09-09 15:08:12 +00003750
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003751 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3752 if (LHSUnsigned) {
3753 // If the unsigned [LHS] type is larger, return it.
3754 if (LHSRank >= RHSRank)
3755 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003756
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003757 // If the signed type can represent all values of the unsigned type, it
3758 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003759 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003760 return -1;
3761 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003762
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003763 // If the unsigned [RHS] type is larger, return it.
3764 if (RHSRank >= LHSRank)
3765 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003766
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003767 // If the signed type can represent all values of the unsigned type, it
3768 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003769 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003770 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003771}
Anders Carlsson98f07902007-08-17 05:31:46 +00003772
Anders Carlsson6d417272009-11-14 21:45:58 +00003773static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003774CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3775 DeclContext *DC, IdentifierInfo *Id) {
3776 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003777 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003778 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003779 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003780 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003781}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003782
Mike Stump11289f42009-09-09 15:08:12 +00003783// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003784QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003785 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003786 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003787 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003788 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003789 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003790
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003791 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003792
Anders Carlsson98f07902007-08-17 05:31:46 +00003793 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003794 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003795 // int flags;
3796 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003797 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003798 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003799 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003800 FieldTypes[3] = LongTy;
3801
Anders Carlsson98f07902007-08-17 05:31:46 +00003802 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003803 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003804 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003805 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003806 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003807 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003808 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003809 /*Mutable=*/false,
3810 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003811 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003812 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003813 }
3814
Douglas Gregord5058122010-02-11 01:19:42 +00003815 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003816 }
Mike Stump11289f42009-09-09 15:08:12 +00003817
Anders Carlsson98f07902007-08-17 05:31:46 +00003818 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003819}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003820
Douglas Gregor512b0772009-04-23 22:29:11 +00003821void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003822 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003823 assert(Rec && "Invalid CFConstantStringType");
3824 CFConstantStringTypeDecl = Rec->getDecl();
3825}
3826
Jay Foad39c79802011-01-12 09:06:06 +00003827QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003828 if (BlockDescriptorType)
3829 return getTagDeclType(BlockDescriptorType);
3830
3831 RecordDecl *T;
3832 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003833 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003834 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003835 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003836
3837 QualType FieldTypes[] = {
3838 UnsignedLongTy,
3839 UnsignedLongTy,
3840 };
3841
3842 const char *FieldNames[] = {
3843 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003844 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003845 };
3846
3847 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003848 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003849 SourceLocation(),
3850 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003851 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003852 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003853 /*Mutable=*/false,
3854 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003855 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003856 T->addDecl(Field);
3857 }
3858
Douglas Gregord5058122010-02-11 01:19:42 +00003859 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003860
3861 BlockDescriptorType = T;
3862
3863 return getTagDeclType(BlockDescriptorType);
3864}
3865
Jay Foad39c79802011-01-12 09:06:06 +00003866QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003867 if (BlockDescriptorExtendedType)
3868 return getTagDeclType(BlockDescriptorExtendedType);
3869
3870 RecordDecl *T;
3871 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003872 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003873 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003874 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003875
3876 QualType FieldTypes[] = {
3877 UnsignedLongTy,
3878 UnsignedLongTy,
3879 getPointerType(VoidPtrTy),
3880 getPointerType(VoidPtrTy)
3881 };
3882
3883 const char *FieldNames[] = {
3884 "reserved",
3885 "Size",
3886 "CopyFuncPtr",
3887 "DestroyFuncPtr"
3888 };
3889
3890 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003891 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003892 SourceLocation(),
3893 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003894 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003895 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003896 /*Mutable=*/false,
3897 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003898 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003899 T->addDecl(Field);
3900 }
3901
Douglas Gregord5058122010-02-11 01:19:42 +00003902 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003903
3904 BlockDescriptorExtendedType = T;
3905
3906 return getTagDeclType(BlockDescriptorExtendedType);
3907}
3908
Jay Foad39c79802011-01-12 09:06:06 +00003909bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003910 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003911 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003912 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003913 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3914 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003915 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003916
3917 }
3918 }
Mike Stump94967902009-10-21 18:16:27 +00003919 return false;
3920}
3921
Jay Foad39c79802011-01-12 09:06:06 +00003922QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003923ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003924 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003925 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003926 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003927 // unsigned int __flags;
3928 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003929 // void *__copy_helper; // as needed
3930 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003931 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003932 // } *
3933
Mike Stump94967902009-10-21 18:16:27 +00003934 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3935
3936 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003937 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003938 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3939 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003940 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003941 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003942 T->startDefinition();
3943 QualType Int32Ty = IntTy;
3944 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3945 QualType FieldTypes[] = {
3946 getPointerType(VoidPtrTy),
3947 getPointerType(getTagDeclType(T)),
3948 Int32Ty,
3949 Int32Ty,
3950 getPointerType(VoidPtrTy),
3951 getPointerType(VoidPtrTy),
3952 Ty
3953 };
3954
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003955 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003956 "__isa",
3957 "__forwarding",
3958 "__flags",
3959 "__size",
3960 "__copy_helper",
3961 "__destroy_helper",
3962 DeclName,
3963 };
3964
3965 for (size_t i = 0; i < 7; ++i) {
3966 if (!HasCopyAndDispose && i >=4 && i <= 5)
3967 continue;
3968 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003969 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003970 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003971 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003972 /*BitWidth=*/0, /*Mutable=*/false,
3973 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003974 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003975 T->addDecl(Field);
3976 }
3977
Douglas Gregord5058122010-02-11 01:19:42 +00003978 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003979
3980 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003981}
3982
Douglas Gregorbab8a962011-09-08 01:46:34 +00003983TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3984 if (!ObjCInstanceTypeDecl)
3985 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3986 getTranslationUnitDecl(),
3987 SourceLocation(),
3988 SourceLocation(),
3989 &Idents.get("instancetype"),
3990 getTrivialTypeSourceInfo(getObjCIdType()));
3991 return ObjCInstanceTypeDecl;
3992}
3993
Anders Carlsson18acd442007-10-29 06:33:42 +00003994// This returns true if a type has been typedefed to BOOL:
3995// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003996static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003997 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003998 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3999 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004000
Anders Carlssond8499822007-10-29 05:01:08 +00004001 return false;
4002}
4003
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004004/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004005/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004006CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004007 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4008 return CharUnits::Zero();
4009
Ken Dyck40775002010-01-11 17:06:35 +00004010 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004011
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004012 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004013 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004014 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004015 // Treat arrays as pointers, since that's how they're passed in.
4016 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004017 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004018 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004019}
4020
4021static inline
4022std::string charUnitsToString(const CharUnits &CU) {
4023 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004024}
4025
John McCall351762c2011-02-07 10:33:21 +00004026/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004027/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004028std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4029 std::string S;
4030
David Chisnall950a9512009-11-17 19:33:30 +00004031 const BlockDecl *Decl = Expr->getBlockDecl();
4032 QualType BlockTy =
4033 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4034 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004035 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004036 // Compute size of all parameters.
4037 // Start with computing size of a pointer in number of bytes.
4038 // FIXME: There might(should) be a better way of doing this computation!
4039 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004040 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4041 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004042 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004043 E = Decl->param_end(); PI != E; ++PI) {
4044 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004045 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00004046 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004047 ParmOffset += sz;
4048 }
4049 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004050 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004051 // Block pointer and offset.
4052 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004053
4054 // Argument types.
4055 ParmOffset = PtrSize;
4056 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4057 Decl->param_end(); PI != E; ++PI) {
4058 ParmVarDecl *PVDecl = *PI;
4059 QualType PType = PVDecl->getOriginalType();
4060 if (const ArrayType *AT =
4061 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4062 // Use array's original type only if it has known number of
4063 // elements.
4064 if (!isa<ConstantArrayType>(AT))
4065 PType = PVDecl->getType();
4066 } else if (PType->isFunctionType())
4067 PType = PVDecl->getType();
4068 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004069 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004070 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004071 }
John McCall351762c2011-02-07 10:33:21 +00004072
4073 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004074}
4075
Douglas Gregora9d84932011-05-27 01:19:52 +00004076bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004077 std::string& S) {
4078 // Encode result type.
4079 getObjCEncodingForType(Decl->getResultType(), S);
4080 CharUnits ParmOffset;
4081 // Compute size of all parameters.
4082 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4083 E = Decl->param_end(); PI != E; ++PI) {
4084 QualType PType = (*PI)->getType();
4085 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004086 if (sz.isZero())
4087 return true;
4088
David Chisnall50e4eba2010-12-30 14:05:53 +00004089 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004090 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004091 ParmOffset += sz;
4092 }
4093 S += charUnitsToString(ParmOffset);
4094 ParmOffset = CharUnits::Zero();
4095
4096 // Argument types.
4097 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4098 E = Decl->param_end(); PI != E; ++PI) {
4099 ParmVarDecl *PVDecl = *PI;
4100 QualType PType = PVDecl->getOriginalType();
4101 if (const ArrayType *AT =
4102 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4103 // Use array's original type only if it has known number of
4104 // elements.
4105 if (!isa<ConstantArrayType>(AT))
4106 PType = PVDecl->getType();
4107 } else if (PType->isFunctionType())
4108 PType = PVDecl->getType();
4109 getObjCEncodingForType(PType, S);
4110 S += charUnitsToString(ParmOffset);
4111 ParmOffset += getObjCEncodingTypeSize(PType);
4112 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004113
4114 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004115}
4116
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004117/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4118/// method parameter or return type. If Extended, include class names and
4119/// block object types.
4120void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4121 QualType T, std::string& S,
4122 bool Extended) const {
4123 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4124 getObjCEncodingForTypeQualifier(QT, S);
4125 // Encode parameter type.
4126 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4127 true /*OutermostType*/,
4128 false /*EncodingProperty*/,
4129 false /*StructField*/,
4130 Extended /*EncodeBlockParameters*/,
4131 Extended /*EncodeClassNames*/);
4132}
4133
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004134/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004135/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004136bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004137 std::string& S,
4138 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004139 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004140 // Encode return type.
4141 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4142 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004143 // Compute size of all parameters.
4144 // Start with computing size of a pointer in number of bytes.
4145 // FIXME: There might(should) be a better way of doing this computation!
4146 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004147 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004148 // The first two arguments (self and _cmd) are pointers; account for
4149 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004150 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004151 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004152 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004153 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004154 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004155 if (sz.isZero())
4156 return true;
4157
Ken Dyck40775002010-01-11 17:06:35 +00004158 assert (sz.isPositive() &&
4159 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004160 ParmOffset += sz;
4161 }
Ken Dyck40775002010-01-11 17:06:35 +00004162 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004163 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004164 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004165
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004166 // Argument types.
4167 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004168 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004169 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004170 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004171 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004172 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004173 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4174 // Use array's original type only if it has known number of
4175 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004176 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004177 PType = PVDecl->getType();
4178 } else if (PType->isFunctionType())
4179 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004180 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4181 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004182 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004183 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004184 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004185
4186 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004187}
4188
Daniel Dunbar4932b362008-08-28 04:38:10 +00004189/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004190/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004191/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4192/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004193/// Property attributes are stored as a comma-delimited C string. The simple
4194/// attributes readonly and bycopy are encoded as single characters. The
4195/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4196/// encoded as single characters, followed by an identifier. Property types
4197/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004198/// these attributes are defined by the following enumeration:
4199/// @code
4200/// enum PropertyAttributes {
4201/// kPropertyReadOnly = 'R', // property is read-only.
4202/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4203/// kPropertyByref = '&', // property is a reference to the value last assigned
4204/// kPropertyDynamic = 'D', // property is dynamic
4205/// kPropertyGetter = 'G', // followed by getter selector name
4206/// kPropertySetter = 'S', // followed by setter selector name
4207/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004208/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004209/// kPropertyWeak = 'W' // 'weak' property
4210/// kPropertyStrong = 'P' // property GC'able
4211/// kPropertyNonAtomic = 'N' // property non-atomic
4212/// };
4213/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004214void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004215 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004216 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004217 // Collect information from the property implementation decl(s).
4218 bool Dynamic = false;
4219 ObjCPropertyImplDecl *SynthesizePID = 0;
4220
4221 // FIXME: Duplicated code due to poor abstraction.
4222 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004223 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004224 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4225 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004226 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004227 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004228 ObjCPropertyImplDecl *PID = *i;
4229 if (PID->getPropertyDecl() == PD) {
4230 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4231 Dynamic = true;
4232 } else {
4233 SynthesizePID = PID;
4234 }
4235 }
4236 }
4237 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004238 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004239 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004240 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004241 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004242 ObjCPropertyImplDecl *PID = *i;
4243 if (PID->getPropertyDecl() == PD) {
4244 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4245 Dynamic = true;
4246 } else {
4247 SynthesizePID = PID;
4248 }
4249 }
Mike Stump11289f42009-09-09 15:08:12 +00004250 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004251 }
4252 }
4253
4254 // FIXME: This is not very efficient.
4255 S = "T";
4256
4257 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004258 // GCC has some special rules regarding encoding of properties which
4259 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004260 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004261 true /* outermost type */,
4262 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004263
4264 if (PD->isReadOnly()) {
4265 S += ",R";
4266 } else {
4267 switch (PD->getSetterKind()) {
4268 case ObjCPropertyDecl::Assign: break;
4269 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004270 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004271 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004272 }
4273 }
4274
4275 // It really isn't clear at all what this means, since properties
4276 // are "dynamic by default".
4277 if (Dynamic)
4278 S += ",D";
4279
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004280 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4281 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004282
Daniel Dunbar4932b362008-08-28 04:38:10 +00004283 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4284 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004285 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004286 }
4287
4288 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4289 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004290 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004291 }
4292
4293 if (SynthesizePID) {
4294 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4295 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004296 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004297 }
4298
4299 // FIXME: OBJCGC: weak & strong
4300}
4301
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004302/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004303/// Another legacy compatibility encoding: 32-bit longs are encoded as
4304/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004305/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4306///
4307void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004308 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004309 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004310 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004311 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004312 else
Jay Foad39c79802011-01-12 09:06:06 +00004313 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004314 PointeeTy = IntTy;
4315 }
4316 }
4317}
4318
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004319void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004320 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004321 // We follow the behavior of gcc, expanding structures which are
4322 // directly pointed to, and expanding embedded structures. Note that
4323 // these rules are sufficient to prevent recursive encoding of the
4324 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004325 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004326 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004327}
4328
David Chisnallb190a2c2010-06-04 01:10:52 +00004329static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4330 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004331 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004332 case BuiltinType::Void: return 'v';
4333 case BuiltinType::Bool: return 'B';
4334 case BuiltinType::Char_U:
4335 case BuiltinType::UChar: return 'C';
4336 case BuiltinType::UShort: return 'S';
4337 case BuiltinType::UInt: return 'I';
4338 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004339 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004340 case BuiltinType::UInt128: return 'T';
4341 case BuiltinType::ULongLong: return 'Q';
4342 case BuiltinType::Char_S:
4343 case BuiltinType::SChar: return 'c';
4344 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004345 case BuiltinType::WChar_S:
4346 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004347 case BuiltinType::Int: return 'i';
4348 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004349 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004350 case BuiltinType::LongLong: return 'q';
4351 case BuiltinType::Int128: return 't';
4352 case BuiltinType::Float: return 'f';
4353 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004354 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004355 }
4356}
4357
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004358static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4359 EnumDecl *Enum = ET->getDecl();
4360
4361 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4362 if (!Enum->isFixed())
4363 return 'i';
4364
4365 // The encoding of a fixed enum type matches its fixed underlying type.
4366 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4367}
4368
Jay Foad39c79802011-01-12 09:06:06 +00004369static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004370 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004371 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004372 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004373 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4374 // The GNU runtime requires more information; bitfields are encoded as b,
4375 // then the offset (in bits) of the first element, then the type of the
4376 // bitfield, then the size in bits. For example, in this structure:
4377 //
4378 // struct
4379 // {
4380 // int integer;
4381 // int flags:2;
4382 // };
4383 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4384 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4385 // information is not especially sensible, but we're stuck with it for
4386 // compatibility with GCC, although providing it breaks anything that
4387 // actually uses runtime introspection and wants to work on both runtimes...
David Blaikiebbafb8a2012-03-11 07:00:24 +00004388 if (!Ctx->getLangOpts().NeXTRuntime) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004389 const RecordDecl *RD = FD->getParent();
4390 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004391 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004392 if (const EnumType *ET = T->getAs<EnumType>())
4393 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004394 else
Jay Foad39c79802011-01-12 09:06:06 +00004395 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004396 }
Richard Smithcaf33902011-10-10 18:28:20 +00004397 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004398}
4399
Daniel Dunbar07d07852009-10-18 21:17:35 +00004400// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004401void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4402 bool ExpandPointedToStructures,
4403 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004404 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004405 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004406 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004407 bool StructField,
4408 bool EncodeBlockParameters,
4409 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004410 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004411 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004412 return EncodeBitField(this, S, T, FD);
4413 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004414 return;
4415 }
Mike Stump11289f42009-09-09 15:08:12 +00004416
John McCall9dd450b2009-09-21 23:43:11 +00004417 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004418 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004419 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004420 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004421 return;
4422 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004423
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004424 // encoding for pointer or r3eference types.
4425 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004426 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004427 if (PT->isObjCSelType()) {
4428 S += ':';
4429 return;
4430 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004431 PointeeTy = PT->getPointeeType();
4432 }
4433 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4434 PointeeTy = RT->getPointeeType();
4435 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004436 bool isReadOnly = false;
4437 // For historical/compatibility reasons, the read-only qualifier of the
4438 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4439 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004440 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004441 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004442 if (OutermostType && T.isConstQualified()) {
4443 isReadOnly = true;
4444 S += 'r';
4445 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004446 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004447 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004448 while (P->getAs<PointerType>())
4449 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004450 if (P.isConstQualified()) {
4451 isReadOnly = true;
4452 S += 'r';
4453 }
4454 }
4455 if (isReadOnly) {
4456 // Another legacy compatibility encoding. Some ObjC qualifier and type
4457 // combinations need to be rearranged.
4458 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004459 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004460 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004461 }
Mike Stump11289f42009-09-09 15:08:12 +00004462
Anders Carlssond8499822007-10-29 05:01:08 +00004463 if (PointeeTy->isCharType()) {
4464 // char pointer types should be encoded as '*' unless it is a
4465 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004466 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004467 S += '*';
4468 return;
4469 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004470 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004471 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4472 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4473 S += '#';
4474 return;
4475 }
4476 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4477 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4478 S += '@';
4479 return;
4480 }
4481 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004482 }
Anders Carlssond8499822007-10-29 05:01:08 +00004483 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004484 getLegacyIntegralTypeEncoding(PointeeTy);
4485
Mike Stump11289f42009-09-09 15:08:12 +00004486 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004487 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004488 return;
4489 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004490
Chris Lattnere7cabb92009-07-13 00:10:46 +00004491 if (const ArrayType *AT =
4492 // Ignore type qualifiers etc.
4493 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004494 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004495 // Incomplete arrays are encoded as a pointer to the array element.
4496 S += '^';
4497
Mike Stump11289f42009-09-09 15:08:12 +00004498 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004499 false, ExpandStructures, FD);
4500 } else {
4501 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004502
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004503 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4504 if (getTypeSize(CAT->getElementType()) == 0)
4505 S += '0';
4506 else
4507 S += llvm::utostr(CAT->getSize().getZExtValue());
4508 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004509 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004510 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4511 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004512 S += '0';
4513 }
Mike Stump11289f42009-09-09 15:08:12 +00004514
4515 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004516 false, ExpandStructures, FD);
4517 S += ']';
4518 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004519 return;
4520 }
Mike Stump11289f42009-09-09 15:08:12 +00004521
John McCall9dd450b2009-09-21 23:43:11 +00004522 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004523 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004524 return;
4525 }
Mike Stump11289f42009-09-09 15:08:12 +00004526
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004527 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004528 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004529 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004530 // Anonymous structures print as '?'
4531 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4532 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004533 if (ClassTemplateSpecializationDecl *Spec
4534 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4535 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4536 std::string TemplateArgsStr
4537 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004538 TemplateArgs.data(),
4539 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004540 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004541
4542 S += TemplateArgsStr;
4543 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004544 } else {
4545 S += '?';
4546 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004547 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004548 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004549 if (!RDecl->isUnion()) {
4550 getObjCEncodingForStructureImpl(RDecl, S, FD);
4551 } else {
4552 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4553 FieldEnd = RDecl->field_end();
4554 Field != FieldEnd; ++Field) {
4555 if (FD) {
4556 S += '"';
4557 S += Field->getNameAsString();
4558 S += '"';
4559 }
Mike Stump11289f42009-09-09 15:08:12 +00004560
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004561 // Special case bit-fields.
4562 if (Field->isBitField()) {
4563 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4564 (*Field));
4565 } else {
4566 QualType qt = Field->getType();
4567 getLegacyIntegralTypeEncoding(qt);
4568 getObjCEncodingForTypeImpl(qt, S, false, true,
4569 FD, /*OutermostType*/false,
4570 /*EncodingProperty*/false,
4571 /*StructField*/true);
4572 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004573 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004574 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004575 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004576 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004577 return;
4578 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004579
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004580 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004581 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004582 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004583 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004584 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004585 return;
4586 }
Mike Stump11289f42009-09-09 15:08:12 +00004587
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004588 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004589 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004590 if (EncodeBlockParameters) {
4591 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4592
4593 S += '<';
4594 // Block return type
4595 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4596 ExpandPointedToStructures, ExpandStructures,
4597 FD,
4598 false /* OutermostType */,
4599 EncodingProperty,
4600 false /* StructField */,
4601 EncodeBlockParameters,
4602 EncodeClassNames);
4603 // Block self
4604 S += "@?";
4605 // Block parameters
4606 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4607 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4608 E = FPT->arg_type_end(); I && (I != E); ++I) {
4609 getObjCEncodingForTypeImpl(*I, S,
4610 ExpandPointedToStructures,
4611 ExpandStructures,
4612 FD,
4613 false /* OutermostType */,
4614 EncodingProperty,
4615 false /* StructField */,
4616 EncodeBlockParameters,
4617 EncodeClassNames);
4618 }
4619 }
4620 S += '>';
4621 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004622 return;
4623 }
Mike Stump11289f42009-09-09 15:08:12 +00004624
John McCall8b07ec22010-05-15 11:32:37 +00004625 // Ignore protocol qualifiers when mangling at this level.
4626 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4627 T = OT->getBaseType();
4628
John McCall8ccfcb52009-09-24 19:53:00 +00004629 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004630 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004631 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004632 S += '{';
4633 const IdentifierInfo *II = OI->getIdentifier();
4634 S += II->getName();
4635 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004636 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004637 DeepCollectObjCIvars(OI, true, Ivars);
4638 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004639 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004640 if (Field->isBitField())
4641 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004642 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004643 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004644 }
4645 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004646 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004647 }
Mike Stump11289f42009-09-09 15:08:12 +00004648
John McCall9dd450b2009-09-21 23:43:11 +00004649 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004650 if (OPT->isObjCIdType()) {
4651 S += '@';
4652 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004653 }
Mike Stump11289f42009-09-09 15:08:12 +00004654
Steve Narofff0c86112009-10-28 22:03:49 +00004655 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4656 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4657 // Since this is a binary compatibility issue, need to consult with runtime
4658 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004659 S += '#';
4660 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004661 }
Mike Stump11289f42009-09-09 15:08:12 +00004662
Chris Lattnere7cabb92009-07-13 00:10:46 +00004663 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004664 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004665 ExpandPointedToStructures,
4666 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004667 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004668 // Note that we do extended encoding of protocol qualifer list
4669 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004670 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004671 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4672 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004673 S += '<';
4674 S += (*I)->getNameAsString();
4675 S += '>';
4676 }
4677 S += '"';
4678 }
4679 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004680 }
Mike Stump11289f42009-09-09 15:08:12 +00004681
Chris Lattnere7cabb92009-07-13 00:10:46 +00004682 QualType PointeeTy = OPT->getPointeeType();
4683 if (!EncodingProperty &&
4684 isa<TypedefType>(PointeeTy.getTypePtr())) {
4685 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004686 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004687 // {...};
4688 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004689 getObjCEncodingForTypeImpl(PointeeTy, S,
4690 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004691 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004692 return;
4693 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004694
4695 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004696 if (OPT->getInterfaceDecl() &&
4697 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004698 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004699 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004700 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4701 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004702 S += '<';
4703 S += (*I)->getNameAsString();
4704 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004705 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004706 S += '"';
4707 }
4708 return;
4709 }
Mike Stump11289f42009-09-09 15:08:12 +00004710
John McCalla9e6e8d2010-05-17 23:56:34 +00004711 // gcc just blithely ignores member pointers.
4712 // TODO: maybe there should be a mangling for these
4713 if (T->getAs<MemberPointerType>())
4714 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004715
4716 if (T->isVectorType()) {
4717 // This matches gcc's encoding, even though technically it is
4718 // insufficient.
4719 // FIXME. We should do a better job than gcc.
4720 return;
4721 }
4722
David Blaikie83d382b2011-09-23 05:06:16 +00004723 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004724}
4725
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004726void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4727 std::string &S,
4728 const FieldDecl *FD,
4729 bool includeVBases) const {
4730 assert(RDecl && "Expected non-null RecordDecl");
4731 assert(!RDecl->isUnion() && "Should not be called for unions");
4732 if (!RDecl->getDefinition())
4733 return;
4734
4735 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4736 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4737 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4738
4739 if (CXXRec) {
4740 for (CXXRecordDecl::base_class_iterator
4741 BI = CXXRec->bases_begin(),
4742 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4743 if (!BI->isVirtual()) {
4744 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004745 if (base->isEmpty())
4746 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004747 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4748 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4749 std::make_pair(offs, base));
4750 }
4751 }
4752 }
4753
4754 unsigned i = 0;
4755 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4756 FieldEnd = RDecl->field_end();
4757 Field != FieldEnd; ++Field, ++i) {
4758 uint64_t offs = layout.getFieldOffset(i);
4759 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4760 std::make_pair(offs, *Field));
4761 }
4762
4763 if (CXXRec && includeVBases) {
4764 for (CXXRecordDecl::base_class_iterator
4765 BI = CXXRec->vbases_begin(),
4766 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4767 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004768 if (base->isEmpty())
4769 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004770 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004771 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4772 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4773 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004774 }
4775 }
4776
4777 CharUnits size;
4778 if (CXXRec) {
4779 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4780 } else {
4781 size = layout.getSize();
4782 }
4783
4784 uint64_t CurOffs = 0;
4785 std::multimap<uint64_t, NamedDecl *>::iterator
4786 CurLayObj = FieldOrBaseOffsets.begin();
4787
Argyrios Kyrtzidisc7e50c52011-08-22 16:03:14 +00004788 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4789 (CurLayObj == FieldOrBaseOffsets.end() &&
4790 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004791 assert(CXXRec && CXXRec->isDynamicClass() &&
4792 "Offset 0 was empty but no VTable ?");
4793 if (FD) {
4794 S += "\"_vptr$";
4795 std::string recname = CXXRec->getNameAsString();
4796 if (recname.empty()) recname = "?";
4797 S += recname;
4798 S += '"';
4799 }
4800 S += "^^?";
4801 CurOffs += getTypeSize(VoidPtrTy);
4802 }
4803
4804 if (!RDecl->hasFlexibleArrayMember()) {
4805 // Mark the end of the structure.
4806 uint64_t offs = toBits(size);
4807 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4808 std::make_pair(offs, (NamedDecl*)0));
4809 }
4810
4811 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4812 assert(CurOffs <= CurLayObj->first);
4813
4814 if (CurOffs < CurLayObj->first) {
4815 uint64_t padding = CurLayObj->first - CurOffs;
4816 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4817 // packing/alignment of members is different that normal, in which case
4818 // the encoding will be out-of-sync with the real layout.
4819 // If the runtime switches to just consider the size of types without
4820 // taking into account alignment, we could make padding explicit in the
4821 // encoding (e.g. using arrays of chars). The encoding strings would be
4822 // longer then though.
4823 CurOffs += padding;
4824 }
4825
4826 NamedDecl *dcl = CurLayObj->second;
4827 if (dcl == 0)
4828 break; // reached end of structure.
4829
4830 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4831 // We expand the bases without their virtual bases since those are going
4832 // in the initial structure. Note that this differs from gcc which
4833 // expands virtual bases each time one is encountered in the hierarchy,
4834 // making the encoding type bigger than it really is.
4835 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004836 assert(!base->isEmpty());
4837 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004838 } else {
4839 FieldDecl *field = cast<FieldDecl>(dcl);
4840 if (FD) {
4841 S += '"';
4842 S += field->getNameAsString();
4843 S += '"';
4844 }
4845
4846 if (field->isBitField()) {
4847 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004848 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004849 } else {
4850 QualType qt = field->getType();
4851 getLegacyIntegralTypeEncoding(qt);
4852 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4853 /*OutermostType*/false,
4854 /*EncodingProperty*/false,
4855 /*StructField*/true);
4856 CurOffs += getTypeSize(field->getType());
4857 }
4858 }
4859 }
4860}
4861
Mike Stump11289f42009-09-09 15:08:12 +00004862void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004863 std::string& S) const {
4864 if (QT & Decl::OBJC_TQ_In)
4865 S += 'n';
4866 if (QT & Decl::OBJC_TQ_Inout)
4867 S += 'N';
4868 if (QT & Decl::OBJC_TQ_Out)
4869 S += 'o';
4870 if (QT & Decl::OBJC_TQ_Bycopy)
4871 S += 'O';
4872 if (QT & Decl::OBJC_TQ_Byref)
4873 S += 'R';
4874 if (QT & Decl::OBJC_TQ_Oneway)
4875 S += 'V';
4876}
4877
Chris Lattnere7cabb92009-07-13 00:10:46 +00004878void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004879 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004880
Anders Carlsson87c149b2007-10-11 01:00:40 +00004881 BuiltinVaListType = T;
4882}
4883
Douglas Gregor3ea72692011-08-12 05:46:01 +00004884TypedefDecl *ASTContext::getObjCIdDecl() const {
4885 if (!ObjCIdDecl) {
4886 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4887 T = getObjCObjectPointerType(T);
4888 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4889 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4890 getTranslationUnitDecl(),
4891 SourceLocation(), SourceLocation(),
4892 &Idents.get("id"), IdInfo);
4893 }
4894
4895 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004896}
4897
Douglas Gregor52e02802011-08-12 06:17:30 +00004898TypedefDecl *ASTContext::getObjCSelDecl() const {
4899 if (!ObjCSelDecl) {
4900 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4901 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4902 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4903 getTranslationUnitDecl(),
4904 SourceLocation(), SourceLocation(),
4905 &Idents.get("SEL"), SelInfo);
4906 }
4907 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004908}
4909
Douglas Gregor0a586182011-08-12 05:59:41 +00004910TypedefDecl *ASTContext::getObjCClassDecl() const {
4911 if (!ObjCClassDecl) {
4912 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4913 T = getObjCObjectPointerType(T);
4914 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4915 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4916 getTranslationUnitDecl(),
4917 SourceLocation(), SourceLocation(),
4918 &Idents.get("Class"), ClassInfo);
4919 }
4920
4921 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004922}
4923
Douglas Gregord53ae832012-01-17 18:09:05 +00004924ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4925 if (!ObjCProtocolClassDecl) {
4926 ObjCProtocolClassDecl
4927 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4928 SourceLocation(),
4929 &Idents.get("Protocol"),
4930 /*PrevDecl=*/0,
4931 SourceLocation(), true);
4932 }
4933
4934 return ObjCProtocolClassDecl;
4935}
4936
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004937void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004938 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004939 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004940
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004941 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004942}
4943
John McCalld28ae272009-12-02 08:04:21 +00004944/// \brief Retrieve the template name that corresponds to a non-empty
4945/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004946TemplateName
4947ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4948 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004949 unsigned size = End - Begin;
4950 assert(size > 1 && "set is not overloaded!");
4951
4952 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4953 size * sizeof(FunctionTemplateDecl*));
4954 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4955
4956 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004957 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004958 NamedDecl *D = *I;
4959 assert(isa<FunctionTemplateDecl>(D) ||
4960 (isa<UsingShadowDecl>(D) &&
4961 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4962 *Storage++ = D;
4963 }
4964
4965 return TemplateName(OT);
4966}
4967
Douglas Gregordc572a32009-03-30 22:58:21 +00004968/// \brief Retrieve the template name that represents a qualified
4969/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004970TemplateName
4971ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4972 bool TemplateKeyword,
4973 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004974 assert(NNS && "Missing nested-name-specifier in qualified template name");
4975
Douglas Gregorc42075a2010-02-04 18:10:26 +00004976 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004977 llvm::FoldingSetNodeID ID;
4978 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4979
4980 void *InsertPos = 0;
4981 QualifiedTemplateName *QTN =
4982 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4983 if (!QTN) {
4984 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4985 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4986 }
4987
4988 return TemplateName(QTN);
4989}
4990
4991/// \brief Retrieve the template name that represents a dependent
4992/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004993TemplateName
4994ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4995 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004996 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004997 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004998
4999 llvm::FoldingSetNodeID ID;
5000 DependentTemplateName::Profile(ID, NNS, Name);
5001
5002 void *InsertPos = 0;
5003 DependentTemplateName *QTN =
5004 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5005
5006 if (QTN)
5007 return TemplateName(QTN);
5008
5009 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5010 if (CanonNNS == NNS) {
5011 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5012 } else {
5013 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5014 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005015 DependentTemplateName *CheckQTN =
5016 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5017 assert(!CheckQTN && "Dependent type name canonicalization broken");
5018 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005019 }
5020
5021 DependentTemplateNames.InsertNode(QTN, InsertPos);
5022 return TemplateName(QTN);
5023}
5024
Douglas Gregor71395fa2009-11-04 00:56:37 +00005025/// \brief Retrieve the template name that represents a dependent
5026/// template name such as \c MetaFun::template operator+.
5027TemplateName
5028ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005029 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005030 assert((!NNS || NNS->isDependent()) &&
5031 "Nested name specifier must be dependent");
5032
5033 llvm::FoldingSetNodeID ID;
5034 DependentTemplateName::Profile(ID, NNS, Operator);
5035
5036 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005037 DependentTemplateName *QTN
5038 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005039
5040 if (QTN)
5041 return TemplateName(QTN);
5042
5043 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5044 if (CanonNNS == NNS) {
5045 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5046 } else {
5047 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5048 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005049
5050 DependentTemplateName *CheckQTN
5051 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5052 assert(!CheckQTN && "Dependent template name canonicalization broken");
5053 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005054 }
5055
5056 DependentTemplateNames.InsertNode(QTN, InsertPos);
5057 return TemplateName(QTN);
5058}
5059
Douglas Gregor5590be02011-01-15 06:45:20 +00005060TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005061ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5062 TemplateName replacement) const {
5063 llvm::FoldingSetNodeID ID;
5064 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5065
5066 void *insertPos = 0;
5067 SubstTemplateTemplateParmStorage *subst
5068 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5069
5070 if (!subst) {
5071 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5072 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5073 }
5074
5075 return TemplateName(subst);
5076}
5077
5078TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005079ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5080 const TemplateArgument &ArgPack) const {
5081 ASTContext &Self = const_cast<ASTContext &>(*this);
5082 llvm::FoldingSetNodeID ID;
5083 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5084
5085 void *InsertPos = 0;
5086 SubstTemplateTemplateParmPackStorage *Subst
5087 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5088
5089 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005090 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005091 ArgPack.pack_size(),
5092 ArgPack.pack_begin());
5093 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5094 }
5095
5096 return TemplateName(Subst);
5097}
5098
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005099/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005100/// TargetInfo, produce the corresponding type. The unsigned @p Type
5101/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005102CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005103 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005104 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005105 case TargetInfo::SignedShort: return ShortTy;
5106 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5107 case TargetInfo::SignedInt: return IntTy;
5108 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5109 case TargetInfo::SignedLong: return LongTy;
5110 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5111 case TargetInfo::SignedLongLong: return LongLongTy;
5112 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5113 }
5114
David Blaikie83d382b2011-09-23 05:06:16 +00005115 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005116}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005117
5118//===----------------------------------------------------------------------===//
5119// Type Predicates.
5120//===----------------------------------------------------------------------===//
5121
Fariborz Jahanian96207692009-02-18 21:49:28 +00005122/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5123/// garbage collection attribute.
5124///
John McCall553d45a2011-01-12 00:34:59 +00005125Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005126 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005127 return Qualifiers::GCNone;
5128
David Blaikiebbafb8a2012-03-11 07:00:24 +00005129 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005130 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5131
5132 // Default behaviour under objective-C's gc is for ObjC pointers
5133 // (or pointers to them) be treated as though they were declared
5134 // as __strong.
5135 if (GCAttrs == Qualifiers::GCNone) {
5136 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5137 return Qualifiers::Strong;
5138 else if (Ty->isPointerType())
5139 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5140 } else {
5141 // It's not valid to set GC attributes on anything that isn't a
5142 // pointer.
5143#ifndef NDEBUG
5144 QualType CT = Ty->getCanonicalTypeInternal();
5145 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5146 CT = AT->getElementType();
5147 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5148#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005149 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005150 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005151}
5152
Chris Lattner49af6a42008-04-07 06:51:04 +00005153//===----------------------------------------------------------------------===//
5154// Type Compatibility Testing
5155//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005156
Mike Stump11289f42009-09-09 15:08:12 +00005157/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005158/// compatible.
5159static bool areCompatVectorTypes(const VectorType *LHS,
5160 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005161 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005162 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005163 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005164}
5165
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005166bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5167 QualType SecondVec) {
5168 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5169 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5170
5171 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5172 return true;
5173
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005174 // Treat Neon vector types and most AltiVec vector types as if they are the
5175 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005176 const VectorType *First = FirstVec->getAs<VectorType>();
5177 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005178 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005179 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005180 First->getVectorKind() != VectorType::AltiVecPixel &&
5181 First->getVectorKind() != VectorType::AltiVecBool &&
5182 Second->getVectorKind() != VectorType::AltiVecPixel &&
5183 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005184 return true;
5185
5186 return false;
5187}
5188
Steve Naroff8e6aee52009-07-23 01:01:38 +00005189//===----------------------------------------------------------------------===//
5190// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5191//===----------------------------------------------------------------------===//
5192
5193/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5194/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005195bool
5196ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5197 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005198 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005199 return true;
5200 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5201 E = rProto->protocol_end(); PI != E; ++PI)
5202 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5203 return true;
5204 return false;
5205}
5206
Steve Naroff8e6aee52009-07-23 01:01:38 +00005207/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5208/// return true if lhs's protocols conform to rhs's protocol; false
5209/// otherwise.
5210bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5211 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5212 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5213 return false;
5214}
5215
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005216/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5217/// Class<p1, ...>.
5218bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5219 QualType rhs) {
5220 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5221 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5222 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5223
5224 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5225 E = lhsQID->qual_end(); I != E; ++I) {
5226 bool match = false;
5227 ObjCProtocolDecl *lhsProto = *I;
5228 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5229 E = rhsOPT->qual_end(); J != E; ++J) {
5230 ObjCProtocolDecl *rhsProto = *J;
5231 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5232 match = true;
5233 break;
5234 }
5235 }
5236 if (!match)
5237 return false;
5238 }
5239 return true;
5240}
5241
Steve Naroff8e6aee52009-07-23 01:01:38 +00005242/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5243/// ObjCQualifiedIDType.
5244bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5245 bool compare) {
5246 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005247 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005248 lhs->isObjCIdType() || lhs->isObjCClassType())
5249 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005250 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005251 rhs->isObjCIdType() || rhs->isObjCClassType())
5252 return true;
5253
5254 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005255 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005256
Steve Naroff8e6aee52009-07-23 01:01:38 +00005257 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005258
Steve Naroff8e6aee52009-07-23 01:01:38 +00005259 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005260 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005261 // make sure we check the class hierarchy.
5262 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5263 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5264 E = lhsQID->qual_end(); I != E; ++I) {
5265 // when comparing an id<P> on lhs with a static type on rhs,
5266 // see if static class implements all of id's protocols, directly or
5267 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005268 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005269 return false;
5270 }
5271 }
5272 // If there are no qualifiers and no interface, we have an 'id'.
5273 return true;
5274 }
Mike Stump11289f42009-09-09 15:08:12 +00005275 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005276 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5277 E = lhsQID->qual_end(); I != E; ++I) {
5278 ObjCProtocolDecl *lhsProto = *I;
5279 bool match = false;
5280
5281 // when comparing an id<P> on lhs with a static type on rhs,
5282 // see if static class implements all of id's protocols, directly or
5283 // through its super class and categories.
5284 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5285 E = rhsOPT->qual_end(); J != E; ++J) {
5286 ObjCProtocolDecl *rhsProto = *J;
5287 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5288 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5289 match = true;
5290 break;
5291 }
5292 }
Mike Stump11289f42009-09-09 15:08:12 +00005293 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005294 // make sure we check the class hierarchy.
5295 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5296 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5297 E = lhsQID->qual_end(); I != E; ++I) {
5298 // when comparing an id<P> on lhs with a static type on rhs,
5299 // see if static class implements all of id's protocols, directly or
5300 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005301 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005302 match = true;
5303 break;
5304 }
5305 }
5306 }
5307 if (!match)
5308 return false;
5309 }
Mike Stump11289f42009-09-09 15:08:12 +00005310
Steve Naroff8e6aee52009-07-23 01:01:38 +00005311 return true;
5312 }
Mike Stump11289f42009-09-09 15:08:12 +00005313
Steve Naroff8e6aee52009-07-23 01:01:38 +00005314 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5315 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5316
Mike Stump11289f42009-09-09 15:08:12 +00005317 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005318 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005319 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005320 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5321 E = lhsOPT->qual_end(); I != E; ++I) {
5322 ObjCProtocolDecl *lhsProto = *I;
5323 bool match = false;
5324
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005325 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005326 // see if static class implements all of id's protocols, directly or
5327 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005328 // First, lhs protocols in the qualifier list must be found, direct
5329 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005330 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5331 E = rhsQID->qual_end(); J != E; ++J) {
5332 ObjCProtocolDecl *rhsProto = *J;
5333 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5334 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5335 match = true;
5336 break;
5337 }
5338 }
5339 if (!match)
5340 return false;
5341 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005342
5343 // Static class's protocols, or its super class or category protocols
5344 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5345 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5346 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5347 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5348 // This is rather dubious but matches gcc's behavior. If lhs has
5349 // no type qualifier and its class has no static protocol(s)
5350 // assume that it is mismatch.
5351 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5352 return false;
5353 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5354 LHSInheritedProtocols.begin(),
5355 E = LHSInheritedProtocols.end(); I != E; ++I) {
5356 bool match = false;
5357 ObjCProtocolDecl *lhsProto = (*I);
5358 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5359 E = rhsQID->qual_end(); J != E; ++J) {
5360 ObjCProtocolDecl *rhsProto = *J;
5361 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5362 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5363 match = true;
5364 break;
5365 }
5366 }
5367 if (!match)
5368 return false;
5369 }
5370 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005371 return true;
5372 }
5373 return false;
5374}
5375
Eli Friedman47f77112008-08-22 00:56:42 +00005376/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005377/// compatible for assignment from RHS to LHS. This handles validation of any
5378/// protocol qualifiers on the LHS or RHS.
5379///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005380bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5381 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005382 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5383 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5384
Steve Naroff1329fa02009-07-15 18:40:39 +00005385 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005386 if (LHS->isObjCUnqualifiedIdOrClass() ||
5387 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005388 return true;
5389
John McCall8b07ec22010-05-15 11:32:37 +00005390 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005391 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5392 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005393 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005394
5395 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5396 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5397 QualType(RHSOPT,0));
5398
John McCall8b07ec22010-05-15 11:32:37 +00005399 // If we have 2 user-defined types, fall into that path.
5400 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005401 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005402
Steve Naroff8e6aee52009-07-23 01:01:38 +00005403 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005404}
5405
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005406/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005407/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005408/// arguments in block literals. When passed as arguments, passing 'A*' where
5409/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5410/// not OK. For the return type, the opposite is not OK.
5411bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5412 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005413 const ObjCObjectPointerType *RHSOPT,
5414 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005415 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005416 return true;
5417
5418 if (LHSOPT->isObjCBuiltinType()) {
5419 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5420 }
5421
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005422 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005423 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5424 QualType(RHSOPT,0),
5425 false);
5426
5427 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5428 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5429 if (LHS && RHS) { // We have 2 user-defined types.
5430 if (LHS != RHS) {
5431 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005432 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005433 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005434 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005435 }
5436 else
5437 return true;
5438 }
5439 return false;
5440}
5441
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005442/// getIntersectionOfProtocols - This routine finds the intersection of set
5443/// of protocols inherited from two distinct objective-c pointer objects.
5444/// It is used to build composite qualifier list of the composite type of
5445/// the conditional expression involving two objective-c pointer objects.
5446static
5447void getIntersectionOfProtocols(ASTContext &Context,
5448 const ObjCObjectPointerType *LHSOPT,
5449 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005450 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005451
John McCall8b07ec22010-05-15 11:32:37 +00005452 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5453 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5454 assert(LHS->getInterface() && "LHS must have an interface base");
5455 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005456
5457 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5458 unsigned LHSNumProtocols = LHS->getNumProtocols();
5459 if (LHSNumProtocols > 0)
5460 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5461 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005462 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005463 Context.CollectInheritedProtocols(LHS->getInterface(),
5464 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005465 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5466 LHSInheritedProtocols.end());
5467 }
5468
5469 unsigned RHSNumProtocols = RHS->getNumProtocols();
5470 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005471 ObjCProtocolDecl **RHSProtocols =
5472 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005473 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5474 if (InheritedProtocolSet.count(RHSProtocols[i]))
5475 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005476 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005477 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005478 Context.CollectInheritedProtocols(RHS->getInterface(),
5479 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005480 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5481 RHSInheritedProtocols.begin(),
5482 E = RHSInheritedProtocols.end(); I != E; ++I)
5483 if (InheritedProtocolSet.count((*I)))
5484 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005485 }
5486}
5487
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005488/// areCommonBaseCompatible - Returns common base class of the two classes if
5489/// one found. Note that this is O'2 algorithm. But it will be called as the
5490/// last type comparison in a ?-exp of ObjC pointer types before a
5491/// warning is issued. So, its invokation is extremely rare.
5492QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005493 const ObjCObjectPointerType *Lptr,
5494 const ObjCObjectPointerType *Rptr) {
5495 const ObjCObjectType *LHS = Lptr->getObjectType();
5496 const ObjCObjectType *RHS = Rptr->getObjectType();
5497 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5498 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005499 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005500 return QualType();
5501
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005502 do {
John McCall8b07ec22010-05-15 11:32:37 +00005503 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005504 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005505 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005506 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5507
5508 QualType Result = QualType(LHS, 0);
5509 if (!Protocols.empty())
5510 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5511 Result = getObjCObjectPointerType(Result);
5512 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005513 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005514 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005515
5516 return QualType();
5517}
5518
John McCall8b07ec22010-05-15 11:32:37 +00005519bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5520 const ObjCObjectType *RHS) {
5521 assert(LHS->getInterface() && "LHS is not an interface type");
5522 assert(RHS->getInterface() && "RHS is not an interface type");
5523
Chris Lattner49af6a42008-04-07 06:51:04 +00005524 // Verify that the base decls are compatible: the RHS must be a subclass of
5525 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005526 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005527 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005528
Chris Lattner49af6a42008-04-07 06:51:04 +00005529 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5530 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005531 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005532 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005533
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005534 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5535 // more detailed analysis is required.
5536 if (RHS->getNumProtocols() == 0) {
5537 // OK, if LHS is a superclass of RHS *and*
5538 // this superclass is assignment compatible with LHS.
5539 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005540 bool IsSuperClass =
5541 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5542 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005543 // OK if conversion of LHS to SuperClass results in narrowing of types
5544 // ; i.e., SuperClass may implement at least one of the protocols
5545 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5546 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5547 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005548 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005549 // If super class has no protocols, it is not a match.
5550 if (SuperClassInheritedProtocols.empty())
5551 return false;
5552
5553 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5554 LHSPE = LHS->qual_end();
5555 LHSPI != LHSPE; LHSPI++) {
5556 bool SuperImplementsProtocol = false;
5557 ObjCProtocolDecl *LHSProto = (*LHSPI);
5558
5559 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5560 SuperClassInheritedProtocols.begin(),
5561 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5562 ObjCProtocolDecl *SuperClassProto = (*I);
5563 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5564 SuperImplementsProtocol = true;
5565 break;
5566 }
5567 }
5568 if (!SuperImplementsProtocol)
5569 return false;
5570 }
5571 return true;
5572 }
5573 return false;
5574 }
Mike Stump11289f42009-09-09 15:08:12 +00005575
John McCall8b07ec22010-05-15 11:32:37 +00005576 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5577 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005578 LHSPI != LHSPE; LHSPI++) {
5579 bool RHSImplementsProtocol = false;
5580
5581 // If the RHS doesn't implement the protocol on the left, the types
5582 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005583 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5584 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005585 RHSPI != RHSPE; RHSPI++) {
5586 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005587 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005588 break;
5589 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005590 }
5591 // FIXME: For better diagnostics, consider passing back the protocol name.
5592 if (!RHSImplementsProtocol)
5593 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005594 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005595 // The RHS implements all protocols listed on the LHS.
5596 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005597}
5598
Steve Naroffb7605152009-02-12 17:52:19 +00005599bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5600 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005601 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5602 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005603
Steve Naroff7cae42b2009-07-10 23:34:53 +00005604 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005605 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005606
5607 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5608 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005609}
5610
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005611bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5612 return canAssignObjCInterfaces(
5613 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5614 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5615}
5616
Mike Stump11289f42009-09-09 15:08:12 +00005617/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005618/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005619/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005620/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005621bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5622 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005623 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00005624 return hasSameType(LHS, RHS);
5625
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005626 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005627}
5628
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005629bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005630 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005631}
5632
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005633bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5634 return !mergeTypes(LHS, RHS, true).isNull();
5635}
5636
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005637/// mergeTransparentUnionType - if T is a transparent union type and a member
5638/// of T is compatible with SubType, return the merged type, else return
5639/// QualType()
5640QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5641 bool OfBlockPointer,
5642 bool Unqualified) {
5643 if (const RecordType *UT = T->getAsUnionType()) {
5644 RecordDecl *UD = UT->getDecl();
5645 if (UD->hasAttr<TransparentUnionAttr>()) {
5646 for (RecordDecl::field_iterator it = UD->field_begin(),
5647 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005648 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005649 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5650 if (!MT.isNull())
5651 return MT;
5652 }
5653 }
5654 }
5655
5656 return QualType();
5657}
5658
5659/// mergeFunctionArgumentTypes - merge two types which appear as function
5660/// argument types
5661QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5662 bool OfBlockPointer,
5663 bool Unqualified) {
5664 // GNU extension: two types are compatible if they appear as a function
5665 // argument, one of the types is a transparent union type and the other
5666 // type is compatible with a union member
5667 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5668 Unqualified);
5669 if (!lmerge.isNull())
5670 return lmerge;
5671
5672 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5673 Unqualified);
5674 if (!rmerge.isNull())
5675 return rmerge;
5676
5677 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5678}
5679
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005680QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005681 bool OfBlockPointer,
5682 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005683 const FunctionType *lbase = lhs->getAs<FunctionType>();
5684 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005685 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5686 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005687 bool allLTypes = true;
5688 bool allRTypes = true;
5689
5690 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005691 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005692 if (OfBlockPointer) {
5693 QualType RHS = rbase->getResultType();
5694 QualType LHS = lbase->getResultType();
5695 bool UnqualifiedResult = Unqualified;
5696 if (!UnqualifiedResult)
5697 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005698 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005699 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005700 else
John McCall8c6b56f2010-12-15 01:06:38 +00005701 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5702 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005703 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005704
5705 if (Unqualified)
5706 retType = retType.getUnqualifiedType();
5707
5708 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5709 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5710 if (Unqualified) {
5711 LRetType = LRetType.getUnqualifiedType();
5712 RRetType = RRetType.getUnqualifiedType();
5713 }
5714
5715 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005716 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005717 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005718 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005719
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005720 // FIXME: double check this
5721 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5722 // rbase->getRegParmAttr() != 0 &&
5723 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005724 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5725 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005726
Douglas Gregor8c940862010-01-18 17:14:39 +00005727 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005728 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005729 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005730
John McCall8c6b56f2010-12-15 01:06:38 +00005731 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005732 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5733 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005734 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5735 return QualType();
5736
John McCall31168b02011-06-15 23:02:42 +00005737 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5738 return QualType();
5739
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005740 // functypes which return are preferred over those that do not.
5741 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5742 allLTypes = false;
5743 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5744 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005745 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5746 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00005747
John McCall31168b02011-06-15 23:02:42 +00005748 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005749
Eli Friedman47f77112008-08-22 00:56:42 +00005750 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005751 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5752 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005753 unsigned lproto_nargs = lproto->getNumArgs();
5754 unsigned rproto_nargs = rproto->getNumArgs();
5755
5756 // Compatible functions must have the same number of arguments
5757 if (lproto_nargs != rproto_nargs)
5758 return QualType();
5759
5760 // Variadic and non-variadic functions aren't compatible
5761 if (lproto->isVariadic() != rproto->isVariadic())
5762 return QualType();
5763
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005764 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5765 return QualType();
5766
Fariborz Jahanian97676972011-09-28 21:52:05 +00005767 if (LangOpts.ObjCAutoRefCount &&
5768 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5769 return QualType();
5770
Eli Friedman47f77112008-08-22 00:56:42 +00005771 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005772 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00005773 for (unsigned i = 0; i < lproto_nargs; i++) {
5774 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5775 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005776 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5777 OfBlockPointer,
5778 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005779 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005780
5781 if (Unqualified)
5782 argtype = argtype.getUnqualifiedType();
5783
Eli Friedman47f77112008-08-22 00:56:42 +00005784 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005785 if (Unqualified) {
5786 largtype = largtype.getUnqualifiedType();
5787 rargtype = rargtype.getUnqualifiedType();
5788 }
5789
Chris Lattner465fa322008-10-05 17:34:18 +00005790 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5791 allLTypes = false;
5792 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5793 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005794 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00005795
Eli Friedman47f77112008-08-22 00:56:42 +00005796 if (allLTypes) return lhs;
5797 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005798
5799 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5800 EPI.ExtInfo = einfo;
5801 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005802 }
5803
5804 if (lproto) allRTypes = false;
5805 if (rproto) allLTypes = false;
5806
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005807 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005808 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005809 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005810 if (proto->isVariadic()) return QualType();
5811 // Check that the types are compatible with the types that
5812 // would result from default argument promotions (C99 6.7.5.3p15).
5813 // The only types actually affected are promotable integer
5814 // types and floats, which would be passed as a different
5815 // type depending on whether the prototype is visible.
5816 unsigned proto_nargs = proto->getNumArgs();
5817 for (unsigned i = 0; i < proto_nargs; ++i) {
5818 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005819
5820 // Look at the promotion type of enum types, since that is the type used
5821 // to pass enum values.
5822 if (const EnumType *Enum = argTy->getAs<EnumType>())
5823 argTy = Enum->getDecl()->getPromotionType();
5824
Eli Friedman47f77112008-08-22 00:56:42 +00005825 if (argTy->isPromotableIntegerType() ||
5826 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5827 return QualType();
5828 }
5829
5830 if (allLTypes) return lhs;
5831 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005832
5833 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5834 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005835 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005836 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005837 }
5838
5839 if (allLTypes) return lhs;
5840 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005841 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005842}
5843
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005844QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005845 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005846 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005847 // C++ [expr]: If an expression initially has the type "reference to T", the
5848 // type is adjusted to "T" prior to any further analysis, the expression
5849 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005850 // expression is an lvalue unless the reference is an rvalue reference and
5851 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005852 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5853 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005854
5855 if (Unqualified) {
5856 LHS = LHS.getUnqualifiedType();
5857 RHS = RHS.getUnqualifiedType();
5858 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005859
Eli Friedman47f77112008-08-22 00:56:42 +00005860 QualType LHSCan = getCanonicalType(LHS),
5861 RHSCan = getCanonicalType(RHS);
5862
5863 // If two types are identical, they are compatible.
5864 if (LHSCan == RHSCan)
5865 return LHS;
5866
John McCall8ccfcb52009-09-24 19:53:00 +00005867 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005868 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5869 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005870 if (LQuals != RQuals) {
5871 // If any of these qualifiers are different, we have a type
5872 // mismatch.
5873 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005874 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5875 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005876 return QualType();
5877
5878 // Exactly one GC qualifier difference is allowed: __strong is
5879 // okay if the other type has no GC qualifier but is an Objective
5880 // C object pointer (i.e. implicitly strong by default). We fix
5881 // this by pretending that the unqualified type was actually
5882 // qualified __strong.
5883 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5884 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5885 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5886
5887 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5888 return QualType();
5889
5890 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5891 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5892 }
5893 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5894 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5895 }
Eli Friedman47f77112008-08-22 00:56:42 +00005896 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005897 }
5898
5899 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005900
Eli Friedmandcca6332009-06-01 01:22:52 +00005901 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5902 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005903
Chris Lattnerfd652912008-01-14 05:45:46 +00005904 // We want to consider the two function types to be the same for these
5905 // comparisons, just force one to the other.
5906 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5907 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005908
5909 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005910 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5911 LHSClass = Type::ConstantArray;
5912 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5913 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005914
John McCall8b07ec22010-05-15 11:32:37 +00005915 // ObjCInterfaces are just specialized ObjCObjects.
5916 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5917 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5918
Nate Begemance4d7fc2008-04-18 23:10:10 +00005919 // Canonicalize ExtVector -> Vector.
5920 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5921 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005922
Chris Lattner95554662008-04-07 05:43:21 +00005923 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005924 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005925 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005926 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005927 // Compatibility is based on the underlying type, not the promotion
5928 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005929 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00005930 QualType TINT = ETy->getDecl()->getIntegerType();
5931 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00005932 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005933 }
John McCall9dd450b2009-09-21 23:43:11 +00005934 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00005935 QualType TINT = ETy->getDecl()->getIntegerType();
5936 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00005937 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005938 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00005939 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00005940 if (OfBlockPointer && !BlockReturnType) {
5941 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5942 return LHS;
5943 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5944 return RHS;
5945 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00005946
Eli Friedman47f77112008-08-22 00:56:42 +00005947 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005948 }
Eli Friedman47f77112008-08-22 00:56:42 +00005949
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005950 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005951 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005952#define TYPE(Class, Base)
5953#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005954#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005955#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5956#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5957#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00005958 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005959
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005960 case Type::LValueReference:
5961 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005962 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00005963 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005964
John McCall8b07ec22010-05-15 11:32:37 +00005965 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005966 case Type::IncompleteArray:
5967 case Type::VariableArray:
5968 case Type::FunctionProto:
5969 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00005970 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005971
Chris Lattnerfd652912008-01-14 05:45:46 +00005972 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005973 {
5974 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005975 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5976 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005977 if (Unqualified) {
5978 LHSPointee = LHSPointee.getUnqualifiedType();
5979 RHSPointee = RHSPointee.getUnqualifiedType();
5980 }
5981 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5982 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005983 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005984 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005985 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005986 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005987 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005988 return getPointerType(ResultType);
5989 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005990 case Type::BlockPointer:
5991 {
5992 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005993 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5994 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005995 if (Unqualified) {
5996 LHSPointee = LHSPointee.getUnqualifiedType();
5997 RHSPointee = RHSPointee.getUnqualifiedType();
5998 }
5999 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6000 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006001 if (ResultType.isNull()) return QualType();
6002 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6003 return LHS;
6004 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6005 return RHS;
6006 return getBlockPointerType(ResultType);
6007 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006008 case Type::Atomic:
6009 {
6010 // Merge two pointer types, while trying to preserve typedef info
6011 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6012 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6013 if (Unqualified) {
6014 LHSValue = LHSValue.getUnqualifiedType();
6015 RHSValue = RHSValue.getUnqualifiedType();
6016 }
6017 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6018 Unqualified);
6019 if (ResultType.isNull()) return QualType();
6020 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6021 return LHS;
6022 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6023 return RHS;
6024 return getAtomicType(ResultType);
6025 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006026 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006027 {
6028 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6029 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6030 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6031 return QualType();
6032
6033 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6034 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006035 if (Unqualified) {
6036 LHSElem = LHSElem.getUnqualifiedType();
6037 RHSElem = RHSElem.getUnqualifiedType();
6038 }
6039
6040 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006041 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006042 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6043 return LHS;
6044 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6045 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006046 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6047 ArrayType::ArraySizeModifier(), 0);
6048 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6049 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006050 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6051 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006052 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6053 return LHS;
6054 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6055 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006056 if (LVAT) {
6057 // FIXME: This isn't correct! But tricky to implement because
6058 // the array's size has to be the size of LHS, but the type
6059 // has to be different.
6060 return LHS;
6061 }
6062 if (RVAT) {
6063 // FIXME: This isn't correct! But tricky to implement because
6064 // the array's size has to be the size of RHS, but the type
6065 // has to be different.
6066 return RHS;
6067 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006068 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6069 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006070 return getIncompleteArrayType(ResultType,
6071 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006072 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006073 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006074 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006075 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006076 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006077 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006078 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006079 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006080 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006081 case Type::Complex:
6082 // Distinct complex types are incompatible.
6083 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006084 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006085 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006086 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6087 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006088 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006089 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006090 case Type::ObjCObject: {
6091 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006092 // FIXME: This should be type compatibility, e.g. whether
6093 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006094 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6095 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6096 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006097 return LHS;
6098
Eli Friedman47f77112008-08-22 00:56:42 +00006099 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006100 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006101 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006102 if (OfBlockPointer) {
6103 if (canAssignObjCInterfacesInBlockPointer(
6104 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006105 RHS->getAs<ObjCObjectPointerType>(),
6106 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006107 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006108 return QualType();
6109 }
John McCall9dd450b2009-09-21 23:43:11 +00006110 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6111 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006112 return LHS;
6113
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006114 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006115 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006116 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006117
David Blaikie8a40f702012-01-17 06:56:22 +00006118 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006119}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006120
Fariborz Jahanian97676972011-09-28 21:52:05 +00006121bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6122 const FunctionProtoType *FromFunctionType,
6123 const FunctionProtoType *ToFunctionType) {
6124 if (FromFunctionType->hasAnyConsumedArgs() !=
6125 ToFunctionType->hasAnyConsumedArgs())
6126 return false;
6127 FunctionProtoType::ExtProtoInfo FromEPI =
6128 FromFunctionType->getExtProtoInfo();
6129 FunctionProtoType::ExtProtoInfo ToEPI =
6130 ToFunctionType->getExtProtoInfo();
6131 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6132 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6133 ArgIdx != NumArgs; ++ArgIdx) {
6134 if (FromEPI.ConsumedArguments[ArgIdx] !=
6135 ToEPI.ConsumedArguments[ArgIdx])
6136 return false;
6137 }
6138 return true;
6139}
6140
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006141/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6142/// 'RHS' attributes and returns the merged version; including for function
6143/// return types.
6144QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6145 QualType LHSCan = getCanonicalType(LHS),
6146 RHSCan = getCanonicalType(RHS);
6147 // If two types are identical, they are compatible.
6148 if (LHSCan == RHSCan)
6149 return LHS;
6150 if (RHSCan->isFunctionType()) {
6151 if (!LHSCan->isFunctionType())
6152 return QualType();
6153 QualType OldReturnType =
6154 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6155 QualType NewReturnType =
6156 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6157 QualType ResReturnType =
6158 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6159 if (ResReturnType.isNull())
6160 return QualType();
6161 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6162 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6163 // In either case, use OldReturnType to build the new function type.
6164 const FunctionType *F = LHS->getAs<FunctionType>();
6165 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006166 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6167 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006168 QualType ResultType
6169 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006170 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006171 return ResultType;
6172 }
6173 }
6174 return QualType();
6175 }
6176
6177 // If the qualifiers are different, the types can still be merged.
6178 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6179 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6180 if (LQuals != RQuals) {
6181 // If any of these qualifiers are different, we have a type mismatch.
6182 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6183 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6184 return QualType();
6185
6186 // Exactly one GC qualifier difference is allowed: __strong is
6187 // okay if the other type has no GC qualifier but is an Objective
6188 // C object pointer (i.e. implicitly strong by default). We fix
6189 // this by pretending that the unqualified type was actually
6190 // qualified __strong.
6191 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6192 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6193 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6194
6195 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6196 return QualType();
6197
6198 if (GC_L == Qualifiers::Strong)
6199 return LHS;
6200 if (GC_R == Qualifiers::Strong)
6201 return RHS;
6202 return QualType();
6203 }
6204
6205 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6206 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6207 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6208 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6209 if (ResQT == LHSBaseQT)
6210 return LHS;
6211 if (ResQT == RHSBaseQT)
6212 return RHS;
6213 }
6214 return QualType();
6215}
6216
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006217//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006218// Integer Predicates
6219//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006220
Jay Foad39c79802011-01-12 09:06:06 +00006221unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006222 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006223 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006224 if (T->isBooleanType())
6225 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006226 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006227 return (unsigned)getTypeSize(T);
6228}
6229
6230QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006231 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006232
6233 // Turn <4 x signed int> -> <4 x unsigned int>
6234 if (const VectorType *VTy = T->getAs<VectorType>())
6235 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006236 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006237
6238 // For enums, we return the unsigned version of the base type.
6239 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006240 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006241
6242 const BuiltinType *BTy = T->getAs<BuiltinType>();
6243 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006244 switch (BTy->getKind()) {
6245 case BuiltinType::Char_S:
6246 case BuiltinType::SChar:
6247 return UnsignedCharTy;
6248 case BuiltinType::Short:
6249 return UnsignedShortTy;
6250 case BuiltinType::Int:
6251 return UnsignedIntTy;
6252 case BuiltinType::Long:
6253 return UnsignedLongTy;
6254 case BuiltinType::LongLong:
6255 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006256 case BuiltinType::Int128:
6257 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006258 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006259 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006260 }
6261}
6262
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006263ASTMutationListener::~ASTMutationListener() { }
6264
Chris Lattnerecd79c62009-06-14 00:45:47 +00006265
6266//===----------------------------------------------------------------------===//
6267// Builtin Type Computation
6268//===----------------------------------------------------------------------===//
6269
6270/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006271/// pointer over the consumed characters. This returns the resultant type. If
6272/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6273/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6274/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006275///
6276/// RequiresICE is filled in on return to indicate whether the value is required
6277/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006278static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006279 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006280 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006281 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006282 // Modifiers.
6283 int HowLong = 0;
6284 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006285 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006286
Chris Lattnerdc226c22010-10-01 22:42:38 +00006287 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006288 bool Done = false;
6289 while (!Done) {
6290 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006291 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006292 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006293 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006294 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006295 case 'S':
6296 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6297 assert(!Signed && "Can't use 'S' modifier multiple times!");
6298 Signed = true;
6299 break;
6300 case 'U':
6301 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6302 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6303 Unsigned = true;
6304 break;
6305 case 'L':
6306 assert(HowLong <= 2 && "Can't have LLLL modifier");
6307 ++HowLong;
6308 break;
6309 }
6310 }
6311
6312 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006313
Chris Lattnerecd79c62009-06-14 00:45:47 +00006314 // Read the base type.
6315 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006316 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006317 case 'v':
6318 assert(HowLong == 0 && !Signed && !Unsigned &&
6319 "Bad modifiers used with 'v'!");
6320 Type = Context.VoidTy;
6321 break;
6322 case 'f':
6323 assert(HowLong == 0 && !Signed && !Unsigned &&
6324 "Bad modifiers used with 'f'!");
6325 Type = Context.FloatTy;
6326 break;
6327 case 'd':
6328 assert(HowLong < 2 && !Signed && !Unsigned &&
6329 "Bad modifiers used with 'd'!");
6330 if (HowLong)
6331 Type = Context.LongDoubleTy;
6332 else
6333 Type = Context.DoubleTy;
6334 break;
6335 case 's':
6336 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6337 if (Unsigned)
6338 Type = Context.UnsignedShortTy;
6339 else
6340 Type = Context.ShortTy;
6341 break;
6342 case 'i':
6343 if (HowLong == 3)
6344 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6345 else if (HowLong == 2)
6346 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6347 else if (HowLong == 1)
6348 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6349 else
6350 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6351 break;
6352 case 'c':
6353 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6354 if (Signed)
6355 Type = Context.SignedCharTy;
6356 else if (Unsigned)
6357 Type = Context.UnsignedCharTy;
6358 else
6359 Type = Context.CharTy;
6360 break;
6361 case 'b': // boolean
6362 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6363 Type = Context.BoolTy;
6364 break;
6365 case 'z': // size_t.
6366 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6367 Type = Context.getSizeType();
6368 break;
6369 case 'F':
6370 Type = Context.getCFConstantStringType();
6371 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006372 case 'G':
6373 Type = Context.getObjCIdType();
6374 break;
6375 case 'H':
6376 Type = Context.getObjCSelType();
6377 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006378 case 'a':
6379 Type = Context.getBuiltinVaListType();
6380 assert(!Type.isNull() && "builtin va list type not initialized!");
6381 break;
6382 case 'A':
6383 // This is a "reference" to a va_list; however, what exactly
6384 // this means depends on how va_list is defined. There are two
6385 // different kinds of va_list: ones passed by value, and ones
6386 // passed by reference. An example of a by-value va_list is
6387 // x86, where va_list is a char*. An example of by-ref va_list
6388 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6389 // we want this argument to be a char*&; for x86-64, we want
6390 // it to be a __va_list_tag*.
6391 Type = Context.getBuiltinVaListType();
6392 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006393 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006394 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006395 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006396 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006397 break;
6398 case 'V': {
6399 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006400 unsigned NumElements = strtoul(Str, &End, 10);
6401 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006402 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006403
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006404 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6405 RequiresICE, false);
6406 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006407
6408 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006409 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006410 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006411 break;
6412 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006413 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006414 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6415 false);
6416 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006417 Type = Context.getComplexType(ElementType);
6418 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006419 }
6420 case 'Y' : {
6421 Type = Context.getPointerDiffType();
6422 break;
6423 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006424 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006425 Type = Context.getFILEType();
6426 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006427 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006428 return QualType();
6429 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006430 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006431 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006432 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006433 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006434 else
6435 Type = Context.getjmp_bufType();
6436
Mike Stump2adb4da2009-07-28 23:47:15 +00006437 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006438 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006439 return QualType();
6440 }
6441 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006442 case 'K':
6443 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6444 Type = Context.getucontext_tType();
6445
6446 if (Type.isNull()) {
6447 Error = ASTContext::GE_Missing_ucontext;
6448 return QualType();
6449 }
6450 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006451 }
Mike Stump11289f42009-09-09 15:08:12 +00006452
Chris Lattnerdc226c22010-10-01 22:42:38 +00006453 // If there are modifiers and if we're allowed to parse them, go for it.
6454 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006455 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006456 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006457 default: Done = true; --Str; break;
6458 case '*':
6459 case '&': {
6460 // Both pointers and references can have their pointee types
6461 // qualified with an address space.
6462 char *End;
6463 unsigned AddrSpace = strtoul(Str, &End, 10);
6464 if (End != Str && AddrSpace != 0) {
6465 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6466 Str = End;
6467 }
6468 if (c == '*')
6469 Type = Context.getPointerType(Type);
6470 else
6471 Type = Context.getLValueReferenceType(Type);
6472 break;
6473 }
6474 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6475 case 'C':
6476 Type = Type.withConst();
6477 break;
6478 case 'D':
6479 Type = Context.getVolatileType(Type);
6480 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006481 case 'R':
6482 Type = Type.withRestrict();
6483 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006484 }
6485 }
Chris Lattner84733392010-10-01 07:13:18 +00006486
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006487 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006488 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006489
Chris Lattnerecd79c62009-06-14 00:45:47 +00006490 return Type;
6491}
6492
6493/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006494QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006495 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006496 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006497 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006498
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006499 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006500
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006501 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006502 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006503 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6504 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006505 if (Error != GE_None)
6506 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006507
6508 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6509
Chris Lattnerecd79c62009-06-14 00:45:47 +00006510 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006511 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006512 if (Error != GE_None)
6513 return QualType();
6514
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006515 // If this argument is required to be an IntegerConstantExpression and the
6516 // caller cares, fill in the bitmask we return.
6517 if (RequiresICE && IntegerConstantArgs)
6518 *IntegerConstantArgs |= 1 << ArgTypes.size();
6519
Chris Lattnerecd79c62009-06-14 00:45:47 +00006520 // Do array -> pointer decay. The builtin should use the decayed type.
6521 if (Ty->isArrayType())
6522 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006523
Chris Lattnerecd79c62009-06-14 00:45:47 +00006524 ArgTypes.push_back(Ty);
6525 }
6526
6527 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6528 "'.' should only occur at end of builtin type list!");
6529
John McCall991eb4b2010-12-21 00:44:39 +00006530 FunctionType::ExtInfo EI;
6531 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6532
6533 bool Variadic = (TypeStr[0] == '.');
6534
6535 // We really shouldn't be making a no-proto type here, especially in C++.
6536 if (ArgTypes.empty() && Variadic)
6537 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006538
John McCalldb40c7f2010-12-14 08:05:40 +00006539 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006540 EPI.ExtInfo = EI;
6541 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006542
6543 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006544}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006545
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006546GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6547 GVALinkage External = GVA_StrongExternal;
6548
6549 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006550 switch (L) {
6551 case NoLinkage:
6552 case InternalLinkage:
6553 case UniqueExternalLinkage:
6554 return GVA_Internal;
6555
6556 case ExternalLinkage:
6557 switch (FD->getTemplateSpecializationKind()) {
6558 case TSK_Undeclared:
6559 case TSK_ExplicitSpecialization:
6560 External = GVA_StrongExternal;
6561 break;
6562
6563 case TSK_ExplicitInstantiationDefinition:
6564 return GVA_ExplicitTemplateInstantiation;
6565
6566 case TSK_ExplicitInstantiationDeclaration:
6567 case TSK_ImplicitInstantiation:
6568 External = GVA_TemplateInstantiation;
6569 break;
6570 }
6571 }
6572
6573 if (!FD->isInlined())
6574 return External;
6575
David Blaikiebbafb8a2012-03-11 07:00:24 +00006576 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006577 // GNU or C99 inline semantics. Determine whether this symbol should be
6578 // externally visible.
6579 if (FD->isInlineDefinitionExternallyVisible())
6580 return External;
6581
6582 // C99 inline semantics, where the symbol is not externally visible.
6583 return GVA_C99Inline;
6584 }
6585
6586 // C++0x [temp.explicit]p9:
6587 // [ Note: The intent is that an inline function that is the subject of
6588 // an explicit instantiation declaration will still be implicitly
6589 // instantiated when used so that the body can be considered for
6590 // inlining, but that no out-of-line copy of the inline function would be
6591 // generated in the translation unit. -- end note ]
6592 if (FD->getTemplateSpecializationKind()
6593 == TSK_ExplicitInstantiationDeclaration)
6594 return GVA_C99Inline;
6595
6596 return GVA_CXXInline;
6597}
6598
6599GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6600 // If this is a static data member, compute the kind of template
6601 // specialization. Otherwise, this variable is not part of a
6602 // template.
6603 TemplateSpecializationKind TSK = TSK_Undeclared;
6604 if (VD->isStaticDataMember())
6605 TSK = VD->getTemplateSpecializationKind();
6606
6607 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006608 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006609 VD->getType()->getLinkage() == UniqueExternalLinkage)
6610 L = UniqueExternalLinkage;
6611
6612 switch (L) {
6613 case NoLinkage:
6614 case InternalLinkage:
6615 case UniqueExternalLinkage:
6616 return GVA_Internal;
6617
6618 case ExternalLinkage:
6619 switch (TSK) {
6620 case TSK_Undeclared:
6621 case TSK_ExplicitSpecialization:
6622 return GVA_StrongExternal;
6623
6624 case TSK_ExplicitInstantiationDeclaration:
6625 llvm_unreachable("Variable should not be instantiated");
6626 // Fall through to treat this like any other instantiation.
6627
6628 case TSK_ExplicitInstantiationDefinition:
6629 return GVA_ExplicitTemplateInstantiation;
6630
6631 case TSK_ImplicitInstantiation:
6632 return GVA_TemplateInstantiation;
6633 }
6634 }
6635
David Blaikie8a40f702012-01-17 06:56:22 +00006636 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006637}
6638
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006639bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006640 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6641 if (!VD->isFileVarDecl())
6642 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006643 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006644 return false;
6645
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006646 // Weak references don't produce any output by themselves.
6647 if (D->hasAttr<WeakRefAttr>())
6648 return false;
6649
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006650 // Aliases and used decls are required.
6651 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6652 return true;
6653
6654 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6655 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006656 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006657 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006658
6659 // Constructors and destructors are required.
6660 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6661 return true;
6662
6663 // The key function for a class is required.
6664 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6665 const CXXRecordDecl *RD = MD->getParent();
6666 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6667 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6668 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6669 return true;
6670 }
6671 }
6672
6673 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6674
6675 // static, static inline, always_inline, and extern inline functions can
6676 // always be deferred. Normal inline functions can be deferred in C99/C++.
6677 // Implicit template instantiations can also be deferred in C++.
6678 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00006679 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006680 return false;
6681 return true;
6682 }
Douglas Gregor87d81242011-09-10 00:22:34 +00006683
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006684 const VarDecl *VD = cast<VarDecl>(D);
6685 assert(VD->isFileVarDecl() && "Expected file scoped var");
6686
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006687 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6688 return false;
6689
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006690 // Structs that have non-trivial constructors or destructors are required.
6691
6692 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006693 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006694 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6695 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006696 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6697 RD->hasTrivialCopyConstructor() &&
6698 RD->hasTrivialMoveConstructor() &&
6699 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006700 return true;
6701 }
6702 }
6703
6704 GVALinkage L = GetGVALinkageForVariable(VD);
6705 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6706 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6707 return false;
6708 }
6709
6710 return true;
6711}
Charles Davis53c59df2010-08-16 03:33:14 +00006712
Charles Davis99202b32010-11-09 18:04:24 +00006713CallingConv ASTContext::getDefaultMethodCallConv() {
6714 // Pass through to the C++ ABI object
6715 return ABI->getDefaultMethodCallConv();
6716}
6717
Jay Foad39c79802011-01-12 09:06:06 +00006718bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006719 // Pass through to the C++ ABI object
6720 return ABI->isNearlyEmpty(RD);
6721}
6722
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006723MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00006724 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006725 case CXXABI_ARM:
6726 case CXXABI_Itanium:
6727 return createItaniumMangleContext(*this, getDiagnostics());
6728 case CXXABI_Microsoft:
6729 return createMicrosoftMangleContext(*this, getDiagnostics());
6730 }
David Blaikie83d382b2011-09-23 05:06:16 +00006731 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006732}
6733
Charles Davis53c59df2010-08-16 03:33:14 +00006734CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006735
6736size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00006737 return ASTRecordLayouts.getMemorySize()
6738 + llvm::capacity_in_bytes(ObjCLayouts)
6739 + llvm::capacity_in_bytes(KeyFunctions)
6740 + llvm::capacity_in_bytes(ObjCImpls)
6741 + llvm::capacity_in_bytes(BlockVarCopyInits)
6742 + llvm::capacity_in_bytes(DeclAttrs)
6743 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6744 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6745 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6746 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6747 + llvm::capacity_in_bytes(OverriddenMethods)
6748 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006749 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00006750 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006751}
Ted Kremenek540017e2011-10-06 05:00:56 +00006752
Douglas Gregor63798542012-02-20 19:44:39 +00006753unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
6754 CXXRecordDecl *Lambda = CallOperator->getParent();
6755 return LambdaMangleContexts[Lambda->getDeclContext()]
6756 .getManglingNumber(CallOperator);
6757}
6758
6759
Ted Kremenek540017e2011-10-06 05:00:56 +00006760void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6761 ParamIndices[D] = index;
6762}
6763
6764unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6765 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6766 assert(I != ParamIndices.end() &&
6767 "ParmIndices lacks entry set by ParmVarDecl");
6768 return I->second;
6769}