blob: 164813b7c35796044041e767c443c1f75cf27215 [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
Peter Collingbournef44bdf92012-05-20 21:08:35 +0000209 3, // opencl_constant
210 4, // cuda_device
211 5, // cuda_constant
212 6 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000213 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000214 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000215 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000216 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000217 }
218}
219
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000220ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000221 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000222 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000223 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000224 unsigned size_reserve,
225 bool DelayInitialization)
226 : FunctionProtoTypes(this_()),
227 TemplateSpecializationTypes(this_()),
228 DependentTemplateSpecializationTypes(this_()),
229 SubstTemplateTemplateParmPacks(this_()),
230 GlobalNestedNameSpecifier(0),
231 Int128Decl(0), UInt128Decl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000232 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000233 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000234 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000235 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
236 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
237 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000238 NullTypeSourceInfo(QualType()),
239 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000240 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000241 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000242 Idents(idents), Selectors(sels),
243 BuiltinInfo(builtins),
244 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000245 ExternalSource(0), Listener(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000246 LastSDM(0, 0),
247 UniqueBlockByRefTypeID(0)
248{
Mike Stump11289f42009-09-09 15:08:12 +0000249 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000250 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000251
252 if (!DelayInitialization) {
253 assert(t && "No target supplied for ASTContext initialization");
254 InitBuiltinTypes(*t);
255 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000256}
257
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000258ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000259 // Release the DenseMaps associated with DeclContext objects.
260 // FIXME: Is this the ideal solution?
261 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000262
Douglas Gregor5b11d492010-07-25 17:53:33 +0000263 // Call all of the deallocation functions.
264 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
265 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000266
Ted Kremenek076baeb2010-06-08 23:00:58 +0000267 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000268 // because they can contain DenseMaps.
269 for (llvm::DenseMap<const ObjCContainerDecl*,
270 const ASTRecordLayout*>::iterator
271 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
272 // Increment in loop to prevent using deallocated memory.
273 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
274 R->Destroy(*this);
275
Ted Kremenek076baeb2010-06-08 23:00:58 +0000276 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
277 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
278 // Increment in loop to prevent using deallocated memory.
279 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
280 R->Destroy(*this);
281 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000282
283 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
284 AEnd = DeclAttrs.end();
285 A != AEnd; ++A)
286 A->second->~AttrVec();
287}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000288
Douglas Gregor1a809332010-05-23 18:26:36 +0000289void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
290 Deallocations.push_back(std::make_pair(Callback, Data));
291}
292
Mike Stump11289f42009-09-09 15:08:12 +0000293void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000294ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000295 ExternalSource.reset(Source.take());
296}
297
Chris Lattner4eb445d2007-01-26 01:27:23 +0000298void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000299 llvm::errs() << "\n*** AST Context Stats:\n";
300 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000301
Douglas Gregora30d0462009-05-26 14:40:08 +0000302 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000303#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000304#define ABSTRACT_TYPE(Name, Parent)
305#include "clang/AST/TypeNodes.def"
306 0 // Extra
307 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000308
Chris Lattner4eb445d2007-01-26 01:27:23 +0000309 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
310 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000311 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000312 }
313
Douglas Gregora30d0462009-05-26 14:40:08 +0000314 unsigned Idx = 0;
315 unsigned TotalBytes = 0;
316#define TYPE(Name, Parent) \
317 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000318 llvm::errs() << " " << counts[Idx] << " " << #Name \
319 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000320 TotalBytes += counts[Idx] * sizeof(Name##Type); \
321 ++Idx;
322#define ABSTRACT_TYPE(Name, Parent)
323#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000324
Chandler Carruth3c147a72011-07-04 05:32:14 +0000325 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
326
Douglas Gregor7454c562010-07-02 20:37:36 +0000327 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000328 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
329 << NumImplicitDefaultConstructors
330 << " implicit default constructors created\n";
331 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
332 << NumImplicitCopyConstructors
333 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000334 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000335 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
336 << NumImplicitMoveConstructors
337 << " implicit move constructors created\n";
338 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
339 << NumImplicitCopyAssignmentOperators
340 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000341 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000342 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
343 << NumImplicitMoveAssignmentOperators
344 << " implicit move assignment operators created\n";
345 llvm::errs() << NumImplicitDestructorsDeclared << "/"
346 << NumImplicitDestructors
347 << " implicit destructors created\n";
348
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000349 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000350 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000351 ExternalSource->PrintStats();
352 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000353
Douglas Gregor5b11d492010-07-25 17:53:33 +0000354 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000355}
356
Douglas Gregor801c99d2011-08-12 06:49:56 +0000357TypedefDecl *ASTContext::getInt128Decl() const {
358 if (!Int128Decl) {
359 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
360 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
361 getTranslationUnitDecl(),
362 SourceLocation(),
363 SourceLocation(),
364 &Idents.get("__int128_t"),
365 TInfo);
366 }
367
368 return Int128Decl;
369}
370
371TypedefDecl *ASTContext::getUInt128Decl() const {
372 if (!UInt128Decl) {
373 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
374 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
375 getTranslationUnitDecl(),
376 SourceLocation(),
377 SourceLocation(),
378 &Idents.get("__uint128_t"),
379 TInfo);
380 }
381
382 return UInt128Decl;
383}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000384
John McCall48f2d582009-10-23 23:03:21 +0000385void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000386 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000387 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000388 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000389}
390
Douglas Gregore8bbc122011-09-02 00:18:52 +0000391void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
392 assert((!this->Target || this->Target == &Target) &&
393 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000394 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000395
Douglas Gregore8bbc122011-09-02 00:18:52 +0000396 this->Target = &Target;
397
398 ABI.reset(createCXXABI(Target));
399 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
400
Chris Lattner970e54e2006-11-12 00:37:36 +0000401 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000402 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000403
Chris Lattner970e54e2006-11-12 00:37:36 +0000404 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000405 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000406 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000407 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000408 InitBuiltinType(CharTy, BuiltinType::Char_S);
409 else
410 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000411 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000412 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
413 InitBuiltinType(ShortTy, BuiltinType::Short);
414 InitBuiltinType(IntTy, BuiltinType::Int);
415 InitBuiltinType(LongTy, BuiltinType::Long);
416 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000417
Chris Lattner970e54e2006-11-12 00:37:36 +0000418 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000419 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
420 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
421 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
422 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
423 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000424
Chris Lattner970e54e2006-11-12 00:37:36 +0000425 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000426 InitBuiltinType(FloatTy, BuiltinType::Float);
427 InitBuiltinType(DoubleTy, BuiltinType::Double);
428 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000429
Chris Lattnerf122cef2009-04-30 02:43:43 +0000430 // GNU extension, 128-bit integers.
431 InitBuiltinType(Int128Ty, BuiltinType::Int128);
432 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
433
Chris Lattnerad3467e2010-12-25 23:25:43 +0000434 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000435 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000436 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
437 else // -fshort-wchar makes wchar_t be unsigned.
438 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
439 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000440 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000441
James Molloy36365542012-05-04 10:55:22 +0000442 WIntTy = getFromTargetType(Target.getWIntType());
443
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000444 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
445 InitBuiltinType(Char16Ty, BuiltinType::Char16);
446 else // C99
447 Char16Ty = getFromTargetType(Target.getChar16Type());
448
449 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
450 InitBuiltinType(Char32Ty, BuiltinType::Char32);
451 else // C99
452 Char32Ty = getFromTargetType(Target.getChar32Type());
453
Douglas Gregor4619e432008-12-05 23:32:09 +0000454 // Placeholder type for type-dependent expressions whose type is
455 // completely unknown. No code should ever check a type against
456 // DependentTy and users should never see it; however, it is here to
457 // help diagnose failures to properly check for type-dependent
458 // expressions.
459 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000460
John McCall36e7fe32010-10-12 00:20:44 +0000461 // Placeholder type for functions.
462 InitBuiltinType(OverloadTy, BuiltinType::Overload);
463
John McCall0009fcc2011-04-26 20:42:42 +0000464 // Placeholder type for bound members.
465 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
466
John McCall526ab472011-10-25 17:37:35 +0000467 // Placeholder type for pseudo-objects.
468 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
469
John McCall31996342011-04-07 08:22:57 +0000470 // "any" type; useful for debugger-like clients.
471 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
472
John McCall8a6b59a2011-10-17 18:09:15 +0000473 // Placeholder type for unbridged ARC casts.
474 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
475
Chris Lattner970e54e2006-11-12 00:37:36 +0000476 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000477 FloatComplexTy = getComplexType(FloatTy);
478 DoubleComplexTy = getComplexType(DoubleTy);
479 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480
Steve Naroff66e9f332007-10-15 14:41:52 +0000481 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000482
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000483 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000484 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
485 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000486 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000487
488 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +0000489 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
490 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000491
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000492 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000493
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000494 // void * type
495 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000496
497 // nullptr type (C++0x 2.14.7)
498 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000499
500 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
501 InitBuiltinType(HalfTy, BuiltinType::Half);
Chris Lattner970e54e2006-11-12 00:37:36 +0000502}
503
David Blaikie9c902b52011-09-25 23:23:43 +0000504DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000505 return SourceMgr.getDiagnostics();
506}
507
Douglas Gregor561eceb2010-08-30 16:49:28 +0000508AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
509 AttrVec *&Result = DeclAttrs[D];
510 if (!Result) {
511 void *Mem = Allocate(sizeof(AttrVec));
512 Result = new (Mem) AttrVec;
513 }
514
515 return *Result;
516}
517
518/// \brief Erase the attributes corresponding to the given declaration.
519void ASTContext::eraseDeclAttrs(const Decl *D) {
520 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
521 if (Pos != DeclAttrs.end()) {
522 Pos->second->~AttrVec();
523 DeclAttrs.erase(Pos);
524 }
525}
526
Douglas Gregor86d142a2009-10-08 07:24:58 +0000527MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000528ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000529 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000530 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000531 = InstantiatedFromStaticDataMember.find(Var);
532 if (Pos == InstantiatedFromStaticDataMember.end())
533 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000534
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000535 return Pos->second;
536}
537
Mike Stump11289f42009-09-09 15:08:12 +0000538void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000539ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000540 TemplateSpecializationKind TSK,
541 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000542 assert(Inst->isStaticDataMember() && "Not a static data member");
543 assert(Tmpl->isStaticDataMember() && "Not a static data member");
544 assert(!InstantiatedFromStaticDataMember[Inst] &&
545 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000546 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000547 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000548}
549
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000550FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
551 const FunctionDecl *FD){
552 assert(FD && "Specialization is 0");
553 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000554 = ClassScopeSpecializationPattern.find(FD);
555 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000556 return 0;
557
558 return Pos->second;
559}
560
561void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
562 FunctionDecl *Pattern) {
563 assert(FD && "Specialization is 0");
564 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000565 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000566}
567
John McCalle61f2ba2009-11-18 02:36:19 +0000568NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000569ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000570 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000571 = InstantiatedFromUsingDecl.find(UUD);
572 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000573 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000574
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000575 return Pos->second;
576}
577
578void
John McCallb96ec562009-12-04 22:46:56 +0000579ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
580 assert((isa<UsingDecl>(Pattern) ||
581 isa<UnresolvedUsingValueDecl>(Pattern) ||
582 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
583 "pattern decl is not a using decl");
584 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
585 InstantiatedFromUsingDecl[Inst] = Pattern;
586}
587
588UsingShadowDecl *
589ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
590 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
591 = InstantiatedFromUsingShadowDecl.find(Inst);
592 if (Pos == InstantiatedFromUsingShadowDecl.end())
593 return 0;
594
595 return Pos->second;
596}
597
598void
599ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
600 UsingShadowDecl *Pattern) {
601 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
602 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000603}
604
Anders Carlsson5da84842009-09-01 04:26:58 +0000605FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
606 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
607 = InstantiatedFromUnnamedFieldDecl.find(Field);
608 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
609 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000610
Anders Carlsson5da84842009-09-01 04:26:58 +0000611 return Pos->second;
612}
613
614void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
615 FieldDecl *Tmpl) {
616 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
617 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
618 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
619 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000620
Anders Carlsson5da84842009-09-01 04:26:58 +0000621 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
622}
623
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000624bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
625 const FieldDecl *LastFD) const {
626 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000627 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000628}
629
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000630bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
631 const FieldDecl *LastFD) const {
632 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000633 FD->getBitWidthValue(*this) == 0 &&
634 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000635}
636
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000637bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
638 const FieldDecl *LastFD) const {
639 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000640 FD->getBitWidthValue(*this) &&
641 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000642}
643
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000644bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000645 const FieldDecl *LastFD) const {
646 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000647 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000648}
649
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000650bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000651 const FieldDecl *LastFD) const {
652 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000653 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000654}
655
Douglas Gregor832940b2010-03-02 23:58:15 +0000656ASTContext::overridden_cxx_method_iterator
657ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
658 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
659 = OverriddenMethods.find(Method);
660 if (Pos == OverriddenMethods.end())
661 return 0;
662
663 return Pos->second.begin();
664}
665
666ASTContext::overridden_cxx_method_iterator
667ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
668 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
669 = OverriddenMethods.find(Method);
670 if (Pos == OverriddenMethods.end())
671 return 0;
672
673 return Pos->second.end();
674}
675
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000676unsigned
677ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
678 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
679 = OverriddenMethods.find(Method);
680 if (Pos == OverriddenMethods.end())
681 return 0;
682
683 return Pos->second.size();
684}
685
Douglas Gregor832940b2010-03-02 23:58:15 +0000686void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
687 const CXXMethodDecl *Overridden) {
688 OverriddenMethods[Method].push_back(Overridden);
689}
690
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000691void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
692 assert(!Import->NextLocalImport && "Import declaration already in the chain");
693 assert(!Import->isFromASTFile() && "Non-local import declaration");
694 if (!FirstLocalImport) {
695 FirstLocalImport = Import;
696 LastLocalImport = Import;
697 return;
698 }
699
700 LastLocalImport->NextLocalImport = Import;
701 LastLocalImport = Import;
702}
703
Chris Lattner53cfe802007-07-18 17:52:12 +0000704//===----------------------------------------------------------------------===//
705// Type Sizing and Analysis
706//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000707
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000708/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
709/// scalar floating point type.
710const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000711 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000712 assert(BT && "Not a floating point type!");
713 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000714 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000715 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000716 case BuiltinType::Float: return Target->getFloatFormat();
717 case BuiltinType::Double: return Target->getDoubleFormat();
718 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000719 }
720}
721
Ken Dyck160146e2010-01-27 17:10:57 +0000722/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000723/// specified decl. Note that bitfields do not have a valid alignment, so
724/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000725/// If @p RefAsPointee, references are treated like their underlying type
726/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000727CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000728 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000729
John McCall94268702010-10-08 18:24:19 +0000730 bool UseAlignAttrOnly = false;
731 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
732 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000733
John McCall94268702010-10-08 18:24:19 +0000734 // __attribute__((aligned)) can increase or decrease alignment
735 // *except* on a struct or struct member, where it only increases
736 // alignment unless 'packed' is also specified.
737 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000738 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000739 // ignore that possibility; Sema should diagnose it.
740 if (isa<FieldDecl>(D)) {
741 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
742 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
743 } else {
744 UseAlignAttrOnly = true;
745 }
746 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000747 else if (isa<FieldDecl>(D))
748 UseAlignAttrOnly =
749 D->hasAttr<PackedAttr>() ||
750 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000751
John McCall4e819612011-01-20 07:57:12 +0000752 // If we're using the align attribute only, just ignore everything
753 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000754 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000755 // do nothing
756
John McCall94268702010-10-08 18:24:19 +0000757 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000758 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000759 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000760 if (RefAsPointee)
761 T = RT->getPointeeType();
762 else
763 T = getPointerType(RT->getPointeeType());
764 }
765 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000766 // Adjust alignments of declarations with array type by the
767 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000768 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000769 const ArrayType *arrayType;
770 if (MinWidth && (arrayType = getAsArrayType(T))) {
771 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000772 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000773 else if (isa<ConstantArrayType>(arrayType) &&
774 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000775 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000776
John McCall33ddac02011-01-19 10:06:00 +0000777 // Walk through any array types while we're at it.
778 T = getBaseElementType(arrayType);
779 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000780 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000781 }
John McCall4e819612011-01-20 07:57:12 +0000782
783 // Fields can be subject to extra alignment constraints, like if
784 // the field is packed, the struct is packed, or the struct has a
785 // a max-field-alignment constraint (#pragma pack). So calculate
786 // the actual alignment of the field within the struct, and then
787 // (as we're expected to) constrain that by the alignment of the type.
788 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
789 // So calculate the alignment of the field.
790 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
791
792 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000793 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000794
795 // Use the GCD of that and the offset within the record.
796 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
797 if (offset > 0) {
798 // Alignment is always a power of 2, so the GCD will be a power of 2,
799 // which means we get to do this crazy thing instead of Euclid's.
800 uint64_t lowBitOfOffset = offset & (~offset + 1);
801 if (lowBitOfOffset < fieldAlign)
802 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
803 }
804
805 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000806 }
Chris Lattner68061312009-01-24 21:53:27 +0000807 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000808
Ken Dyckcc56c542011-01-15 18:38:59 +0000809 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000810}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000811
John McCall87fe5d52010-05-20 01:18:31 +0000812std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000813ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000814 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000815 return std::make_pair(toCharUnitsFromBits(Info.first),
816 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000817}
818
819std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000820ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000821 return getTypeInfoInChars(T.getTypePtr());
822}
823
Daniel Dunbarc6475872012-03-09 04:12:54 +0000824std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
825 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
826 if (it != MemoizedTypeInfo.end())
827 return it->second;
828
829 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
830 MemoizedTypeInfo.insert(std::make_pair(T, Info));
831 return Info;
832}
833
834/// getTypeInfoImpl - Return the size of the specified type, in bits. This
835/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000836///
837/// FIXME: Pointers into different addr spaces could have different sizes and
838/// alignment requirements: getPointerInfo should take an AddrSpace, this
839/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000840std::pair<uint64_t, unsigned>
Daniel Dunbarc6475872012-03-09 04:12:54 +0000841ASTContext::getTypeInfoImpl(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000842 uint64_t Width=0;
843 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000844 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000845#define TYPE(Class, Base)
846#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000847#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000848#define DEPENDENT_TYPE(Class, Base) case Type::Class:
849#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000850 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000851
Chris Lattner355332d2007-07-13 22:27:08 +0000852 case Type::FunctionNoProto:
853 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000854 // GCC extension: alignof(function) = 32 bits
855 Width = 0;
856 Align = 32;
857 break;
858
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000859 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000860 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000861 Width = 0;
862 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
863 break;
864
Steve Naroff5c131802007-08-30 01:06:46 +0000865 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000866 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000867
Chris Lattner37e05872008-03-05 18:54:05 +0000868 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000869 uint64_t Size = CAT->getSize().getZExtValue();
Daniel Dunbarc6475872012-03-09 04:12:54 +0000870 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
871 "Overflow in array type bit size evaluation");
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000872 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000873 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000874 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000875 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000876 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000877 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000878 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000879 const VectorType *VT = cast<VectorType>(T);
880 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
881 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000882 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000883 // If the alignment is not a power of 2, round up to the next power of 2.
884 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000885 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000886 Align = llvm::NextPowerOf2(Align);
887 Width = llvm::RoundUpToAlignment(Width, Align);
888 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000889 break;
890 }
Chris Lattner647fb222007-07-18 18:26:58 +0000891
Chris Lattner7570e9c2008-03-08 08:52:55 +0000892 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000893 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000894 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000895 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000896 // GCC extension: alignof(void) = 8 bits.
897 Width = 0;
898 Align = 8;
899 break;
900
Chris Lattner6a4f7452007-12-19 19:23:28 +0000901 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000902 Width = Target->getBoolWidth();
903 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000904 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000905 case BuiltinType::Char_S:
906 case BuiltinType::Char_U:
907 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000908 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000909 Width = Target->getCharWidth();
910 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000911 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000912 case BuiltinType::WChar_S:
913 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000914 Width = Target->getWCharWidth();
915 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000916 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000917 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000918 Width = Target->getChar16Width();
919 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000920 break;
921 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000922 Width = Target->getChar32Width();
923 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000924 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000925 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000926 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000927 Width = Target->getShortWidth();
928 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000929 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000930 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000931 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000932 Width = Target->getIntWidth();
933 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000934 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000935 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000936 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000937 Width = Target->getLongWidth();
938 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000939 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000940 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000941 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000942 Width = Target->getLongLongWidth();
943 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000944 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000945 case BuiltinType::Int128:
946 case BuiltinType::UInt128:
947 Width = 128;
948 Align = 128; // int128_t is 128-bit aligned on all targets.
949 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000950 case BuiltinType::Half:
951 Width = Target->getHalfWidth();
952 Align = Target->getHalfAlign();
953 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000954 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000955 Width = Target->getFloatWidth();
956 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000957 break;
958 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000959 Width = Target->getDoubleWidth();
960 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000961 break;
962 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000963 Width = Target->getLongDoubleWidth();
964 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000965 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000966 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000967 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
968 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000969 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000970 case BuiltinType::ObjCId:
971 case BuiltinType::ObjCClass:
972 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000973 Width = Target->getPointerWidth(0);
974 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000975 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000976 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000977 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000978 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000979 Width = Target->getPointerWidth(0);
980 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000981 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000982 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000983 unsigned AS = getTargetAddressSpace(
984 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000985 Width = Target->getPointerWidth(AS);
986 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +0000987 break;
988 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000989 case Type::LValueReference:
990 case Type::RValueReference: {
991 // alignof and sizeof should never enter this code path here, so we go
992 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000993 unsigned AS = getTargetAddressSpace(
994 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000995 Width = Target->getPointerWidth(AS);
996 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000997 break;
998 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000999 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001000 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001001 Width = Target->getPointerWidth(AS);
1002 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001003 break;
1004 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001005 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001006 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001007 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +00001008 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +00001009 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001010 Align = PtrDiffInfo.second;
1011 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001012 }
Chris Lattner647fb222007-07-18 18:26:58 +00001013 case Type::Complex: {
1014 // Complex types have the same alignment as their elements, but twice the
1015 // size.
Mike Stump11289f42009-09-09 15:08:12 +00001016 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001017 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001018 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001019 Align = EltInfo.second;
1020 break;
1021 }
John McCall8b07ec22010-05-15 11:32:37 +00001022 case Type::ObjCObject:
1023 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001024 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001025 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001026 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001027 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001028 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001029 break;
1030 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001031 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001032 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001033 const TagType *TT = cast<TagType>(T);
1034
1035 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001036 Width = 8;
1037 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001038 break;
1039 }
Mike Stump11289f42009-09-09 15:08:12 +00001040
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001041 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001042 return getTypeInfo(ET->getDecl()->getIntegerType());
1043
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001044 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001045 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001046 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001047 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001048 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001049 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001050
Chris Lattner63d2b362009-10-22 05:17:15 +00001051 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001052 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1053 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001054
Richard Smith30482bc2011-02-20 03:19:35 +00001055 case Type::Auto: {
1056 const AutoType *A = cast<AutoType>(T);
1057 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001058 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001059 }
1060
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001061 case Type::Paren:
1062 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1063
Douglas Gregoref462e62009-04-30 17:32:17 +00001064 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001065 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001066 std::pair<uint64_t, unsigned> Info
1067 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001068 // If the typedef has an aligned attribute on it, it overrides any computed
1069 // alignment we have. This violates the GCC documentation (which says that
1070 // attribute(aligned) can only round up) but matches its implementation.
1071 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1072 Align = AttrAlign;
1073 else
1074 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001075 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001076 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001077 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001078
1079 case Type::TypeOfExpr:
1080 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1081 .getTypePtr());
1082
1083 case Type::TypeOf:
1084 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1085
Anders Carlsson81df7b82009-06-24 19:06:50 +00001086 case Type::Decltype:
1087 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1088 .getTypePtr());
1089
Alexis Hunte852b102011-05-24 22:41:36 +00001090 case Type::UnaryTransform:
1091 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1092
Abramo Bagnara6150c882010-05-11 21:36:43 +00001093 case Type::Elaborated:
1094 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001095
John McCall81904512011-01-06 01:58:22 +00001096 case Type::Attributed:
1097 return getTypeInfo(
1098 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1099
Richard Smith3f1b5d02011-05-05 21:57:07 +00001100 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001101 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001102 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001103 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1104 // A type alias template specialization may refer to a typedef with the
1105 // aligned attribute on it.
1106 if (TST->isTypeAlias())
1107 return getTypeInfo(TST->getAliasedType().getTypePtr());
1108 else
1109 return getTypeInfo(getCanonicalType(T));
1110 }
1111
Eli Friedman0dfb8892011-10-06 23:00:33 +00001112 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001113 std::pair<uint64_t, unsigned> Info
1114 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1115 Width = Info.first;
1116 Align = Info.second;
1117 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1118 llvm::isPowerOf2_64(Width)) {
1119 // We can potentially perform lock-free atomic operations for this
1120 // type; promote the alignment appropriately.
1121 // FIXME: We could potentially promote the width here as well...
1122 // is that worthwhile? (Non-struct atomic types generally have
1123 // power-of-two size anyway, but structs might not. Requires a bit
1124 // of implementation work to make sure we zero out the extra bits.)
1125 Align = static_cast<unsigned>(Width);
1126 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001127 }
1128
Douglas Gregoref462e62009-04-30 17:32:17 +00001129 }
Mike Stump11289f42009-09-09 15:08:12 +00001130
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001131 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001132 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001133}
1134
Ken Dyckcc56c542011-01-15 18:38:59 +00001135/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1136CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1137 return CharUnits::fromQuantity(BitSize / getCharWidth());
1138}
1139
Ken Dyckb0fcc592011-02-11 01:54:29 +00001140/// toBits - Convert a size in characters to a size in characters.
1141int64_t ASTContext::toBits(CharUnits CharSize) const {
1142 return CharSize.getQuantity() * getCharWidth();
1143}
1144
Ken Dyck8c89d592009-12-22 14:23:30 +00001145/// getTypeSizeInChars - Return the size of the specified type, in characters.
1146/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001147CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001148 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001149}
Jay Foad39c79802011-01-12 09:06:06 +00001150CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001151 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001152}
1153
Ken Dycka6046ab2010-01-26 17:25:18 +00001154/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001155/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001156CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001157 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001158}
Jay Foad39c79802011-01-12 09:06:06 +00001159CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001160 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001161}
1162
Chris Lattnera3402cd2009-01-27 18:08:34 +00001163/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1164/// type for the current target in bits. This can be different than the ABI
1165/// alignment in cases where it is beneficial for performance to overalign
1166/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001167unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001168 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001169
1170 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001171 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001172 T = CT->getElementType().getTypePtr();
1173 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00001174 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1175 T->isSpecificBuiltinType(BuiltinType::ULongLong))
Eli Friedman7ab09572009-05-25 21:27:19 +00001176 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1177
Chris Lattnera3402cd2009-01-27 18:08:34 +00001178 return ABIAlign;
1179}
1180
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001181/// DeepCollectObjCIvars -
1182/// This routine first collects all declared, but not synthesized, ivars in
1183/// super class and then collects all ivars, including those synthesized for
1184/// current class. This routine is used for implementation of current class
1185/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001186///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001187void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1188 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001189 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001190 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1191 DeepCollectObjCIvars(SuperClass, false, Ivars);
1192 if (!leafClass) {
1193 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1194 E = OI->ivar_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001195 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001196 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001197 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001198 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001199 Iv= Iv->getNextIvar())
1200 Ivars.push_back(Iv);
1201 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001202}
1203
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001204/// CollectInheritedProtocols - Collect all protocols in current class and
1205/// those inherited by it.
1206void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001207 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001208 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001209 // We can use protocol_iterator here instead of
1210 // all_referenced_protocol_iterator since we are walking all categories.
1211 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1212 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001213 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001214 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001215 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001216 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001217 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001218 CollectInheritedProtocols(*P, Protocols);
1219 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001220 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001221
1222 // Categories of this Interface.
1223 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1224 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1225 CollectInheritedProtocols(CDeclChain, Protocols);
1226 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1227 while (SD) {
1228 CollectInheritedProtocols(SD, Protocols);
1229 SD = SD->getSuperClass();
1230 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001231 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001232 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001233 PE = OC->protocol_end(); P != PE; ++P) {
1234 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001235 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001236 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1237 PE = Proto->protocol_end(); P != PE; ++P)
1238 CollectInheritedProtocols(*P, Protocols);
1239 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001240 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001241 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1242 PE = OP->protocol_end(); P != PE; ++P) {
1243 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001244 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001245 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1246 PE = Proto->protocol_end(); P != PE; ++P)
1247 CollectInheritedProtocols(*P, Protocols);
1248 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001249 }
1250}
1251
Jay Foad39c79802011-01-12 09:06:06 +00001252unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001253 unsigned count = 0;
1254 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001255 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1256 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001257 count += CDecl->ivar_size();
1258
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001259 // Count ivar defined in this class's implementation. This
1260 // includes synthesized ivars.
1261 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001262 count += ImplDecl->ivar_size();
1263
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001264 return count;
1265}
1266
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001267bool ASTContext::isSentinelNullExpr(const Expr *E) {
1268 if (!E)
1269 return false;
1270
1271 // nullptr_t is always treated as null.
1272 if (E->getType()->isNullPtrType()) return true;
1273
1274 if (E->getType()->isAnyPointerType() &&
1275 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1276 Expr::NPC_ValueDependentIsNull))
1277 return true;
1278
1279 // Unfortunately, __null has type 'int'.
1280 if (isa<GNUNullExpr>(E)) return true;
1281
1282 return false;
1283}
1284
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001285/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1286ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1287 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1288 I = ObjCImpls.find(D);
1289 if (I != ObjCImpls.end())
1290 return cast<ObjCImplementationDecl>(I->second);
1291 return 0;
1292}
1293/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1294ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1295 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1296 I = ObjCImpls.find(D);
1297 if (I != ObjCImpls.end())
1298 return cast<ObjCCategoryImplDecl>(I->second);
1299 return 0;
1300}
1301
1302/// \brief Set the implementation of ObjCInterfaceDecl.
1303void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1304 ObjCImplementationDecl *ImplD) {
1305 assert(IFaceD && ImplD && "Passed null params");
1306 ObjCImpls[IFaceD] = ImplD;
1307}
1308/// \brief Set the implementation of ObjCCategoryDecl.
1309void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1310 ObjCCategoryImplDecl *ImplD) {
1311 assert(CatD && ImplD && "Passed null params");
1312 ObjCImpls[CatD] = ImplD;
1313}
1314
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001315ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1316 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1317 return ID;
1318 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1319 return CD->getClassInterface();
1320 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1321 return IMD->getClassInterface();
1322
1323 return 0;
1324}
1325
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001326/// \brief Get the copy initialization expression of VarDecl,or NULL if
1327/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001328Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001329 assert(VD && "Passed null params");
1330 assert(VD->hasAttr<BlocksAttr>() &&
1331 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001332 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001333 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001334 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1335}
1336
1337/// \brief Set the copy inialization expression of a block var decl.
1338void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1339 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001340 assert(VD->hasAttr<BlocksAttr>() &&
1341 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001342 BlockVarCopyInits[VD] = Init;
1343}
1344
John McCallbcd03502009-12-07 02:54:59 +00001345/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001346///
John McCallbcd03502009-12-07 02:54:59 +00001347/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001348/// the TypeLoc wrappers.
1349///
1350/// \param T the type that will be the basis for type source info. This type
1351/// should refer to how the declarator was written in source code, not to
1352/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001353TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001354 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001355 if (!DataSize)
1356 DataSize = TypeLoc::getFullDataSizeForType(T);
1357 else
1358 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001359 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001360
John McCallbcd03502009-12-07 02:54:59 +00001361 TypeSourceInfo *TInfo =
1362 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1363 new (TInfo) TypeSourceInfo(T);
1364 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001365}
1366
John McCallbcd03502009-12-07 02:54:59 +00001367TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001368 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001369 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001370 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001371 return DI;
1372}
1373
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001374const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001375ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001376 return getObjCLayout(D, 0);
1377}
1378
1379const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001380ASTContext::getASTObjCImplementationLayout(
1381 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001382 return getObjCLayout(D->getClassInterface(), D);
1383}
1384
Chris Lattner983a8bb2007-07-13 22:13:22 +00001385//===----------------------------------------------------------------------===//
1386// Type creation/memoization methods
1387//===----------------------------------------------------------------------===//
1388
Jay Foad39c79802011-01-12 09:06:06 +00001389QualType
John McCall33ddac02011-01-19 10:06:00 +00001390ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1391 unsigned fastQuals = quals.getFastQualifiers();
1392 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001393
1394 // Check if we've already instantiated this type.
1395 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001396 ExtQuals::Profile(ID, baseType, quals);
1397 void *insertPos = 0;
1398 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1399 assert(eq->getQualifiers() == quals);
1400 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001401 }
1402
John McCall33ddac02011-01-19 10:06:00 +00001403 // If the base type is not canonical, make the appropriate canonical type.
1404 QualType canon;
1405 if (!baseType->isCanonicalUnqualified()) {
1406 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001407 canonSplit.Quals.addConsistentQualifiers(quals);
1408 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001409
1410 // Re-find the insert position.
1411 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1412 }
1413
1414 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1415 ExtQualNodes.InsertNode(eq, insertPos);
1416 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001417}
1418
Jay Foad39c79802011-01-12 09:06:06 +00001419QualType
1420ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001421 QualType CanT = getCanonicalType(T);
1422 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001423 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001424
John McCall8ccfcb52009-09-24 19:53:00 +00001425 // If we are composing extended qualifiers together, merge together
1426 // into one ExtQuals node.
1427 QualifierCollector Quals;
1428 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001429
John McCall8ccfcb52009-09-24 19:53:00 +00001430 // If this type already has an address space specified, it cannot get
1431 // another one.
1432 assert(!Quals.hasAddressSpace() &&
1433 "Type cannot be in multiple addr spaces!");
1434 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001435
John McCall8ccfcb52009-09-24 19:53:00 +00001436 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001437}
1438
Chris Lattnerd60183d2009-02-18 22:53:11 +00001439QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001440 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001441 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001442 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001443 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001444
John McCall53fa7142010-12-24 02:08:15 +00001445 if (const PointerType *ptr = T->getAs<PointerType>()) {
1446 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001447 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001448 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1449 return getPointerType(ResultType);
1450 }
1451 }
Mike Stump11289f42009-09-09 15:08:12 +00001452
John McCall8ccfcb52009-09-24 19:53:00 +00001453 // If we are composing extended qualifiers together, merge together
1454 // into one ExtQuals node.
1455 QualifierCollector Quals;
1456 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001457
John McCall8ccfcb52009-09-24 19:53:00 +00001458 // If this type already has an ObjCGC specified, it cannot get
1459 // another one.
1460 assert(!Quals.hasObjCGCAttr() &&
1461 "Type cannot have multiple ObjCGCs!");
1462 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001463
John McCall8ccfcb52009-09-24 19:53:00 +00001464 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001465}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001466
John McCall4f5019e2010-12-19 02:44:49 +00001467const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1468 FunctionType::ExtInfo Info) {
1469 if (T->getExtInfo() == Info)
1470 return T;
1471
1472 QualType Result;
1473 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1474 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1475 } else {
1476 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1477 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1478 EPI.ExtInfo = Info;
1479 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1480 FPT->getNumArgs(), EPI);
1481 }
1482
1483 return cast<FunctionType>(Result.getTypePtr());
1484}
1485
Chris Lattnerc6395932007-06-22 20:56:16 +00001486/// getComplexType - Return the uniqued reference to the type for a complex
1487/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001488QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001489 // Unique pointers, to guarantee there is only one pointer of a particular
1490 // structure.
1491 llvm::FoldingSetNodeID ID;
1492 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001493
Chris Lattnerc6395932007-06-22 20:56:16 +00001494 void *InsertPos = 0;
1495 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1496 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001497
Chris Lattnerc6395932007-06-22 20:56:16 +00001498 // If the pointee type isn't canonical, this won't be a canonical type either,
1499 // so fill in the canonical type field.
1500 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001501 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001502 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001503
Chris Lattnerc6395932007-06-22 20:56:16 +00001504 // Get the new insert position for the node we care about.
1505 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001506 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001507 }
John McCall90d1c2d2009-09-24 23:30:46 +00001508 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001509 Types.push_back(New);
1510 ComplexTypes.InsertNode(New, InsertPos);
1511 return QualType(New, 0);
1512}
1513
Chris Lattner970e54e2006-11-12 00:37:36 +00001514/// getPointerType - Return the uniqued reference to the type for a pointer to
1515/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001516QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001517 // Unique pointers, to guarantee there is only one pointer of a particular
1518 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001519 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001520 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001521
Chris Lattner67521df2007-01-27 01:29:36 +00001522 void *InsertPos = 0;
1523 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001524 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001525
Chris Lattner7ccecb92006-11-12 08:50:50 +00001526 // If the pointee type isn't canonical, this won't be a canonical type either,
1527 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001528 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001529 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001530 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001531
Chris Lattner67521df2007-01-27 01:29:36 +00001532 // Get the new insert position for the node we care about.
1533 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001534 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001535 }
John McCall90d1c2d2009-09-24 23:30:46 +00001536 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001537 Types.push_back(New);
1538 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001539 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001540}
1541
Mike Stump11289f42009-09-09 15:08:12 +00001542/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001543/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001544QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001545 assert(T->isFunctionType() && "block of function types only");
1546 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001547 // structure.
1548 llvm::FoldingSetNodeID ID;
1549 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001550
Steve Naroffec33ed92008-08-27 16:04:49 +00001551 void *InsertPos = 0;
1552 if (BlockPointerType *PT =
1553 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1554 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001555
1556 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001557 // type either so fill in the canonical type field.
1558 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001559 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001560 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001561
Steve Naroffec33ed92008-08-27 16:04:49 +00001562 // Get the new insert position for the node we care about.
1563 BlockPointerType *NewIP =
1564 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001565 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001566 }
John McCall90d1c2d2009-09-24 23:30:46 +00001567 BlockPointerType *New
1568 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001569 Types.push_back(New);
1570 BlockPointerTypes.InsertNode(New, InsertPos);
1571 return QualType(New, 0);
1572}
1573
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001574/// getLValueReferenceType - Return the uniqued reference to the type for an
1575/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001576QualType
1577ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001578 assert(getCanonicalType(T) != OverloadTy &&
1579 "Unresolved overloaded function type");
1580
Bill Wendling3708c182007-05-27 10:15:43 +00001581 // Unique pointers, to guarantee there is only one pointer of a particular
1582 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001583 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001584 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001585
1586 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001587 if (LValueReferenceType *RT =
1588 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001589 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001590
John McCallfc93cf92009-10-22 22:37:11 +00001591 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1592
Bill Wendling3708c182007-05-27 10:15:43 +00001593 // If the referencee type isn't canonical, this won't be a canonical type
1594 // either, so fill in the canonical type field.
1595 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001596 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1597 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1598 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001599
Bill Wendling3708c182007-05-27 10:15:43 +00001600 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001601 LValueReferenceType *NewIP =
1602 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001603 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001604 }
1605
John McCall90d1c2d2009-09-24 23:30:46 +00001606 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001607 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1608 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001609 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001610 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001611
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001612 return QualType(New, 0);
1613}
1614
1615/// getRValueReferenceType - Return the uniqued reference to the type for an
1616/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001617QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001618 // Unique pointers, to guarantee there is only one pointer of a particular
1619 // structure.
1620 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001621 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001622
1623 void *InsertPos = 0;
1624 if (RValueReferenceType *RT =
1625 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1626 return QualType(RT, 0);
1627
John McCallfc93cf92009-10-22 22:37:11 +00001628 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1629
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001630 // If the referencee type isn't canonical, this won't be a canonical type
1631 // either, so fill in the canonical type field.
1632 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001633 if (InnerRef || !T.isCanonical()) {
1634 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1635 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001636
1637 // Get the new insert position for the node we care about.
1638 RValueReferenceType *NewIP =
1639 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001640 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001641 }
1642
John McCall90d1c2d2009-09-24 23:30:46 +00001643 RValueReferenceType *New
1644 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001645 Types.push_back(New);
1646 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001647 return QualType(New, 0);
1648}
1649
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001650/// getMemberPointerType - Return the uniqued reference to the type for a
1651/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001652QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001653 // Unique pointers, to guarantee there is only one pointer of a particular
1654 // structure.
1655 llvm::FoldingSetNodeID ID;
1656 MemberPointerType::Profile(ID, T, Cls);
1657
1658 void *InsertPos = 0;
1659 if (MemberPointerType *PT =
1660 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1661 return QualType(PT, 0);
1662
1663 // If the pointee or class type isn't canonical, this won't be a canonical
1664 // type either, so fill in the canonical type field.
1665 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001666 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001667 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1668
1669 // Get the new insert position for the node we care about.
1670 MemberPointerType *NewIP =
1671 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001672 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001673 }
John McCall90d1c2d2009-09-24 23:30:46 +00001674 MemberPointerType *New
1675 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001676 Types.push_back(New);
1677 MemberPointerTypes.InsertNode(New, InsertPos);
1678 return QualType(New, 0);
1679}
1680
Mike Stump11289f42009-09-09 15:08:12 +00001681/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001682/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001683QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001684 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001685 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001686 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001687 assert((EltTy->isDependentType() ||
1688 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001689 "Constant array of VLAs is illegal!");
1690
Chris Lattnere2df3f92009-05-13 04:12:56 +00001691 // Convert the array size into a canonical width matching the pointer size for
1692 // the target.
1693 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001694 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001695 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001696
Chris Lattner23b7eb62007-06-15 23:05:46 +00001697 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001698 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001699
Chris Lattner36f8e652007-01-27 08:31:04 +00001700 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001701 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001702 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001703 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001704
John McCall33ddac02011-01-19 10:06:00 +00001705 // If the element type isn't canonical or has qualifiers, this won't
1706 // be a canonical type either, so fill in the canonical type field.
1707 QualType Canon;
1708 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1709 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001710 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001711 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001712 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001713
Chris Lattner36f8e652007-01-27 08:31:04 +00001714 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001715 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001716 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001717 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001718 }
Mike Stump11289f42009-09-09 15:08:12 +00001719
John McCall90d1c2d2009-09-24 23:30:46 +00001720 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001721 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001722 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001723 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001724 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001725}
1726
John McCall06549462011-01-18 08:40:38 +00001727/// getVariableArrayDecayedType - Turns the given type, which may be
1728/// variably-modified, into the corresponding type with all the known
1729/// sizes replaced with [*].
1730QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1731 // Vastly most common case.
1732 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001733
John McCall06549462011-01-18 08:40:38 +00001734 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001735
John McCall06549462011-01-18 08:40:38 +00001736 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001737 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001738 switch (ty->getTypeClass()) {
1739#define TYPE(Class, Base)
1740#define ABSTRACT_TYPE(Class, Base)
1741#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1742#include "clang/AST/TypeNodes.def"
1743 llvm_unreachable("didn't desugar past all non-canonical types?");
1744
1745 // These types should never be variably-modified.
1746 case Type::Builtin:
1747 case Type::Complex:
1748 case Type::Vector:
1749 case Type::ExtVector:
1750 case Type::DependentSizedExtVector:
1751 case Type::ObjCObject:
1752 case Type::ObjCInterface:
1753 case Type::ObjCObjectPointer:
1754 case Type::Record:
1755 case Type::Enum:
1756 case Type::UnresolvedUsing:
1757 case Type::TypeOfExpr:
1758 case Type::TypeOf:
1759 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001760 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001761 case Type::DependentName:
1762 case Type::InjectedClassName:
1763 case Type::TemplateSpecialization:
1764 case Type::DependentTemplateSpecialization:
1765 case Type::TemplateTypeParm:
1766 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001767 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001768 case Type::PackExpansion:
1769 llvm_unreachable("type should never be variably-modified");
1770
1771 // These types can be variably-modified but should never need to
1772 // further decay.
1773 case Type::FunctionNoProto:
1774 case Type::FunctionProto:
1775 case Type::BlockPointer:
1776 case Type::MemberPointer:
1777 return type;
1778
1779 // These types can be variably-modified. All these modifications
1780 // preserve structure except as noted by comments.
1781 // TODO: if we ever care about optimizing VLAs, there are no-op
1782 // optimizations available here.
1783 case Type::Pointer:
1784 result = getPointerType(getVariableArrayDecayedType(
1785 cast<PointerType>(ty)->getPointeeType()));
1786 break;
1787
1788 case Type::LValueReference: {
1789 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1790 result = getLValueReferenceType(
1791 getVariableArrayDecayedType(lv->getPointeeType()),
1792 lv->isSpelledAsLValue());
1793 break;
1794 }
1795
1796 case Type::RValueReference: {
1797 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1798 result = getRValueReferenceType(
1799 getVariableArrayDecayedType(lv->getPointeeType()));
1800 break;
1801 }
1802
Eli Friedman0dfb8892011-10-06 23:00:33 +00001803 case Type::Atomic: {
1804 const AtomicType *at = cast<AtomicType>(ty);
1805 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1806 break;
1807 }
1808
John McCall06549462011-01-18 08:40:38 +00001809 case Type::ConstantArray: {
1810 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1811 result = getConstantArrayType(
1812 getVariableArrayDecayedType(cat->getElementType()),
1813 cat->getSize(),
1814 cat->getSizeModifier(),
1815 cat->getIndexTypeCVRQualifiers());
1816 break;
1817 }
1818
1819 case Type::DependentSizedArray: {
1820 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1821 result = getDependentSizedArrayType(
1822 getVariableArrayDecayedType(dat->getElementType()),
1823 dat->getSizeExpr(),
1824 dat->getSizeModifier(),
1825 dat->getIndexTypeCVRQualifiers(),
1826 dat->getBracketsRange());
1827 break;
1828 }
1829
1830 // Turn incomplete types into [*] types.
1831 case Type::IncompleteArray: {
1832 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1833 result = getVariableArrayType(
1834 getVariableArrayDecayedType(iat->getElementType()),
1835 /*size*/ 0,
1836 ArrayType::Normal,
1837 iat->getIndexTypeCVRQualifiers(),
1838 SourceRange());
1839 break;
1840 }
1841
1842 // Turn VLA types into [*] types.
1843 case Type::VariableArray: {
1844 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1845 result = getVariableArrayType(
1846 getVariableArrayDecayedType(vat->getElementType()),
1847 /*size*/ 0,
1848 ArrayType::Star,
1849 vat->getIndexTypeCVRQualifiers(),
1850 vat->getBracketsRange());
1851 break;
1852 }
1853 }
1854
1855 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00001856 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00001857}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001858
Steve Naroffcadebd02007-08-30 18:14:25 +00001859/// getVariableArrayType - Returns a non-unique reference to the type for a
1860/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001861QualType ASTContext::getVariableArrayType(QualType EltTy,
1862 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001863 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001864 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001865 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001866 // Since we don't unique expressions, it isn't possible to unique VLA's
1867 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001868 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001869
John McCall33ddac02011-01-19 10:06:00 +00001870 // Be sure to pull qualifiers off the element type.
1871 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1872 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001873 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001874 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00001875 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001876 }
1877
John McCall90d1c2d2009-09-24 23:30:46 +00001878 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001879 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001880
1881 VariableArrayTypes.push_back(New);
1882 Types.push_back(New);
1883 return QualType(New, 0);
1884}
1885
Douglas Gregor4619e432008-12-05 23:32:09 +00001886/// getDependentSizedArrayType - Returns a non-unique reference to
1887/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001888/// type.
John McCall33ddac02011-01-19 10:06:00 +00001889QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1890 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001891 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001892 unsigned elementTypeQuals,
1893 SourceRange brackets) const {
1894 assert((!numElements || numElements->isTypeDependent() ||
1895 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001896 "Size must be type- or value-dependent!");
1897
John McCall33ddac02011-01-19 10:06:00 +00001898 // Dependently-sized array types that do not have a specified number
1899 // of elements will have their sizes deduced from a dependent
1900 // initializer. We do no canonicalization here at all, which is okay
1901 // because they can't be used in most locations.
1902 if (!numElements) {
1903 DependentSizedArrayType *newType
1904 = new (*this, TypeAlignment)
1905 DependentSizedArrayType(*this, elementType, QualType(),
1906 numElements, ASM, elementTypeQuals,
1907 brackets);
1908 Types.push_back(newType);
1909 return QualType(newType, 0);
1910 }
1911
1912 // Otherwise, we actually build a new type every time, but we
1913 // also build a canonical type.
1914
1915 SplitQualType canonElementType = getCanonicalType(elementType).split();
1916
1917 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001918 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001919 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00001920 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001921 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001922
John McCall33ddac02011-01-19 10:06:00 +00001923 // Look for an existing type with these properties.
1924 DependentSizedArrayType *canonTy =
1925 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001926
John McCall33ddac02011-01-19 10:06:00 +00001927 // If we don't have one, build one.
1928 if (!canonTy) {
1929 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00001930 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001931 QualType(), numElements, ASM, elementTypeQuals,
1932 brackets);
1933 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1934 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001935 }
1936
John McCall33ddac02011-01-19 10:06:00 +00001937 // Apply qualifiers from the element type to the array.
1938 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00001939 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00001940
John McCall33ddac02011-01-19 10:06:00 +00001941 // If we didn't need extra canonicalization for the element type,
1942 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00001943 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00001944 return canon;
1945
1946 // Otherwise, we need to build a type which follows the spelling
1947 // of the element type.
1948 DependentSizedArrayType *sugaredType
1949 = new (*this, TypeAlignment)
1950 DependentSizedArrayType(*this, elementType, canon, numElements,
1951 ASM, elementTypeQuals, brackets);
1952 Types.push_back(sugaredType);
1953 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001954}
1955
John McCall33ddac02011-01-19 10:06:00 +00001956QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001957 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001958 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001959 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001960 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001961
John McCall33ddac02011-01-19 10:06:00 +00001962 void *insertPos = 0;
1963 if (IncompleteArrayType *iat =
1964 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1965 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001966
1967 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001968 // either, so fill in the canonical type field. We also have to pull
1969 // qualifiers off the element type.
1970 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001971
John McCall33ddac02011-01-19 10:06:00 +00001972 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1973 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00001974 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001975 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001976 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001977
1978 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001979 IncompleteArrayType *existing =
1980 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1981 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001982 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001983
John McCall33ddac02011-01-19 10:06:00 +00001984 IncompleteArrayType *newType = new (*this, TypeAlignment)
1985 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001986
John McCall33ddac02011-01-19 10:06:00 +00001987 IncompleteArrayTypes.InsertNode(newType, insertPos);
1988 Types.push_back(newType);
1989 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001990}
1991
Steve Naroff91fcddb2007-07-18 18:00:27 +00001992/// getVectorType - Return the unique reference to a vector type of
1993/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001994QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001995 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001996 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001997
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001998 // Check if we've already instantiated a vector of this type.
1999 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00002000 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00002001
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002002 void *InsertPos = 0;
2003 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2004 return QualType(VTP, 0);
2005
2006 // If the element type isn't canonical, this won't be a canonical type either,
2007 // so fill in the canonical type field.
2008 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00002009 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00002010 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00002011
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002012 // Get the new insert position for the node we care about.
2013 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002014 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002015 }
John McCall90d1c2d2009-09-24 23:30:46 +00002016 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00002017 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002018 VectorTypes.InsertNode(New, InsertPos);
2019 Types.push_back(New);
2020 return QualType(New, 0);
2021}
2022
Nate Begemance4d7fc2008-04-18 23:10:10 +00002023/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002024/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002025QualType
2026ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002027 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002028
Steve Naroff91fcddb2007-07-18 18:00:27 +00002029 // Check if we've already instantiated a vector of this type.
2030 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002031 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002032 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002033 void *InsertPos = 0;
2034 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2035 return QualType(VTP, 0);
2036
2037 // If the element type isn't canonical, this won't be a canonical type either,
2038 // so fill in the canonical type field.
2039 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002040 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002041 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002042
Steve Naroff91fcddb2007-07-18 18:00:27 +00002043 // Get the new insert position for the node we care about.
2044 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002045 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002046 }
John McCall90d1c2d2009-09-24 23:30:46 +00002047 ExtVectorType *New = new (*this, TypeAlignment)
2048 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002049 VectorTypes.InsertNode(New, InsertPos);
2050 Types.push_back(New);
2051 return QualType(New, 0);
2052}
2053
Jay Foad39c79802011-01-12 09:06:06 +00002054QualType
2055ASTContext::getDependentSizedExtVectorType(QualType vecType,
2056 Expr *SizeExpr,
2057 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002058 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002059 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002060 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002061
Douglas Gregor352169a2009-07-31 03:54:25 +00002062 void *InsertPos = 0;
2063 DependentSizedExtVectorType *Canon
2064 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2065 DependentSizedExtVectorType *New;
2066 if (Canon) {
2067 // We already have a canonical version of this array type; use it as
2068 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002069 New = new (*this, TypeAlignment)
2070 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2071 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002072 } else {
2073 QualType CanonVecTy = getCanonicalType(vecType);
2074 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002075 New = new (*this, TypeAlignment)
2076 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2077 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002078
2079 DependentSizedExtVectorType *CanonCheck
2080 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2081 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2082 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002083 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2084 } else {
2085 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2086 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002087 New = new (*this, TypeAlignment)
2088 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002089 }
2090 }
Mike Stump11289f42009-09-09 15:08:12 +00002091
Douglas Gregor758a8692009-06-17 21:51:59 +00002092 Types.push_back(New);
2093 return QualType(New, 0);
2094}
2095
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002096/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002097///
Jay Foad39c79802011-01-12 09:06:06 +00002098QualType
2099ASTContext::getFunctionNoProtoType(QualType ResultTy,
2100 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002101 const CallingConv DefaultCC = Info.getCC();
2102 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2103 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002104 // Unique functions, to guarantee there is only one function of a particular
2105 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002106 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002107 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002108
Chris Lattner47955de2007-01-27 08:37:20 +00002109 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002110 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002111 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002112 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002113
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002114 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002115 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002116 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002117 Canonical =
2118 getFunctionNoProtoType(getCanonicalType(ResultTy),
2119 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002120
Chris Lattner47955de2007-01-27 08:37:20 +00002121 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002122 FunctionNoProtoType *NewIP =
2123 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002124 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002125 }
Mike Stump11289f42009-09-09 15:08:12 +00002126
Roman Divacky65b88cd2011-03-01 17:40:53 +00002127 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002128 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002129 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002130 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002131 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002132 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002133}
2134
2135/// getFunctionType - Return a normal function type with a typed argument
2136/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002137QualType
2138ASTContext::getFunctionType(QualType ResultTy,
2139 const QualType *ArgArray, unsigned NumArgs,
2140 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002141 // Unique functions, to guarantee there is only one function of a particular
2142 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002143 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002144 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002145
2146 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002147 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002148 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002149 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002150
2151 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002152 bool isCanonical =
2153 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2154 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002155 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002156 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002157 isCanonical = false;
2158
Roman Divacky65b88cd2011-03-01 17:40:53 +00002159 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2160 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2161 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002162
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002163 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002164 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002165 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002166 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002167 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002168 CanonicalArgs.reserve(NumArgs);
2169 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002170 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002171
John McCalldb40c7f2010-12-14 08:05:40 +00002172 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002173 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002174 CanonicalEPI.ExceptionSpecType = EST_None;
2175 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002176 CanonicalEPI.ExtInfo
2177 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2178
Chris Lattner76a00cf2008-04-06 22:59:24 +00002179 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002180 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002181 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002182
Chris Lattnerfd4de792007-01-27 01:15:32 +00002183 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002184 FunctionProtoType *NewIP =
2185 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002186 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002187 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002188
John McCall31168b02011-06-15 23:02:42 +00002189 // FunctionProtoType objects are allocated with extra bytes after
2190 // them for three variable size arrays at the end:
2191 // - parameter types
2192 // - exception types
2193 // - consumed-arguments flags
2194 // Instead of the exception types, there could be a noexcept
2195 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002196 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002197 NumArgs * sizeof(QualType);
2198 if (EPI.ExceptionSpecType == EST_Dynamic)
2199 Size += EPI.NumExceptions * sizeof(QualType);
2200 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002201 Size += sizeof(Expr*);
Richard Smithf623c962012-04-17 00:58:00 +00002202 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00002203 Size += 2 * sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002204 }
John McCall31168b02011-06-15 23:02:42 +00002205 if (EPI.ConsumedArguments)
2206 Size += NumArgs * sizeof(bool);
2207
John McCalldb40c7f2010-12-14 08:05:40 +00002208 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002209 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2210 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002211 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002212 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002213 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002214 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002215}
Chris Lattneref51c202006-11-10 07:17:23 +00002216
John McCalle78aac42010-03-10 03:28:59 +00002217#ifndef NDEBUG
2218static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2219 if (!isa<CXXRecordDecl>(D)) return false;
2220 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2221 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2222 return true;
2223 if (RD->getDescribedClassTemplate() &&
2224 !isa<ClassTemplateSpecializationDecl>(RD))
2225 return true;
2226 return false;
2227}
2228#endif
2229
2230/// getInjectedClassNameType - Return the unique reference to the
2231/// injected class name type for the specified templated declaration.
2232QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002233 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002234 assert(NeedsInjectedClassNameType(Decl));
2235 if (Decl->TypeForDecl) {
2236 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002237 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002238 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2239 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2240 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2241 } else {
John McCall424cec92011-01-19 06:33:43 +00002242 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002243 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002244 Decl->TypeForDecl = newType;
2245 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002246 }
2247 return QualType(Decl->TypeForDecl, 0);
2248}
2249
Douglas Gregor83a586e2008-04-13 21:07:44 +00002250/// getTypeDeclType - Return the unique reference to the type for the
2251/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002252QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002253 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002254 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002255
Richard Smithdda56e42011-04-15 14:24:37 +00002256 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002257 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002258
John McCall96f0b5f2010-03-10 06:48:02 +00002259 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2260 "Template type parameter types are always available.");
2261
John McCall81e38502010-02-16 03:57:14 +00002262 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002263 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002264 "struct/union has previous declaration");
2265 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002266 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002267 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002268 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002269 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002270 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002271 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002272 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002273 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2274 Decl->TypeForDecl = newType;
2275 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002276 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002277 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002278
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002279 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002280}
2281
Chris Lattner32d920b2007-01-26 02:01:53 +00002282/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002283/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002284QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002285ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2286 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002287 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002288
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002289 if (Canonical.isNull())
2290 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002291 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002292 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002293 Decl->TypeForDecl = newType;
2294 Types.push_back(newType);
2295 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002296}
2297
Jay Foad39c79802011-01-12 09:06:06 +00002298QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002299 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2300
Douglas Gregorec9fd132012-01-14 16:38:05 +00002301 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002302 if (PrevDecl->TypeForDecl)
2303 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2304
John McCall424cec92011-01-19 06:33:43 +00002305 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2306 Decl->TypeForDecl = newType;
2307 Types.push_back(newType);
2308 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002309}
2310
Jay Foad39c79802011-01-12 09:06:06 +00002311QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002312 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2313
Douglas Gregorec9fd132012-01-14 16:38:05 +00002314 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002315 if (PrevDecl->TypeForDecl)
2316 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2317
John McCall424cec92011-01-19 06:33:43 +00002318 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2319 Decl->TypeForDecl = newType;
2320 Types.push_back(newType);
2321 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002322}
2323
John McCall81904512011-01-06 01:58:22 +00002324QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2325 QualType modifiedType,
2326 QualType equivalentType) {
2327 llvm::FoldingSetNodeID id;
2328 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2329
2330 void *insertPos = 0;
2331 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2332 if (type) return QualType(type, 0);
2333
2334 QualType canon = getCanonicalType(equivalentType);
2335 type = new (*this, TypeAlignment)
2336 AttributedType(canon, attrKind, modifiedType, equivalentType);
2337
2338 Types.push_back(type);
2339 AttributedTypes.InsertNode(type, insertPos);
2340
2341 return QualType(type, 0);
2342}
2343
2344
John McCallcebee162009-10-18 09:09:24 +00002345/// \brief Retrieve a substitution-result type.
2346QualType
2347ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002348 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002349 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002350 && "replacement types must always be canonical");
2351
2352 llvm::FoldingSetNodeID ID;
2353 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2354 void *InsertPos = 0;
2355 SubstTemplateTypeParmType *SubstParm
2356 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2357
2358 if (!SubstParm) {
2359 SubstParm = new (*this, TypeAlignment)
2360 SubstTemplateTypeParmType(Parm, Replacement);
2361 Types.push_back(SubstParm);
2362 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2363 }
2364
2365 return QualType(SubstParm, 0);
2366}
2367
Douglas Gregorada4b792011-01-14 02:55:32 +00002368/// \brief Retrieve a
2369QualType ASTContext::getSubstTemplateTypeParmPackType(
2370 const TemplateTypeParmType *Parm,
2371 const TemplateArgument &ArgPack) {
2372#ifndef NDEBUG
2373 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2374 PEnd = ArgPack.pack_end();
2375 P != PEnd; ++P) {
2376 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2377 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2378 }
2379#endif
2380
2381 llvm::FoldingSetNodeID ID;
2382 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2383 void *InsertPos = 0;
2384 if (SubstTemplateTypeParmPackType *SubstParm
2385 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2386 return QualType(SubstParm, 0);
2387
2388 QualType Canon;
2389 if (!Parm->isCanonicalUnqualified()) {
2390 Canon = getCanonicalType(QualType(Parm, 0));
2391 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2392 ArgPack);
2393 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2394 }
2395
2396 SubstTemplateTypeParmPackType *SubstParm
2397 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2398 ArgPack);
2399 Types.push_back(SubstParm);
2400 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2401 return QualType(SubstParm, 0);
2402}
2403
Douglas Gregoreff93e02009-02-05 23:33:38 +00002404/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002405/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002406/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002407QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002408 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002409 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002410 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002411 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002412 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002413 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002414 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2415
2416 if (TypeParm)
2417 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002418
Chandler Carruth08836322011-05-01 00:51:33 +00002419 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002420 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002421 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002422
2423 TemplateTypeParmType *TypeCheck
2424 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2425 assert(!TypeCheck && "Template type parameter canonical type broken");
2426 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002427 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002428 TypeParm = new (*this, TypeAlignment)
2429 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002430
2431 Types.push_back(TypeParm);
2432 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2433
2434 return QualType(TypeParm, 0);
2435}
2436
John McCalle78aac42010-03-10 03:28:59 +00002437TypeSourceInfo *
2438ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2439 SourceLocation NameLoc,
2440 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002441 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002442 assert(!Name.getAsDependentTemplateName() &&
2443 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002444 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002445
2446 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2447 TemplateSpecializationTypeLoc TL
2448 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002449 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002450 TL.setTemplateNameLoc(NameLoc);
2451 TL.setLAngleLoc(Args.getLAngleLoc());
2452 TL.setRAngleLoc(Args.getRAngleLoc());
2453 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2454 TL.setArgLocInfo(i, Args[i].getLocInfo());
2455 return DI;
2456}
2457
Mike Stump11289f42009-09-09 15:08:12 +00002458QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002459ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002460 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002461 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002462 assert(!Template.getAsDependentTemplateName() &&
2463 "No dependent template names here!");
2464
John McCall6b51f282009-11-23 01:53:49 +00002465 unsigned NumArgs = Args.size();
2466
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002467 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002468 ArgVec.reserve(NumArgs);
2469 for (unsigned i = 0; i != NumArgs; ++i)
2470 ArgVec.push_back(Args[i].getArgument());
2471
John McCall2408e322010-04-27 00:57:59 +00002472 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002473 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002474}
2475
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002476#ifndef NDEBUG
2477static bool hasAnyPackExpansions(const TemplateArgument *Args,
2478 unsigned NumArgs) {
2479 for (unsigned I = 0; I != NumArgs; ++I)
2480 if (Args[I].isPackExpansion())
2481 return true;
2482
2483 return true;
2484}
2485#endif
2486
John McCall0ad16662009-10-29 08:12:44 +00002487QualType
2488ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002489 const TemplateArgument *Args,
2490 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002491 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002492 assert(!Template.getAsDependentTemplateName() &&
2493 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002494 // Look through qualified template names.
2495 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2496 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002497
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002498 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002499 Template.getAsTemplateDecl() &&
2500 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002501 QualType CanonType;
2502 if (!Underlying.isNull())
2503 CanonType = getCanonicalType(Underlying);
2504 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002505 // We can get here with an alias template when the specialization contains
2506 // a pack expansion that does not match up with a parameter pack.
2507 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2508 "Caller must compute aliased type");
2509 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002510 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2511 NumArgs);
2512 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002513
Douglas Gregora8e02e72009-07-28 23:00:59 +00002514 // Allocate the (non-canonical) template specialization type, but don't
2515 // try to unique it: these types typically have location information that
2516 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002517 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2518 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002519 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002520 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002521 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002522 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2523 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002524
Douglas Gregor8bf42052009-02-09 18:46:07 +00002525 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002526 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002527}
2528
Mike Stump11289f42009-09-09 15:08:12 +00002529QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002530ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2531 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002532 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002533 assert(!Template.getAsDependentTemplateName() &&
2534 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002535
Douglas Gregore29139c2011-03-03 17:04:51 +00002536 // Look through qualified template names.
2537 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2538 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002539
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002540 // Build the canonical template specialization type.
2541 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002542 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002543 CanonArgs.reserve(NumArgs);
2544 for (unsigned I = 0; I != NumArgs; ++I)
2545 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2546
2547 // Determine whether this canonical template specialization type already
2548 // exists.
2549 llvm::FoldingSetNodeID ID;
2550 TemplateSpecializationType::Profile(ID, CanonTemplate,
2551 CanonArgs.data(), NumArgs, *this);
2552
2553 void *InsertPos = 0;
2554 TemplateSpecializationType *Spec
2555 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2556
2557 if (!Spec) {
2558 // Allocate a new canonical template specialization type.
2559 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2560 sizeof(TemplateArgument) * NumArgs),
2561 TypeAlignment);
2562 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2563 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002564 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002565 Types.push_back(Spec);
2566 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2567 }
2568
2569 assert(Spec->isDependentType() &&
2570 "Non-dependent template-id type must have a canonical type");
2571 return QualType(Spec, 0);
2572}
2573
2574QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002575ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2576 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002577 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002578 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002579 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002580
2581 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002582 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002583 if (T)
2584 return QualType(T, 0);
2585
Douglas Gregorc42075a2010-02-04 18:10:26 +00002586 QualType Canon = NamedType;
2587 if (!Canon.isCanonical()) {
2588 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002589 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2590 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002591 (void)CheckT;
2592 }
2593
Abramo Bagnara6150c882010-05-11 21:36:43 +00002594 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002595 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002596 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002597 return QualType(T, 0);
2598}
2599
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002600QualType
Jay Foad39c79802011-01-12 09:06:06 +00002601ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002602 llvm::FoldingSetNodeID ID;
2603 ParenType::Profile(ID, InnerType);
2604
2605 void *InsertPos = 0;
2606 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2607 if (T)
2608 return QualType(T, 0);
2609
2610 QualType Canon = InnerType;
2611 if (!Canon.isCanonical()) {
2612 Canon = getCanonicalType(InnerType);
2613 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2614 assert(!CheckT && "Paren canonical type broken");
2615 (void)CheckT;
2616 }
2617
2618 T = new (*this) ParenType(InnerType, Canon);
2619 Types.push_back(T);
2620 ParenTypes.InsertNode(T, InsertPos);
2621 return QualType(T, 0);
2622}
2623
Douglas Gregor02085352010-03-31 20:19:30 +00002624QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2625 NestedNameSpecifier *NNS,
2626 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002627 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002628 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2629
2630 if (Canon.isNull()) {
2631 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002632 ElaboratedTypeKeyword CanonKeyword = Keyword;
2633 if (Keyword == ETK_None)
2634 CanonKeyword = ETK_Typename;
2635
2636 if (CanonNNS != NNS || CanonKeyword != Keyword)
2637 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002638 }
2639
2640 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002641 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002642
2643 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002644 DependentNameType *T
2645 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002646 if (T)
2647 return QualType(T, 0);
2648
Douglas Gregor02085352010-03-31 20:19:30 +00002649 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002650 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002651 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002652 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002653}
2654
Mike Stump11289f42009-09-09 15:08:12 +00002655QualType
John McCallc392f372010-06-11 00:33:02 +00002656ASTContext::getDependentTemplateSpecializationType(
2657 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002658 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002659 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002660 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002661 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002662 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002663 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2664 ArgCopy.push_back(Args[I].getArgument());
2665 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2666 ArgCopy.size(),
2667 ArgCopy.data());
2668}
2669
2670QualType
2671ASTContext::getDependentTemplateSpecializationType(
2672 ElaboratedTypeKeyword Keyword,
2673 NestedNameSpecifier *NNS,
2674 const IdentifierInfo *Name,
2675 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002676 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002677 assert((!NNS || NNS->isDependent()) &&
2678 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002679
Douglas Gregorc42075a2010-02-04 18:10:26 +00002680 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002681 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2682 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002683
2684 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002685 DependentTemplateSpecializationType *T
2686 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002687 if (T)
2688 return QualType(T, 0);
2689
John McCallc392f372010-06-11 00:33:02 +00002690 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002691
John McCallc392f372010-06-11 00:33:02 +00002692 ElaboratedTypeKeyword CanonKeyword = Keyword;
2693 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2694
2695 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002696 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002697 for (unsigned I = 0; I != NumArgs; ++I) {
2698 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2699 if (!CanonArgs[I].structurallyEquals(Args[I]))
2700 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002701 }
2702
John McCallc392f372010-06-11 00:33:02 +00002703 QualType Canon;
2704 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2705 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2706 Name, NumArgs,
2707 CanonArgs.data());
2708
2709 // Find the insert position again.
2710 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2711 }
2712
2713 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2714 sizeof(TemplateArgument) * NumArgs),
2715 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002716 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002717 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002718 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002719 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002720 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002721}
2722
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002723QualType ASTContext::getPackExpansionType(QualType Pattern,
2724 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002725 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002726 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002727
2728 assert(Pattern->containsUnexpandedParameterPack() &&
2729 "Pack expansions must expand one or more parameter packs");
2730 void *InsertPos = 0;
2731 PackExpansionType *T
2732 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2733 if (T)
2734 return QualType(T, 0);
2735
2736 QualType Canon;
2737 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002738 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002739
2740 // Find the insert position again.
2741 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2742 }
2743
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002744 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002745 Types.push_back(T);
2746 PackExpansionTypes.InsertNode(T, InsertPos);
2747 return QualType(T, 0);
2748}
2749
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002750/// CmpProtocolNames - Comparison predicate for sorting protocols
2751/// alphabetically.
2752static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2753 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002754 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002755}
2756
John McCall8b07ec22010-05-15 11:32:37 +00002757static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002758 unsigned NumProtocols) {
2759 if (NumProtocols == 0) return true;
2760
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002761 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2762 return false;
2763
John McCallfc93cf92009-10-22 22:37:11 +00002764 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002765 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2766 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002767 return false;
2768 return true;
2769}
2770
2771static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002772 unsigned &NumProtocols) {
2773 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002774
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002775 // Sort protocols, keyed by name.
2776 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2777
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002778 // Canonicalize.
2779 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2780 Protocols[I] = Protocols[I]->getCanonicalDecl();
2781
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002782 // Remove duplicates.
2783 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2784 NumProtocols = ProtocolsEnd-Protocols;
2785}
2786
John McCall8b07ec22010-05-15 11:32:37 +00002787QualType ASTContext::getObjCObjectType(QualType BaseType,
2788 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002789 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002790 // If the base type is an interface and there aren't any protocols
2791 // to add, then the interface type will do just fine.
2792 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2793 return BaseType;
2794
2795 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002796 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002797 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002798 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002799 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2800 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002801
John McCall8b07ec22010-05-15 11:32:37 +00002802 // Build the canonical type, which has the canonical base type and
2803 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002804 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002805 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2806 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2807 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002808 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002809 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002810 unsigned UniqueCount = NumProtocols;
2811
John McCallfc93cf92009-10-22 22:37:11 +00002812 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002813 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2814 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002815 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002816 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2817 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002818 }
2819
2820 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002821 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2822 }
2823
2824 unsigned Size = sizeof(ObjCObjectTypeImpl);
2825 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2826 void *Mem = Allocate(Size, TypeAlignment);
2827 ObjCObjectTypeImpl *T =
2828 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2829
2830 Types.push_back(T);
2831 ObjCObjectTypes.InsertNode(T, InsertPos);
2832 return QualType(T, 0);
2833}
2834
2835/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2836/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002837QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002838 llvm::FoldingSetNodeID ID;
2839 ObjCObjectPointerType::Profile(ID, ObjectT);
2840
2841 void *InsertPos = 0;
2842 if (ObjCObjectPointerType *QT =
2843 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2844 return QualType(QT, 0);
2845
2846 // Find the canonical object type.
2847 QualType Canonical;
2848 if (!ObjectT.isCanonical()) {
2849 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2850
2851 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002852 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2853 }
2854
Douglas Gregorf85bee62010-02-08 22:59:26 +00002855 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002856 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2857 ObjCObjectPointerType *QType =
2858 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002859
Steve Narofffb4330f2009-06-17 22:40:22 +00002860 Types.push_back(QType);
2861 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002862 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002863}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002864
Douglas Gregor1c283312010-08-11 12:19:30 +00002865/// getObjCInterfaceType - Return the unique reference to the type for the
2866/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002867QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2868 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002869 if (Decl->TypeForDecl)
2870 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002871
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002872 if (PrevDecl) {
2873 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2874 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2875 return QualType(PrevDecl->TypeForDecl, 0);
2876 }
2877
Douglas Gregor7671e532011-12-16 16:34:57 +00002878 // Prefer the definition, if there is one.
2879 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2880 Decl = Def;
2881
Douglas Gregor1c283312010-08-11 12:19:30 +00002882 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2883 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2884 Decl->TypeForDecl = T;
2885 Types.push_back(T);
2886 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002887}
2888
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002889/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2890/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002891/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002892/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002893/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002894QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002895 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002896 if (tofExpr->isTypeDependent()) {
2897 llvm::FoldingSetNodeID ID;
2898 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002899
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002900 void *InsertPos = 0;
2901 DependentTypeOfExprType *Canon
2902 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2903 if (Canon) {
2904 // We already have a "canonical" version of an identical, dependent
2905 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002906 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002907 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002908 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002909 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002910 Canon
2911 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002912 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2913 toe = Canon;
2914 }
2915 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002916 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002917 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002918 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002919 Types.push_back(toe);
2920 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002921}
2922
Steve Naroffa773cd52007-08-01 18:02:17 +00002923/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2924/// TypeOfType AST's. The only motivation to unique these nodes would be
2925/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002926/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002927/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002928QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002929 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002930 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002931 Types.push_back(tot);
2932 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002933}
2934
Anders Carlssonad6bd352009-06-24 21:24:56 +00002935
Anders Carlsson81df7b82009-06-24 19:06:50 +00002936/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2937/// DecltypeType AST's. The only motivation to unique these nodes would be
2938/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002939/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00002940/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00002941QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002942 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002943
2944 // C++0x [temp.type]p2:
2945 // If an expression e involves a template parameter, decltype(e) denotes a
2946 // unique dependent type. Two such decltype-specifiers refer to the same
2947 // type only if their expressions are equivalent (14.5.6.1).
2948 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002949 llvm::FoldingSetNodeID ID;
2950 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002951
Douglas Gregora21f6c32009-07-30 23:36:40 +00002952 void *InsertPos = 0;
2953 DependentDecltypeType *Canon
2954 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2955 if (Canon) {
2956 // We already have a "canonical" version of an equivalent, dependent
2957 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002958 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002959 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002960 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002961 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002962 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002963 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2964 dt = Canon;
2965 }
2966 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00002967 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
2968 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00002969 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002970 Types.push_back(dt);
2971 return QualType(dt, 0);
2972}
2973
Alexis Hunte852b102011-05-24 22:41:36 +00002974/// getUnaryTransformationType - We don't unique these, since the memory
2975/// savings are minimal and these are rare.
2976QualType ASTContext::getUnaryTransformType(QualType BaseType,
2977 QualType UnderlyingType,
2978 UnaryTransformType::UTTKind Kind)
2979 const {
2980 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002981 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2982 Kind,
2983 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00002984 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00002985 Types.push_back(Ty);
2986 return QualType(Ty, 0);
2987}
2988
Richard Smithb2bc2e62011-02-21 20:05:19 +00002989/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002990QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002991 void *InsertPos = 0;
2992 if (!DeducedType.isNull()) {
2993 // Look in the folding set for an existing type.
2994 llvm::FoldingSetNodeID ID;
2995 AutoType::Profile(ID, DeducedType);
2996 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2997 return QualType(AT, 0);
2998 }
2999
3000 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3001 Types.push_back(AT);
3002 if (InsertPos)
3003 AutoTypes.InsertNode(AT, InsertPos);
3004 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00003005}
3006
Eli Friedman0dfb8892011-10-06 23:00:33 +00003007/// getAtomicType - Return the uniqued reference to the atomic type for
3008/// the given value type.
3009QualType ASTContext::getAtomicType(QualType T) const {
3010 // Unique pointers, to guarantee there is only one pointer of a particular
3011 // structure.
3012 llvm::FoldingSetNodeID ID;
3013 AtomicType::Profile(ID, T);
3014
3015 void *InsertPos = 0;
3016 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3017 return QualType(AT, 0);
3018
3019 // If the atomic value type isn't canonical, this won't be a canonical type
3020 // either, so fill in the canonical type field.
3021 QualType Canonical;
3022 if (!T.isCanonical()) {
3023 Canonical = getAtomicType(getCanonicalType(T));
3024
3025 // Get the new insert position for the node we care about.
3026 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3027 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3028 }
3029 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3030 Types.push_back(New);
3031 AtomicTypes.InsertNode(New, InsertPos);
3032 return QualType(New, 0);
3033}
3034
Richard Smith02e85f32011-04-14 22:09:26 +00003035/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3036QualType ASTContext::getAutoDeductType() const {
3037 if (AutoDeductTy.isNull())
3038 AutoDeductTy = getAutoType(QualType());
3039 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3040 return AutoDeductTy;
3041}
3042
3043/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3044QualType ASTContext::getAutoRRefDeductType() const {
3045 if (AutoRRefDeductTy.isNull())
3046 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3047 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3048 return AutoRRefDeductTy;
3049}
3050
Chris Lattnerfb072462007-01-23 05:45:31 +00003051/// getTagDeclType - Return the unique reference to the type for the
3052/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003053QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003054 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003055 // FIXME: What is the design on getTagDeclType when it requires casting
3056 // away const? mutable?
3057 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003058}
3059
Mike Stump11289f42009-09-09 15:08:12 +00003060/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3061/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3062/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003063CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003064 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003065}
Chris Lattnerfb072462007-01-23 05:45:31 +00003066
Hans Wennborg27541db2011-10-27 08:29:09 +00003067/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3068CanQualType ASTContext::getIntMaxType() const {
3069 return getFromTargetType(Target->getIntMaxType());
3070}
3071
3072/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3073CanQualType ASTContext::getUIntMaxType() const {
3074 return getFromTargetType(Target->getUIntMaxType());
3075}
3076
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003077/// getSignedWCharType - Return the type of "signed wchar_t".
3078/// Used when in C++, as a GCC extension.
3079QualType ASTContext::getSignedWCharType() const {
3080 // FIXME: derive from "Target" ?
3081 return WCharTy;
3082}
3083
3084/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3085/// Used when in C++, as a GCC extension.
3086QualType ASTContext::getUnsignedWCharType() const {
3087 // FIXME: derive from "Target" ?
3088 return UnsignedIntTy;
3089}
3090
Hans Wennborg27541db2011-10-27 08:29:09 +00003091/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003092/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3093QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003094 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003095}
3096
Chris Lattnera21ad802008-04-02 05:18:44 +00003097//===----------------------------------------------------------------------===//
3098// Type Operators
3099//===----------------------------------------------------------------------===//
3100
Jay Foad39c79802011-01-12 09:06:06 +00003101CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003102 // Push qualifiers into arrays, and then discard any remaining
3103 // qualifiers.
3104 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003105 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003106 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003107 QualType Result;
3108 if (isa<ArrayType>(Ty)) {
3109 Result = getArrayDecayedType(QualType(Ty,0));
3110 } else if (isa<FunctionType>(Ty)) {
3111 Result = getPointerType(QualType(Ty, 0));
3112 } else {
3113 Result = QualType(Ty, 0);
3114 }
3115
3116 return CanQualType::CreateUnsafe(Result);
3117}
3118
John McCall6c9dd522011-01-18 07:41:22 +00003119QualType ASTContext::getUnqualifiedArrayType(QualType type,
3120 Qualifiers &quals) {
3121 SplitQualType splitType = type.getSplitUnqualifiedType();
3122
3123 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3124 // the unqualified desugared type and then drops it on the floor.
3125 // We then have to strip that sugar back off with
3126 // getUnqualifiedDesugaredType(), which is silly.
3127 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003128 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003129
3130 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003131 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003132 quals = splitType.Quals;
3133 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003134 }
3135
John McCall6c9dd522011-01-18 07:41:22 +00003136 // Otherwise, recurse on the array's element type.
3137 QualType elementType = AT->getElementType();
3138 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3139
3140 // If that didn't change the element type, AT has no qualifiers, so we
3141 // can just use the results in splitType.
3142 if (elementType == unqualElementType) {
3143 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003144 quals = splitType.Quals;
3145 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003146 }
3147
3148 // Otherwise, add in the qualifiers from the outermost type, then
3149 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003150 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003151
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003152 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003153 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003154 CAT->getSizeModifier(), 0);
3155 }
3156
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003157 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003158 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003159 }
3160
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003161 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003162 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003163 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003164 VAT->getSizeModifier(),
3165 VAT->getIndexTypeCVRQualifiers(),
3166 VAT->getBracketsRange());
3167 }
3168
3169 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003170 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003171 DSAT->getSizeModifier(), 0,
3172 SourceRange());
3173}
3174
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003175/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3176/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3177/// they point to and return true. If T1 and T2 aren't pointer types
3178/// or pointer-to-member types, or if they are not similar at this
3179/// level, returns false and leaves T1 and T2 unchanged. Top-level
3180/// qualifiers on T1 and T2 are ignored. This function will typically
3181/// be called in a loop that successively "unwraps" pointer and
3182/// pointer-to-member types to compare them at each level.
3183bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3184 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3185 *T2PtrType = T2->getAs<PointerType>();
3186 if (T1PtrType && T2PtrType) {
3187 T1 = T1PtrType->getPointeeType();
3188 T2 = T2PtrType->getPointeeType();
3189 return true;
3190 }
3191
3192 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3193 *T2MPType = T2->getAs<MemberPointerType>();
3194 if (T1MPType && T2MPType &&
3195 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3196 QualType(T2MPType->getClass(), 0))) {
3197 T1 = T1MPType->getPointeeType();
3198 T2 = T2MPType->getPointeeType();
3199 return true;
3200 }
3201
David Blaikiebbafb8a2012-03-11 07:00:24 +00003202 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003203 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3204 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3205 if (T1OPType && T2OPType) {
3206 T1 = T1OPType->getPointeeType();
3207 T2 = T2OPType->getPointeeType();
3208 return true;
3209 }
3210 }
3211
3212 // FIXME: Block pointers, too?
3213
3214 return false;
3215}
3216
Jay Foad39c79802011-01-12 09:06:06 +00003217DeclarationNameInfo
3218ASTContext::getNameForTemplate(TemplateName Name,
3219 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003220 switch (Name.getKind()) {
3221 case TemplateName::QualifiedTemplate:
3222 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003223 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003224 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3225 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003226
John McCalld9dfe3a2011-06-30 08:33:18 +00003227 case TemplateName::OverloadedTemplate: {
3228 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3229 // DNInfo work in progress: CHECKME: what about DNLoc?
3230 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3231 }
3232
3233 case TemplateName::DependentTemplate: {
3234 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003235 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003236 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003237 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3238 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003239 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003240 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3241 // DNInfo work in progress: FIXME: source locations?
3242 DeclarationNameLoc DNLoc;
3243 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3244 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3245 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003246 }
3247 }
3248
John McCalld9dfe3a2011-06-30 08:33:18 +00003249 case TemplateName::SubstTemplateTemplateParm: {
3250 SubstTemplateTemplateParmStorage *subst
3251 = Name.getAsSubstTemplateTemplateParm();
3252 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3253 NameLoc);
3254 }
3255
3256 case TemplateName::SubstTemplateTemplateParmPack: {
3257 SubstTemplateTemplateParmPackStorage *subst
3258 = Name.getAsSubstTemplateTemplateParmPack();
3259 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3260 NameLoc);
3261 }
3262 }
3263
3264 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003265}
3266
Jay Foad39c79802011-01-12 09:06:06 +00003267TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003268 switch (Name.getKind()) {
3269 case TemplateName::QualifiedTemplate:
3270 case TemplateName::Template: {
3271 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003272 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003273 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003274 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3275
3276 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003277 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003278 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003279
John McCalld9dfe3a2011-06-30 08:33:18 +00003280 case TemplateName::OverloadedTemplate:
3281 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003282
John McCalld9dfe3a2011-06-30 08:33:18 +00003283 case TemplateName::DependentTemplate: {
3284 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3285 assert(DTN && "Non-dependent template names must refer to template decls.");
3286 return DTN->CanonicalTemplateName;
3287 }
3288
3289 case TemplateName::SubstTemplateTemplateParm: {
3290 SubstTemplateTemplateParmStorage *subst
3291 = Name.getAsSubstTemplateTemplateParm();
3292 return getCanonicalTemplateName(subst->getReplacement());
3293 }
3294
3295 case TemplateName::SubstTemplateTemplateParmPack: {
3296 SubstTemplateTemplateParmPackStorage *subst
3297 = Name.getAsSubstTemplateTemplateParmPack();
3298 TemplateTemplateParmDecl *canonParameter
3299 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3300 TemplateArgument canonArgPack
3301 = getCanonicalTemplateArgument(subst->getArgumentPack());
3302 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3303 }
3304 }
3305
3306 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003307}
3308
Douglas Gregoradee3e32009-11-11 23:06:43 +00003309bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3310 X = getCanonicalTemplateName(X);
3311 Y = getCanonicalTemplateName(Y);
3312 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3313}
3314
Mike Stump11289f42009-09-09 15:08:12 +00003315TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003316ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003317 switch (Arg.getKind()) {
3318 case TemplateArgument::Null:
3319 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003320
Douglas Gregora8e02e72009-07-28 23:00:59 +00003321 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003322 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003323
Douglas Gregor31f55dc2012-04-06 22:40:38 +00003324 case TemplateArgument::Declaration: {
3325 if (Decl *D = Arg.getAsDecl())
3326 return TemplateArgument(D->getCanonicalDecl());
3327 return TemplateArgument((Decl*)0);
3328 }
Mike Stump11289f42009-09-09 15:08:12 +00003329
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003330 case TemplateArgument::Template:
3331 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003332
3333 case TemplateArgument::TemplateExpansion:
3334 return TemplateArgument(getCanonicalTemplateName(
3335 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003336 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003337
Douglas Gregora8e02e72009-07-28 23:00:59 +00003338 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003339 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003340 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003341
Douglas Gregora8e02e72009-07-28 23:00:59 +00003342 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003343 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003344
Douglas Gregora8e02e72009-07-28 23:00:59 +00003345 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003346 if (Arg.pack_size() == 0)
3347 return Arg;
3348
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003349 TemplateArgument *CanonArgs
3350 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003351 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003352 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003353 AEnd = Arg.pack_end();
3354 A != AEnd; (void)++A, ++Idx)
3355 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003356
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003357 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003358 }
3359 }
3360
3361 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003362 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003363}
3364
Douglas Gregor333489b2009-03-27 23:10:48 +00003365NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003366ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003367 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003368 return 0;
3369
3370 switch (NNS->getKind()) {
3371 case NestedNameSpecifier::Identifier:
3372 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003373 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003374 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3375 NNS->getAsIdentifier());
3376
3377 case NestedNameSpecifier::Namespace:
3378 // A namespace is canonical; build a nested-name-specifier with
3379 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003380 return NestedNameSpecifier::Create(*this, 0,
3381 NNS->getAsNamespace()->getOriginalNamespace());
3382
3383 case NestedNameSpecifier::NamespaceAlias:
3384 // A namespace is canonical; build a nested-name-specifier with
3385 // this namespace and no prefix.
3386 return NestedNameSpecifier::Create(*this, 0,
3387 NNS->getAsNamespaceAlias()->getNamespace()
3388 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003389
3390 case NestedNameSpecifier::TypeSpec:
3391 case NestedNameSpecifier::TypeSpecWithTemplate: {
3392 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003393
3394 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3395 // break it apart into its prefix and identifier, then reconsititute those
3396 // as the canonical nested-name-specifier. This is required to canonicalize
3397 // a dependent nested-name-specifier involving typedefs of dependent-name
3398 // types, e.g.,
3399 // typedef typename T::type T1;
3400 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003401 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3402 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003403 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003404
Eli Friedman5358a0a2012-03-03 04:09:56 +00003405 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3406 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3407 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003408 return NestedNameSpecifier::Create(*this, 0, false,
3409 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003410 }
3411
3412 case NestedNameSpecifier::Global:
3413 // The global specifier is canonical and unique.
3414 return NNS;
3415 }
3416
David Blaikie8a40f702012-01-17 06:56:22 +00003417 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003418}
3419
Chris Lattner7adf0762008-08-04 07:31:14 +00003420
Jay Foad39c79802011-01-12 09:06:06 +00003421const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003422 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003423 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003424 // Handle the common positive case fast.
3425 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3426 return AT;
3427 }
Mike Stump11289f42009-09-09 15:08:12 +00003428
John McCall8ccfcb52009-09-24 19:53:00 +00003429 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003430 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003431 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003432
John McCall8ccfcb52009-09-24 19:53:00 +00003433 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003434 // implements C99 6.7.3p8: "If the specification of an array type includes
3435 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003436
Chris Lattner7adf0762008-08-04 07:31:14 +00003437 // If we get here, we either have type qualifiers on the type, or we have
3438 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003439 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003440
John McCall33ddac02011-01-19 10:06:00 +00003441 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003442 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003443
Chris Lattner7adf0762008-08-04 07:31:14 +00003444 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003445 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003446 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003447 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003448
Chris Lattner7adf0762008-08-04 07:31:14 +00003449 // Otherwise, we have an array and we have qualifiers on it. Push the
3450 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003451 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003452
Chris Lattner7adf0762008-08-04 07:31:14 +00003453 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3454 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3455 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003456 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003457 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3458 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3459 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003460 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003461
Mike Stump11289f42009-09-09 15:08:12 +00003462 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003463 = dyn_cast<DependentSizedArrayType>(ATy))
3464 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003465 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003466 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003467 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003468 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003469 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003470
Chris Lattner7adf0762008-08-04 07:31:14 +00003471 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003472 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003473 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003474 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003475 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003476 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003477}
3478
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003479QualType ASTContext::getAdjustedParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003480 // C99 6.7.5.3p7:
3481 // A declaration of a parameter as "array of type" shall be
3482 // adjusted to "qualified pointer to type", where the type
3483 // qualifiers (if any) are those specified within the [ and ] of
3484 // the array type derivation.
3485 if (T->isArrayType())
3486 return getArrayDecayedType(T);
3487
3488 // C99 6.7.5.3p8:
3489 // A declaration of a parameter as "function returning type"
3490 // shall be adjusted to "pointer to function returning type", as
3491 // in 6.3.2.1.
3492 if (T->isFunctionType())
3493 return getPointerType(T);
3494
3495 return T;
3496}
3497
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00003498QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00003499 T = getVariableArrayDecayedType(T);
3500 T = getAdjustedParameterType(T);
3501 return T.getUnqualifiedType();
3502}
3503
Chris Lattnera21ad802008-04-02 05:18:44 +00003504/// getArrayDecayedType - Return the properly qualified result of decaying the
3505/// specified array type to a pointer. This operation is non-trivial when
3506/// handling typedefs etc. The canonical type of "T" must be an array type,
3507/// this returns a pointer to a properly qualified element of the array.
3508///
3509/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003510QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003511 // Get the element type with 'getAsArrayType' so that we don't lose any
3512 // typedefs in the element type of the array. This also handles propagation
3513 // of type qualifiers from the array type into the element type if present
3514 // (C99 6.7.3p8).
3515 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3516 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003517
Chris Lattner7adf0762008-08-04 07:31:14 +00003518 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003519
3520 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003521 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003522}
3523
John McCall33ddac02011-01-19 10:06:00 +00003524QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3525 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003526}
3527
John McCall33ddac02011-01-19 10:06:00 +00003528QualType ASTContext::getBaseElementType(QualType type) const {
3529 Qualifiers qs;
3530 while (true) {
3531 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003532 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003533 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003534
John McCall33ddac02011-01-19 10:06:00 +00003535 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003536 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003537 }
Mike Stump11289f42009-09-09 15:08:12 +00003538
John McCall33ddac02011-01-19 10:06:00 +00003539 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003540}
3541
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003542/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003543uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003544ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3545 uint64_t ElementCount = 1;
3546 do {
3547 ElementCount *= CA->getSize().getZExtValue();
3548 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3549 } while (CA);
3550 return ElementCount;
3551}
3552
Steve Naroff0af91202007-04-27 21:51:21 +00003553/// getFloatingRank - Return a relative rank for floating point types.
3554/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003555static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003556 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003557 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003558
John McCall9dd450b2009-09-21 23:43:11 +00003559 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3560 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003561 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003562 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003563 case BuiltinType::Float: return FloatRank;
3564 case BuiltinType::Double: return DoubleRank;
3565 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003566 }
3567}
3568
Mike Stump11289f42009-09-09 15:08:12 +00003569/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3570/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003571/// 'typeDomain' is a real floating point or complex type.
3572/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003573QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3574 QualType Domain) const {
3575 FloatingRank EltRank = getFloatingRank(Size);
3576 if (Domain->isComplexType()) {
3577 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003578 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003579 case FloatRank: return FloatComplexTy;
3580 case DoubleRank: return DoubleComplexTy;
3581 case LongDoubleRank: return LongDoubleComplexTy;
3582 }
Steve Naroff0af91202007-04-27 21:51:21 +00003583 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003584
3585 assert(Domain->isRealFloatingType() && "Unknown domain!");
3586 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003587 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003588 case FloatRank: return FloatTy;
3589 case DoubleRank: return DoubleTy;
3590 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003591 }
David Blaikief47fa302012-01-17 02:30:50 +00003592 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003593}
3594
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003595/// getFloatingTypeOrder - Compare the rank of the two specified floating
3596/// point types, ignoring the domain of the type (i.e. 'double' ==
3597/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003598/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003599int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003600 FloatingRank LHSR = getFloatingRank(LHS);
3601 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003602
Chris Lattnerb90739d2008-04-06 23:38:49 +00003603 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003604 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003605 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003606 return 1;
3607 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003608}
3609
Chris Lattner76a00cf2008-04-06 22:59:24 +00003610/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3611/// routine will assert if passed a built-in type that isn't an integer or enum,
3612/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003613unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003614 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003615
Chris Lattner76a00cf2008-04-06 22:59:24 +00003616 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003617 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003618 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003619 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003620 case BuiltinType::Char_S:
3621 case BuiltinType::Char_U:
3622 case BuiltinType::SChar:
3623 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003624 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003625 case BuiltinType::Short:
3626 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003627 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003628 case BuiltinType::Int:
3629 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003630 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003631 case BuiltinType::Long:
3632 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003633 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003634 case BuiltinType::LongLong:
3635 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003636 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003637 case BuiltinType::Int128:
3638 case BuiltinType::UInt128:
3639 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003640 }
3641}
3642
Eli Friedman629ffb92009-08-20 04:21:42 +00003643/// \brief Whether this is a promotable bitfield reference according
3644/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3645///
3646/// \returns the type this bit-field will promote to, or NULL if no
3647/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003648QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003649 if (E->isTypeDependent() || E->isValueDependent())
3650 return QualType();
3651
Eli Friedman629ffb92009-08-20 04:21:42 +00003652 FieldDecl *Field = E->getBitField();
3653 if (!Field)
3654 return QualType();
3655
3656 QualType FT = Field->getType();
3657
Richard Smithcaf33902011-10-10 18:28:20 +00003658 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003659 uint64_t IntSize = getTypeSize(IntTy);
3660 // GCC extension compatibility: if the bit-field size is less than or equal
3661 // to the size of int, it gets promoted no matter what its type is.
3662 // For instance, unsigned long bf : 4 gets promoted to signed int.
3663 if (BitWidth < IntSize)
3664 return IntTy;
3665
3666 if (BitWidth == IntSize)
3667 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3668
3669 // Types bigger than int are not subject to promotions, and therefore act
3670 // like the base type.
3671 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3672 // is ridiculous.
3673 return QualType();
3674}
3675
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003676/// getPromotedIntegerType - Returns the type that Promotable will
3677/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3678/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003679QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003680 assert(!Promotable.isNull());
3681 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003682 if (const EnumType *ET = Promotable->getAs<EnumType>())
3683 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003684
3685 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3686 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3687 // (3.9.1) can be converted to a prvalue of the first of the following
3688 // types that can represent all the values of its underlying type:
3689 // int, unsigned int, long int, unsigned long int, long long int, or
3690 // unsigned long long int [...]
3691 // FIXME: Is there some better way to compute this?
3692 if (BT->getKind() == BuiltinType::WChar_S ||
3693 BT->getKind() == BuiltinType::WChar_U ||
3694 BT->getKind() == BuiltinType::Char16 ||
3695 BT->getKind() == BuiltinType::Char32) {
3696 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3697 uint64_t FromSize = getTypeSize(BT);
3698 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3699 LongLongTy, UnsignedLongLongTy };
3700 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3701 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3702 if (FromSize < ToSize ||
3703 (FromSize == ToSize &&
3704 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3705 return PromoteTypes[Idx];
3706 }
3707 llvm_unreachable("char type should fit into long long");
3708 }
3709 }
3710
3711 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003712 if (Promotable->isSignedIntegerType())
3713 return IntTy;
3714 uint64_t PromotableSize = getTypeSize(Promotable);
3715 uint64_t IntSize = getTypeSize(IntTy);
3716 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3717 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3718}
3719
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003720/// \brief Recurses in pointer/array types until it finds an objc retainable
3721/// type and returns its ownership.
3722Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3723 while (!T.isNull()) {
3724 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3725 return T.getObjCLifetime();
3726 if (T->isArrayType())
3727 T = getBaseElementType(T);
3728 else if (const PointerType *PT = T->getAs<PointerType>())
3729 T = PT->getPointeeType();
3730 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003731 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003732 else
3733 break;
3734 }
3735
3736 return Qualifiers::OCL_None;
3737}
3738
Mike Stump11289f42009-09-09 15:08:12 +00003739/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003740/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003741/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003742int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003743 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3744 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003745 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003746
Chris Lattner76a00cf2008-04-06 22:59:24 +00003747 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3748 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003749
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003750 unsigned LHSRank = getIntegerRank(LHSC);
3751 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003752
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003753 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3754 if (LHSRank == RHSRank) return 0;
3755 return LHSRank > RHSRank ? 1 : -1;
3756 }
Mike Stump11289f42009-09-09 15:08:12 +00003757
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003758 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3759 if (LHSUnsigned) {
3760 // If the unsigned [LHS] type is larger, return it.
3761 if (LHSRank >= RHSRank)
3762 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003763
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003764 // If the signed type can represent all values of the unsigned type, it
3765 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003766 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003767 return -1;
3768 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003769
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003770 // If the unsigned [RHS] type is larger, return it.
3771 if (RHSRank >= LHSRank)
3772 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003773
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003774 // If the signed type can represent all values of the unsigned type, it
3775 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003776 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003777 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003778}
Anders Carlsson98f07902007-08-17 05:31:46 +00003779
Anders Carlsson6d417272009-11-14 21:45:58 +00003780static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003781CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3782 DeclContext *DC, IdentifierInfo *Id) {
3783 SourceLocation Loc;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003784 if (Ctx.getLangOpts().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003785 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003786 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003787 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003788}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003789
Mike Stump11289f42009-09-09 15:08:12 +00003790// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003791QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003792 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003793 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003794 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003795 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003796 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003797
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003798 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003799
Anders Carlsson98f07902007-08-17 05:31:46 +00003800 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003801 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003802 // int flags;
3803 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003804 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003805 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003806 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003807 FieldTypes[3] = LongTy;
3808
Anders Carlsson98f07902007-08-17 05:31:46 +00003809 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003810 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003811 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003812 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003813 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003814 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003815 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003816 /*Mutable=*/false,
3817 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003818 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003819 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003820 }
3821
Douglas Gregord5058122010-02-11 01:19:42 +00003822 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003823 }
Mike Stump11289f42009-09-09 15:08:12 +00003824
Anders Carlsson98f07902007-08-17 05:31:46 +00003825 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003826}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003827
Douglas Gregor512b0772009-04-23 22:29:11 +00003828void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003829 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003830 assert(Rec && "Invalid CFConstantStringType");
3831 CFConstantStringTypeDecl = Rec->getDecl();
3832}
3833
Jay Foad39c79802011-01-12 09:06:06 +00003834QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003835 if (BlockDescriptorType)
3836 return getTagDeclType(BlockDescriptorType);
3837
3838 RecordDecl *T;
3839 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003840 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003841 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003842 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003843
3844 QualType FieldTypes[] = {
3845 UnsignedLongTy,
3846 UnsignedLongTy,
3847 };
3848
3849 const char *FieldNames[] = {
3850 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003851 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003852 };
3853
3854 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003855 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003856 SourceLocation(),
3857 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003858 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003859 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003860 /*Mutable=*/false,
3861 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003862 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003863 T->addDecl(Field);
3864 }
3865
Douglas Gregord5058122010-02-11 01:19:42 +00003866 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003867
3868 BlockDescriptorType = T;
3869
3870 return getTagDeclType(BlockDescriptorType);
3871}
3872
Jay Foad39c79802011-01-12 09:06:06 +00003873QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003874 if (BlockDescriptorExtendedType)
3875 return getTagDeclType(BlockDescriptorExtendedType);
3876
3877 RecordDecl *T;
3878 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003879 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003880 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003881 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003882
3883 QualType FieldTypes[] = {
3884 UnsignedLongTy,
3885 UnsignedLongTy,
3886 getPointerType(VoidPtrTy),
3887 getPointerType(VoidPtrTy)
3888 };
3889
3890 const char *FieldNames[] = {
3891 "reserved",
3892 "Size",
3893 "CopyFuncPtr",
3894 "DestroyFuncPtr"
3895 };
3896
3897 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003898 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003899 SourceLocation(),
3900 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003901 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003902 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003903 /*Mutable=*/false,
3904 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003905 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003906 T->addDecl(Field);
3907 }
3908
Douglas Gregord5058122010-02-11 01:19:42 +00003909 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003910
3911 BlockDescriptorExtendedType = T;
3912
3913 return getTagDeclType(BlockDescriptorExtendedType);
3914}
3915
Jay Foad39c79802011-01-12 09:06:06 +00003916bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003917 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003918 return true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003919 if (getLangOpts().CPlusPlus) {
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003920 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3921 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003922 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003923
3924 }
3925 }
Mike Stump94967902009-10-21 18:16:27 +00003926 return false;
3927}
3928
Jay Foad39c79802011-01-12 09:06:06 +00003929QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003930ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003931 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003932 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003933 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003934 // unsigned int __flags;
3935 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003936 // void *__copy_helper; // as needed
3937 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003938 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003939 // } *
3940
Mike Stump94967902009-10-21 18:16:27 +00003941 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3942
3943 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003944 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003945 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3946 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003947 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003948 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003949 T->startDefinition();
3950 QualType Int32Ty = IntTy;
3951 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3952 QualType FieldTypes[] = {
3953 getPointerType(VoidPtrTy),
3954 getPointerType(getTagDeclType(T)),
3955 Int32Ty,
3956 Int32Ty,
3957 getPointerType(VoidPtrTy),
3958 getPointerType(VoidPtrTy),
3959 Ty
3960 };
3961
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003962 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003963 "__isa",
3964 "__forwarding",
3965 "__flags",
3966 "__size",
3967 "__copy_helper",
3968 "__destroy_helper",
3969 DeclName,
3970 };
3971
3972 for (size_t i = 0; i < 7; ++i) {
3973 if (!HasCopyAndDispose && i >=4 && i <= 5)
3974 continue;
3975 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003976 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003977 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003978 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003979 /*BitWidth=*/0, /*Mutable=*/false,
3980 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003981 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003982 T->addDecl(Field);
3983 }
3984
Douglas Gregord5058122010-02-11 01:19:42 +00003985 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003986
3987 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003988}
3989
Douglas Gregorbab8a962011-09-08 01:46:34 +00003990TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3991 if (!ObjCInstanceTypeDecl)
3992 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3993 getTranslationUnitDecl(),
3994 SourceLocation(),
3995 SourceLocation(),
3996 &Idents.get("instancetype"),
3997 getTrivialTypeSourceInfo(getObjCIdType()));
3998 return ObjCInstanceTypeDecl;
3999}
4000
Anders Carlsson18acd442007-10-29 06:33:42 +00004001// This returns true if a type has been typedefed to BOOL:
4002// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00004003static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00004004 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00004005 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4006 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00004007
Anders Carlssond8499822007-10-29 05:01:08 +00004008 return false;
4009}
4010
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004011/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004012/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00004013CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00004014 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4015 return CharUnits::Zero();
4016
Ken Dyck40775002010-01-11 17:06:35 +00004017 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00004018
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004019 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00004020 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00004021 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004022 // Treat arrays as pointers, since that's how they're passed in.
4023 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004024 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004025 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004026}
4027
4028static inline
4029std::string charUnitsToString(const CharUnits &CU) {
4030 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004031}
4032
John McCall351762c2011-02-07 10:33:21 +00004033/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004034/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004035std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4036 std::string S;
4037
David Chisnall950a9512009-11-17 19:33:30 +00004038 const BlockDecl *Decl = Expr->getBlockDecl();
4039 QualType BlockTy =
4040 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4041 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004042 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004043 // Compute size of all parameters.
4044 // Start with computing size of a pointer in number of bytes.
4045 // FIXME: There might(should) be a better way of doing this computation!
4046 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004047 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4048 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004049 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004050 E = Decl->param_end(); PI != E; ++PI) {
4051 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004052 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00004053 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004054 ParmOffset += sz;
4055 }
4056 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004057 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004058 // Block pointer and offset.
4059 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004060
4061 // Argument types.
4062 ParmOffset = PtrSize;
4063 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4064 Decl->param_end(); PI != E; ++PI) {
4065 ParmVarDecl *PVDecl = *PI;
4066 QualType PType = PVDecl->getOriginalType();
4067 if (const ArrayType *AT =
4068 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4069 // Use array's original type only if it has known number of
4070 // elements.
4071 if (!isa<ConstantArrayType>(AT))
4072 PType = PVDecl->getType();
4073 } else if (PType->isFunctionType())
4074 PType = PVDecl->getType();
4075 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004076 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004077 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004078 }
John McCall351762c2011-02-07 10:33:21 +00004079
4080 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004081}
4082
Douglas Gregora9d84932011-05-27 01:19:52 +00004083bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004084 std::string& S) {
4085 // Encode result type.
4086 getObjCEncodingForType(Decl->getResultType(), S);
4087 CharUnits ParmOffset;
4088 // Compute size of all parameters.
4089 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4090 E = Decl->param_end(); PI != E; ++PI) {
4091 QualType PType = (*PI)->getType();
4092 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004093 if (sz.isZero())
4094 return true;
4095
David Chisnall50e4eba2010-12-30 14:05:53 +00004096 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004097 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004098 ParmOffset += sz;
4099 }
4100 S += charUnitsToString(ParmOffset);
4101 ParmOffset = CharUnits::Zero();
4102
4103 // Argument types.
4104 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4105 E = Decl->param_end(); PI != E; ++PI) {
4106 ParmVarDecl *PVDecl = *PI;
4107 QualType PType = PVDecl->getOriginalType();
4108 if (const ArrayType *AT =
4109 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4110 // Use array's original type only if it has known number of
4111 // elements.
4112 if (!isa<ConstantArrayType>(AT))
4113 PType = PVDecl->getType();
4114 } else if (PType->isFunctionType())
4115 PType = PVDecl->getType();
4116 getObjCEncodingForType(PType, S);
4117 S += charUnitsToString(ParmOffset);
4118 ParmOffset += getObjCEncodingTypeSize(PType);
4119 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004120
4121 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004122}
4123
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004124/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4125/// method parameter or return type. If Extended, include class names and
4126/// block object types.
4127void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4128 QualType T, std::string& S,
4129 bool Extended) const {
4130 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4131 getObjCEncodingForTypeQualifier(QT, S);
4132 // Encode parameter type.
4133 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4134 true /*OutermostType*/,
4135 false /*EncodingProperty*/,
4136 false /*StructField*/,
4137 Extended /*EncodeBlockParameters*/,
4138 Extended /*EncodeClassNames*/);
4139}
4140
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004141/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004142/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004143bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004144 std::string& S,
4145 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004146 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004147 // Encode return type.
4148 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4149 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004150 // Compute size of all parameters.
4151 // Start with computing size of a pointer in number of bytes.
4152 // FIXME: There might(should) be a better way of doing this computation!
4153 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004154 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004155 // The first two arguments (self and _cmd) are pointers; account for
4156 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004157 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004158 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004159 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004160 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004161 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004162 if (sz.isZero())
4163 return true;
4164
Ken Dyck40775002010-01-11 17:06:35 +00004165 assert (sz.isPositive() &&
4166 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004167 ParmOffset += sz;
4168 }
Ken Dyck40775002010-01-11 17:06:35 +00004169 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004170 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004171 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004172
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004173 // Argument types.
4174 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004175 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004176 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004177 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004178 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004179 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004180 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4181 // Use array's original type only if it has known number of
4182 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004183 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004184 PType = PVDecl->getType();
4185 } else if (PType->isFunctionType())
4186 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004187 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4188 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004189 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004190 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004191 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004192
4193 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004194}
4195
Daniel Dunbar4932b362008-08-28 04:38:10 +00004196/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004197/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004198/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4199/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004200/// Property attributes are stored as a comma-delimited C string. The simple
4201/// attributes readonly and bycopy are encoded as single characters. The
4202/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4203/// encoded as single characters, followed by an identifier. Property types
4204/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004205/// these attributes are defined by the following enumeration:
4206/// @code
4207/// enum PropertyAttributes {
4208/// kPropertyReadOnly = 'R', // property is read-only.
4209/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4210/// kPropertyByref = '&', // property is a reference to the value last assigned
4211/// kPropertyDynamic = 'D', // property is dynamic
4212/// kPropertyGetter = 'G', // followed by getter selector name
4213/// kPropertySetter = 'S', // followed by setter selector name
4214/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00004215/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004216/// kPropertyWeak = 'W' // 'weak' property
4217/// kPropertyStrong = 'P' // property GC'able
4218/// kPropertyNonAtomic = 'N' // property non-atomic
4219/// };
4220/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004221void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004222 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004223 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004224 // Collect information from the property implementation decl(s).
4225 bool Dynamic = false;
4226 ObjCPropertyImplDecl *SynthesizePID = 0;
4227
4228 // FIXME: Duplicated code due to poor abstraction.
4229 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004230 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004231 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4232 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004233 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004234 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004235 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004236 if (PID->getPropertyDecl() == PD) {
4237 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4238 Dynamic = true;
4239 } else {
4240 SynthesizePID = PID;
4241 }
4242 }
4243 }
4244 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004245 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004246 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004247 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004248 i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004249 ObjCPropertyImplDecl *PID = *i;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004250 if (PID->getPropertyDecl() == PD) {
4251 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4252 Dynamic = true;
4253 } else {
4254 SynthesizePID = PID;
4255 }
4256 }
Mike Stump11289f42009-09-09 15:08:12 +00004257 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004258 }
4259 }
4260
4261 // FIXME: This is not very efficient.
4262 S = "T";
4263
4264 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004265 // GCC has some special rules regarding encoding of properties which
4266 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004267 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004268 true /* outermost type */,
4269 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004270
4271 if (PD->isReadOnly()) {
4272 S += ",R";
4273 } else {
4274 switch (PD->getSetterKind()) {
4275 case ObjCPropertyDecl::Assign: break;
4276 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004277 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004278 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004279 }
4280 }
4281
4282 // It really isn't clear at all what this means, since properties
4283 // are "dynamic by default".
4284 if (Dynamic)
4285 S += ",D";
4286
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004287 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4288 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004289
Daniel Dunbar4932b362008-08-28 04:38:10 +00004290 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4291 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004292 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004293 }
4294
4295 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4296 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004297 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004298 }
4299
4300 if (SynthesizePID) {
4301 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4302 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004303 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004304 }
4305
4306 // FIXME: OBJCGC: weak & strong
4307}
4308
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004309/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004310/// Another legacy compatibility encoding: 32-bit longs are encoded as
4311/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004312/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4313///
4314void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004315 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004316 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004317 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004318 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004319 else
Jay Foad39c79802011-01-12 09:06:06 +00004320 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004321 PointeeTy = IntTy;
4322 }
4323 }
4324}
4325
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004326void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004327 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004328 // We follow the behavior of gcc, expanding structures which are
4329 // directly pointed to, and expanding embedded structures. Note that
4330 // these rules are sufficient to prevent recursive encoding of the
4331 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004332 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004333 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004334}
4335
David Chisnallb190a2c2010-06-04 01:10:52 +00004336static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4337 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004338 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004339 case BuiltinType::Void: return 'v';
4340 case BuiltinType::Bool: return 'B';
4341 case BuiltinType::Char_U:
4342 case BuiltinType::UChar: return 'C';
4343 case BuiltinType::UShort: return 'S';
4344 case BuiltinType::UInt: return 'I';
4345 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004346 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004347 case BuiltinType::UInt128: return 'T';
4348 case BuiltinType::ULongLong: return 'Q';
4349 case BuiltinType::Char_S:
4350 case BuiltinType::SChar: return 'c';
4351 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004352 case BuiltinType::WChar_S:
4353 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004354 case BuiltinType::Int: return 'i';
4355 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004356 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004357 case BuiltinType::LongLong: return 'q';
4358 case BuiltinType::Int128: return 't';
4359 case BuiltinType::Float: return 'f';
4360 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004361 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004362 }
4363}
4364
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004365static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4366 EnumDecl *Enum = ET->getDecl();
4367
4368 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4369 if (!Enum->isFixed())
4370 return 'i';
4371
4372 // The encoding of a fixed enum type matches its fixed underlying type.
4373 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4374}
4375
Jay Foad39c79802011-01-12 09:06:06 +00004376static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004377 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004378 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004379 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004380 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4381 // The GNU runtime requires more information; bitfields are encoded as b,
4382 // then the offset (in bits) of the first element, then the type of the
4383 // bitfield, then the size in bits. For example, in this structure:
4384 //
4385 // struct
4386 // {
4387 // int integer;
4388 // int flags:2;
4389 // };
4390 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4391 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4392 // information is not especially sensible, but we're stuck with it for
4393 // compatibility with GCC, although providing it breaks anything that
4394 // actually uses runtime introspection and wants to work on both runtimes...
David Blaikiebbafb8a2012-03-11 07:00:24 +00004395 if (!Ctx->getLangOpts().NeXTRuntime) {
David Chisnallb190a2c2010-06-04 01:10:52 +00004396 const RecordDecl *RD = FD->getParent();
4397 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004398 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004399 if (const EnumType *ET = T->getAs<EnumType>())
4400 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004401 else
Jay Foad39c79802011-01-12 09:06:06 +00004402 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004403 }
Richard Smithcaf33902011-10-10 18:28:20 +00004404 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004405}
4406
Daniel Dunbar07d07852009-10-18 21:17:35 +00004407// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004408void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4409 bool ExpandPointedToStructures,
4410 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004411 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004412 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004413 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004414 bool StructField,
4415 bool EncodeBlockParameters,
4416 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004417 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004418 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004419 return EncodeBitField(this, S, T, FD);
4420 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004421 return;
4422 }
Mike Stump11289f42009-09-09 15:08:12 +00004423
John McCall9dd450b2009-09-21 23:43:11 +00004424 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004425 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004426 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004427 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004428 return;
4429 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004430
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004431 // encoding for pointer or r3eference types.
4432 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004433 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004434 if (PT->isObjCSelType()) {
4435 S += ':';
4436 return;
4437 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004438 PointeeTy = PT->getPointeeType();
4439 }
4440 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4441 PointeeTy = RT->getPointeeType();
4442 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004443 bool isReadOnly = false;
4444 // For historical/compatibility reasons, the read-only qualifier of the
4445 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4446 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004447 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004448 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004449 if (OutermostType && T.isConstQualified()) {
4450 isReadOnly = true;
4451 S += 'r';
4452 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004453 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004454 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004455 while (P->getAs<PointerType>())
4456 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004457 if (P.isConstQualified()) {
4458 isReadOnly = true;
4459 S += 'r';
4460 }
4461 }
4462 if (isReadOnly) {
4463 // Another legacy compatibility encoding. Some ObjC qualifier and type
4464 // combinations need to be rearranged.
4465 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004466 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004467 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004468 }
Mike Stump11289f42009-09-09 15:08:12 +00004469
Anders Carlssond8499822007-10-29 05:01:08 +00004470 if (PointeeTy->isCharType()) {
4471 // char pointer types should be encoded as '*' unless it is a
4472 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004473 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004474 S += '*';
4475 return;
4476 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004477 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004478 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4479 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4480 S += '#';
4481 return;
4482 }
4483 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4484 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4485 S += '@';
4486 return;
4487 }
4488 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004489 }
Anders Carlssond8499822007-10-29 05:01:08 +00004490 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004491 getLegacyIntegralTypeEncoding(PointeeTy);
4492
Mike Stump11289f42009-09-09 15:08:12 +00004493 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004494 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004495 return;
4496 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004497
Chris Lattnere7cabb92009-07-13 00:10:46 +00004498 if (const ArrayType *AT =
4499 // Ignore type qualifiers etc.
4500 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004501 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004502 // Incomplete arrays are encoded as a pointer to the array element.
4503 S += '^';
4504
Mike Stump11289f42009-09-09 15:08:12 +00004505 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004506 false, ExpandStructures, FD);
4507 } else {
4508 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004509
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004510 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4511 if (getTypeSize(CAT->getElementType()) == 0)
4512 S += '0';
4513 else
4514 S += llvm::utostr(CAT->getSize().getZExtValue());
4515 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004516 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004517 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4518 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004519 S += '0';
4520 }
Mike Stump11289f42009-09-09 15:08:12 +00004521
4522 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004523 false, ExpandStructures, FD);
4524 S += ']';
4525 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004526 return;
4527 }
Mike Stump11289f42009-09-09 15:08:12 +00004528
John McCall9dd450b2009-09-21 23:43:11 +00004529 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004530 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004531 return;
4532 }
Mike Stump11289f42009-09-09 15:08:12 +00004533
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004534 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004535 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004536 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004537 // Anonymous structures print as '?'
4538 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4539 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004540 if (ClassTemplateSpecializationDecl *Spec
4541 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4542 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4543 std::string TemplateArgsStr
4544 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004545 TemplateArgs.data(),
4546 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004547 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004548
4549 S += TemplateArgsStr;
4550 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004551 } else {
4552 S += '?';
4553 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004554 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004555 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004556 if (!RDecl->isUnion()) {
4557 getObjCEncodingForStructureImpl(RDecl, S, FD);
4558 } else {
4559 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4560 FieldEnd = RDecl->field_end();
4561 Field != FieldEnd; ++Field) {
4562 if (FD) {
4563 S += '"';
4564 S += Field->getNameAsString();
4565 S += '"';
4566 }
Mike Stump11289f42009-09-09 15:08:12 +00004567
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004568 // Special case bit-fields.
4569 if (Field->isBitField()) {
4570 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
David Blaikie40ed2972012-06-06 20:45:41 +00004571 *Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004572 } else {
4573 QualType qt = Field->getType();
4574 getLegacyIntegralTypeEncoding(qt);
4575 getObjCEncodingForTypeImpl(qt, S, false, true,
4576 FD, /*OutermostType*/false,
4577 /*EncodingProperty*/false,
4578 /*StructField*/true);
4579 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004580 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004581 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004582 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004583 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004584 return;
4585 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004586
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004587 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004588 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004589 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004590 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004591 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004592 return;
4593 }
Mike Stump11289f42009-09-09 15:08:12 +00004594
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004595 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004596 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004597 if (EncodeBlockParameters) {
4598 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4599
4600 S += '<';
4601 // Block return type
4602 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4603 ExpandPointedToStructures, ExpandStructures,
4604 FD,
4605 false /* OutermostType */,
4606 EncodingProperty,
4607 false /* StructField */,
4608 EncodeBlockParameters,
4609 EncodeClassNames);
4610 // Block self
4611 S += "@?";
4612 // Block parameters
4613 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4614 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4615 E = FPT->arg_type_end(); I && (I != E); ++I) {
4616 getObjCEncodingForTypeImpl(*I, S,
4617 ExpandPointedToStructures,
4618 ExpandStructures,
4619 FD,
4620 false /* OutermostType */,
4621 EncodingProperty,
4622 false /* StructField */,
4623 EncodeBlockParameters,
4624 EncodeClassNames);
4625 }
4626 }
4627 S += '>';
4628 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004629 return;
4630 }
Mike Stump11289f42009-09-09 15:08:12 +00004631
John McCall8b07ec22010-05-15 11:32:37 +00004632 // Ignore protocol qualifiers when mangling at this level.
4633 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4634 T = OT->getBaseType();
4635
John McCall8ccfcb52009-09-24 19:53:00 +00004636 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004637 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004638 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004639 S += '{';
4640 const IdentifierInfo *II = OI->getIdentifier();
4641 S += II->getName();
4642 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004643 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004644 DeepCollectObjCIvars(OI, true, Ivars);
4645 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004646 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004647 if (Field->isBitField())
4648 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004649 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004650 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004651 }
4652 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004653 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004654 }
Mike Stump11289f42009-09-09 15:08:12 +00004655
John McCall9dd450b2009-09-21 23:43:11 +00004656 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004657 if (OPT->isObjCIdType()) {
4658 S += '@';
4659 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004660 }
Mike Stump11289f42009-09-09 15:08:12 +00004661
Steve Narofff0c86112009-10-28 22:03:49 +00004662 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4663 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4664 // Since this is a binary compatibility issue, need to consult with runtime
4665 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004666 S += '#';
4667 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004668 }
Mike Stump11289f42009-09-09 15:08:12 +00004669
Chris Lattnere7cabb92009-07-13 00:10:46 +00004670 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004671 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004672 ExpandPointedToStructures,
4673 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004674 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004675 // Note that we do extended encoding of protocol qualifer list
4676 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004677 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004678 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4679 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004680 S += '<';
4681 S += (*I)->getNameAsString();
4682 S += '>';
4683 }
4684 S += '"';
4685 }
4686 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004687 }
Mike Stump11289f42009-09-09 15:08:12 +00004688
Chris Lattnere7cabb92009-07-13 00:10:46 +00004689 QualType PointeeTy = OPT->getPointeeType();
4690 if (!EncodingProperty &&
4691 isa<TypedefType>(PointeeTy.getTypePtr())) {
4692 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004693 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004694 // {...};
4695 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004696 getObjCEncodingForTypeImpl(PointeeTy, S,
4697 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004698 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004699 return;
4700 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004701
4702 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004703 if (OPT->getInterfaceDecl() &&
4704 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004705 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004706 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004707 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4708 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004709 S += '<';
4710 S += (*I)->getNameAsString();
4711 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004712 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004713 S += '"';
4714 }
4715 return;
4716 }
Mike Stump11289f42009-09-09 15:08:12 +00004717
John McCalla9e6e8d2010-05-17 23:56:34 +00004718 // gcc just blithely ignores member pointers.
4719 // TODO: maybe there should be a mangling for these
4720 if (T->getAs<MemberPointerType>())
4721 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004722
4723 if (T->isVectorType()) {
4724 // This matches gcc's encoding, even though technically it is
4725 // insufficient.
4726 // FIXME. We should do a better job than gcc.
4727 return;
4728 }
4729
David Blaikie83d382b2011-09-23 05:06:16 +00004730 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004731}
4732
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004733void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4734 std::string &S,
4735 const FieldDecl *FD,
4736 bool includeVBases) const {
4737 assert(RDecl && "Expected non-null RecordDecl");
4738 assert(!RDecl->isUnion() && "Should not be called for unions");
4739 if (!RDecl->getDefinition())
4740 return;
4741
4742 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4743 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4744 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4745
4746 if (CXXRec) {
4747 for (CXXRecordDecl::base_class_iterator
4748 BI = CXXRec->bases_begin(),
4749 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4750 if (!BI->isVirtual()) {
4751 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004752 if (base->isEmpty())
4753 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004754 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4755 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4756 std::make_pair(offs, base));
4757 }
4758 }
4759 }
4760
4761 unsigned i = 0;
4762 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4763 FieldEnd = RDecl->field_end();
4764 Field != FieldEnd; ++Field, ++i) {
4765 uint64_t offs = layout.getFieldOffset(i);
4766 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
David Blaikie40ed2972012-06-06 20:45:41 +00004767 std::make_pair(offs, *Field));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004768 }
4769
4770 if (CXXRec && includeVBases) {
4771 for (CXXRecordDecl::base_class_iterator
4772 BI = CXXRec->vbases_begin(),
4773 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4774 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004775 if (base->isEmpty())
4776 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004777 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004778 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4779 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4780 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004781 }
4782 }
4783
4784 CharUnits size;
4785 if (CXXRec) {
4786 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4787 } else {
4788 size = layout.getSize();
4789 }
4790
4791 uint64_t CurOffs = 0;
4792 std::multimap<uint64_t, NamedDecl *>::iterator
4793 CurLayObj = FieldOrBaseOffsets.begin();
4794
Douglas Gregorf5d6c742012-04-27 22:30:01 +00004795 if (CXXRec && CXXRec->isDynamicClass() &&
4796 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004797 if (FD) {
4798 S += "\"_vptr$";
4799 std::string recname = CXXRec->getNameAsString();
4800 if (recname.empty()) recname = "?";
4801 S += recname;
4802 S += '"';
4803 }
4804 S += "^^?";
4805 CurOffs += getTypeSize(VoidPtrTy);
4806 }
4807
4808 if (!RDecl->hasFlexibleArrayMember()) {
4809 // Mark the end of the structure.
4810 uint64_t offs = toBits(size);
4811 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4812 std::make_pair(offs, (NamedDecl*)0));
4813 }
4814
4815 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4816 assert(CurOffs <= CurLayObj->first);
4817
4818 if (CurOffs < CurLayObj->first) {
4819 uint64_t padding = CurLayObj->first - CurOffs;
4820 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4821 // packing/alignment of members is different that normal, in which case
4822 // the encoding will be out-of-sync with the real layout.
4823 // If the runtime switches to just consider the size of types without
4824 // taking into account alignment, we could make padding explicit in the
4825 // encoding (e.g. using arrays of chars). The encoding strings would be
4826 // longer then though.
4827 CurOffs += padding;
4828 }
4829
4830 NamedDecl *dcl = CurLayObj->second;
4831 if (dcl == 0)
4832 break; // reached end of structure.
4833
4834 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4835 // We expand the bases without their virtual bases since those are going
4836 // in the initial structure. Note that this differs from gcc which
4837 // expands virtual bases each time one is encountered in the hierarchy,
4838 // making the encoding type bigger than it really is.
4839 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004840 assert(!base->isEmpty());
4841 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004842 } else {
4843 FieldDecl *field = cast<FieldDecl>(dcl);
4844 if (FD) {
4845 S += '"';
4846 S += field->getNameAsString();
4847 S += '"';
4848 }
4849
4850 if (field->isBitField()) {
4851 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004852 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004853 } else {
4854 QualType qt = field->getType();
4855 getLegacyIntegralTypeEncoding(qt);
4856 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4857 /*OutermostType*/false,
4858 /*EncodingProperty*/false,
4859 /*StructField*/true);
4860 CurOffs += getTypeSize(field->getType());
4861 }
4862 }
4863 }
4864}
4865
Mike Stump11289f42009-09-09 15:08:12 +00004866void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004867 std::string& S) const {
4868 if (QT & Decl::OBJC_TQ_In)
4869 S += 'n';
4870 if (QT & Decl::OBJC_TQ_Inout)
4871 S += 'N';
4872 if (QT & Decl::OBJC_TQ_Out)
4873 S += 'o';
4874 if (QT & Decl::OBJC_TQ_Bycopy)
4875 S += 'O';
4876 if (QT & Decl::OBJC_TQ_Byref)
4877 S += 'R';
4878 if (QT & Decl::OBJC_TQ_Oneway)
4879 S += 'V';
4880}
4881
Chris Lattnere7cabb92009-07-13 00:10:46 +00004882void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004883 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004884
Anders Carlsson87c149b2007-10-11 01:00:40 +00004885 BuiltinVaListType = T;
4886}
4887
Douglas Gregor3ea72692011-08-12 05:46:01 +00004888TypedefDecl *ASTContext::getObjCIdDecl() const {
4889 if (!ObjCIdDecl) {
4890 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4891 T = getObjCObjectPointerType(T);
4892 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4893 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4894 getTranslationUnitDecl(),
4895 SourceLocation(), SourceLocation(),
4896 &Idents.get("id"), IdInfo);
4897 }
4898
4899 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004900}
4901
Douglas Gregor52e02802011-08-12 06:17:30 +00004902TypedefDecl *ASTContext::getObjCSelDecl() const {
4903 if (!ObjCSelDecl) {
4904 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4905 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4906 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4907 getTranslationUnitDecl(),
4908 SourceLocation(), SourceLocation(),
4909 &Idents.get("SEL"), SelInfo);
4910 }
4911 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004912}
4913
Douglas Gregor0a586182011-08-12 05:59:41 +00004914TypedefDecl *ASTContext::getObjCClassDecl() const {
4915 if (!ObjCClassDecl) {
4916 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4917 T = getObjCObjectPointerType(T);
4918 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4919 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4920 getTranslationUnitDecl(),
4921 SourceLocation(), SourceLocation(),
4922 &Idents.get("Class"), ClassInfo);
4923 }
4924
4925 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004926}
4927
Douglas Gregord53ae832012-01-17 18:09:05 +00004928ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4929 if (!ObjCProtocolClassDecl) {
4930 ObjCProtocolClassDecl
4931 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4932 SourceLocation(),
4933 &Idents.get("Protocol"),
4934 /*PrevDecl=*/0,
4935 SourceLocation(), true);
4936 }
4937
4938 return ObjCProtocolClassDecl;
4939}
4940
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004941void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004942 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004943 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004944
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004945 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004946}
4947
John McCalld28ae272009-12-02 08:04:21 +00004948/// \brief Retrieve the template name that corresponds to a non-empty
4949/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004950TemplateName
4951ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4952 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004953 unsigned size = End - Begin;
4954 assert(size > 1 && "set is not overloaded!");
4955
4956 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4957 size * sizeof(FunctionTemplateDecl*));
4958 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4959
4960 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004961 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004962 NamedDecl *D = *I;
4963 assert(isa<FunctionTemplateDecl>(D) ||
4964 (isa<UsingShadowDecl>(D) &&
4965 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4966 *Storage++ = D;
4967 }
4968
4969 return TemplateName(OT);
4970}
4971
Douglas Gregordc572a32009-03-30 22:58:21 +00004972/// \brief Retrieve the template name that represents a qualified
4973/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004974TemplateName
4975ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4976 bool TemplateKeyword,
4977 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004978 assert(NNS && "Missing nested-name-specifier in qualified template name");
4979
Douglas Gregorc42075a2010-02-04 18:10:26 +00004980 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004981 llvm::FoldingSetNodeID ID;
4982 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4983
4984 void *InsertPos = 0;
4985 QualifiedTemplateName *QTN =
4986 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4987 if (!QTN) {
4988 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4989 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4990 }
4991
4992 return TemplateName(QTN);
4993}
4994
4995/// \brief Retrieve the template name that represents a dependent
4996/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004997TemplateName
4998ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4999 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00005000 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00005001 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00005002
5003 llvm::FoldingSetNodeID ID;
5004 DependentTemplateName::Profile(ID, NNS, Name);
5005
5006 void *InsertPos = 0;
5007 DependentTemplateName *QTN =
5008 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5009
5010 if (QTN)
5011 return TemplateName(QTN);
5012
5013 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5014 if (CanonNNS == NNS) {
5015 QTN = new (*this,4) DependentTemplateName(NNS, Name);
5016 } else {
5017 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5018 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005019 DependentTemplateName *CheckQTN =
5020 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5021 assert(!CheckQTN && "Dependent type name canonicalization broken");
5022 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005023 }
5024
5025 DependentTemplateNames.InsertNode(QTN, InsertPos);
5026 return TemplateName(QTN);
5027}
5028
Douglas Gregor71395fa2009-11-04 00:56:37 +00005029/// \brief Retrieve the template name that represents a dependent
5030/// template name such as \c MetaFun::template operator+.
5031TemplateName
5032ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005033 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005034 assert((!NNS || NNS->isDependent()) &&
5035 "Nested name specifier must be dependent");
5036
5037 llvm::FoldingSetNodeID ID;
5038 DependentTemplateName::Profile(ID, NNS, Operator);
5039
5040 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005041 DependentTemplateName *QTN
5042 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005043
5044 if (QTN)
5045 return TemplateName(QTN);
5046
5047 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5048 if (CanonNNS == NNS) {
5049 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5050 } else {
5051 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5052 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005053
5054 DependentTemplateName *CheckQTN
5055 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5056 assert(!CheckQTN && "Dependent template name canonicalization broken");
5057 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005058 }
5059
5060 DependentTemplateNames.InsertNode(QTN, InsertPos);
5061 return TemplateName(QTN);
5062}
5063
Douglas Gregor5590be02011-01-15 06:45:20 +00005064TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005065ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5066 TemplateName replacement) const {
5067 llvm::FoldingSetNodeID ID;
5068 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5069
5070 void *insertPos = 0;
5071 SubstTemplateTemplateParmStorage *subst
5072 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5073
5074 if (!subst) {
5075 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5076 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5077 }
5078
5079 return TemplateName(subst);
5080}
5081
5082TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005083ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5084 const TemplateArgument &ArgPack) const {
5085 ASTContext &Self = const_cast<ASTContext &>(*this);
5086 llvm::FoldingSetNodeID ID;
5087 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5088
5089 void *InsertPos = 0;
5090 SubstTemplateTemplateParmPackStorage *Subst
5091 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5092
5093 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005094 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005095 ArgPack.pack_size(),
5096 ArgPack.pack_begin());
5097 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5098 }
5099
5100 return TemplateName(Subst);
5101}
5102
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005103/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005104/// TargetInfo, produce the corresponding type. The unsigned @p Type
5105/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005106CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005107 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005108 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005109 case TargetInfo::SignedShort: return ShortTy;
5110 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5111 case TargetInfo::SignedInt: return IntTy;
5112 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5113 case TargetInfo::SignedLong: return LongTy;
5114 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5115 case TargetInfo::SignedLongLong: return LongLongTy;
5116 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5117 }
5118
David Blaikie83d382b2011-09-23 05:06:16 +00005119 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005120}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005121
5122//===----------------------------------------------------------------------===//
5123// Type Predicates.
5124//===----------------------------------------------------------------------===//
5125
Fariborz Jahanian96207692009-02-18 21:49:28 +00005126/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5127/// garbage collection attribute.
5128///
John McCall553d45a2011-01-12 00:34:59 +00005129Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005130 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005131 return Qualifiers::GCNone;
5132
David Blaikiebbafb8a2012-03-11 07:00:24 +00005133 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00005134 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5135
5136 // Default behaviour under objective-C's gc is for ObjC pointers
5137 // (or pointers to them) be treated as though they were declared
5138 // as __strong.
5139 if (GCAttrs == Qualifiers::GCNone) {
5140 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5141 return Qualifiers::Strong;
5142 else if (Ty->isPointerType())
5143 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5144 } else {
5145 // It's not valid to set GC attributes on anything that isn't a
5146 // pointer.
5147#ifndef NDEBUG
5148 QualType CT = Ty->getCanonicalTypeInternal();
5149 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5150 CT = AT->getElementType();
5151 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5152#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005153 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005154 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005155}
5156
Chris Lattner49af6a42008-04-07 06:51:04 +00005157//===----------------------------------------------------------------------===//
5158// Type Compatibility Testing
5159//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005160
Mike Stump11289f42009-09-09 15:08:12 +00005161/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005162/// compatible.
5163static bool areCompatVectorTypes(const VectorType *LHS,
5164 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005165 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005166 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005167 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005168}
5169
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005170bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5171 QualType SecondVec) {
5172 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5173 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5174
5175 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5176 return true;
5177
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005178 // Treat Neon vector types and most AltiVec vector types as if they are the
5179 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005180 const VectorType *First = FirstVec->getAs<VectorType>();
5181 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005182 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005183 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005184 First->getVectorKind() != VectorType::AltiVecPixel &&
5185 First->getVectorKind() != VectorType::AltiVecBool &&
5186 Second->getVectorKind() != VectorType::AltiVecPixel &&
5187 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005188 return true;
5189
5190 return false;
5191}
5192
Steve Naroff8e6aee52009-07-23 01:01:38 +00005193//===----------------------------------------------------------------------===//
5194// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5195//===----------------------------------------------------------------------===//
5196
5197/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5198/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005199bool
5200ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5201 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005202 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005203 return true;
5204 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5205 E = rProto->protocol_end(); PI != E; ++PI)
5206 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5207 return true;
5208 return false;
5209}
5210
Steve Naroff8e6aee52009-07-23 01:01:38 +00005211/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5212/// return true if lhs's protocols conform to rhs's protocol; false
5213/// otherwise.
5214bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5215 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5216 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5217 return false;
5218}
5219
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005220/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5221/// Class<p1, ...>.
5222bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5223 QualType rhs) {
5224 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5225 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5226 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5227
5228 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5229 E = lhsQID->qual_end(); I != E; ++I) {
5230 bool match = false;
5231 ObjCProtocolDecl *lhsProto = *I;
5232 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5233 E = rhsOPT->qual_end(); J != E; ++J) {
5234 ObjCProtocolDecl *rhsProto = *J;
5235 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5236 match = true;
5237 break;
5238 }
5239 }
5240 if (!match)
5241 return false;
5242 }
5243 return true;
5244}
5245
Steve Naroff8e6aee52009-07-23 01:01:38 +00005246/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5247/// ObjCQualifiedIDType.
5248bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5249 bool compare) {
5250 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005251 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005252 lhs->isObjCIdType() || lhs->isObjCClassType())
5253 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005254 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005255 rhs->isObjCIdType() || rhs->isObjCClassType())
5256 return true;
5257
5258 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005259 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005260
Steve Naroff8e6aee52009-07-23 01:01:38 +00005261 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005262
Steve Naroff8e6aee52009-07-23 01:01:38 +00005263 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005264 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005265 // make sure we check the class hierarchy.
5266 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5267 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5268 E = lhsQID->qual_end(); I != E; ++I) {
5269 // when comparing an id<P> on lhs with a static type on rhs,
5270 // see if static class implements all of id's protocols, directly or
5271 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005272 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005273 return false;
5274 }
5275 }
5276 // If there are no qualifiers and no interface, we have an 'id'.
5277 return true;
5278 }
Mike Stump11289f42009-09-09 15:08:12 +00005279 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005280 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5281 E = lhsQID->qual_end(); I != E; ++I) {
5282 ObjCProtocolDecl *lhsProto = *I;
5283 bool match = false;
5284
5285 // when comparing an id<P> on lhs with a static type on rhs,
5286 // see if static class implements all of id's protocols, directly or
5287 // through its super class and categories.
5288 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5289 E = rhsOPT->qual_end(); J != E; ++J) {
5290 ObjCProtocolDecl *rhsProto = *J;
5291 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5292 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5293 match = true;
5294 break;
5295 }
5296 }
Mike Stump11289f42009-09-09 15:08:12 +00005297 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005298 // make sure we check the class hierarchy.
5299 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5300 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5301 E = lhsQID->qual_end(); I != E; ++I) {
5302 // when comparing an id<P> on lhs with a static type on rhs,
5303 // see if static class implements all of id's protocols, directly or
5304 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005305 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005306 match = true;
5307 break;
5308 }
5309 }
5310 }
5311 if (!match)
5312 return false;
5313 }
Mike Stump11289f42009-09-09 15:08:12 +00005314
Steve Naroff8e6aee52009-07-23 01:01:38 +00005315 return true;
5316 }
Mike Stump11289f42009-09-09 15:08:12 +00005317
Steve Naroff8e6aee52009-07-23 01:01:38 +00005318 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5319 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5320
Mike Stump11289f42009-09-09 15:08:12 +00005321 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005322 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005323 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005324 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5325 E = lhsOPT->qual_end(); I != E; ++I) {
5326 ObjCProtocolDecl *lhsProto = *I;
5327 bool match = false;
5328
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005329 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005330 // see if static class implements all of id's protocols, directly or
5331 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005332 // First, lhs protocols in the qualifier list must be found, direct
5333 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005334 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5335 E = rhsQID->qual_end(); J != E; ++J) {
5336 ObjCProtocolDecl *rhsProto = *J;
5337 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5338 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5339 match = true;
5340 break;
5341 }
5342 }
5343 if (!match)
5344 return false;
5345 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005346
5347 // Static class's protocols, or its super class or category protocols
5348 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5349 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5350 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5351 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5352 // This is rather dubious but matches gcc's behavior. If lhs has
5353 // no type qualifier and its class has no static protocol(s)
5354 // assume that it is mismatch.
5355 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5356 return false;
5357 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5358 LHSInheritedProtocols.begin(),
5359 E = LHSInheritedProtocols.end(); I != E; ++I) {
5360 bool match = false;
5361 ObjCProtocolDecl *lhsProto = (*I);
5362 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5363 E = rhsQID->qual_end(); J != E; ++J) {
5364 ObjCProtocolDecl *rhsProto = *J;
5365 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5366 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5367 match = true;
5368 break;
5369 }
5370 }
5371 if (!match)
5372 return false;
5373 }
5374 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005375 return true;
5376 }
5377 return false;
5378}
5379
Eli Friedman47f77112008-08-22 00:56:42 +00005380/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005381/// compatible for assignment from RHS to LHS. This handles validation of any
5382/// protocol qualifiers on the LHS or RHS.
5383///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005384bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5385 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005386 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5387 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5388
Steve Naroff1329fa02009-07-15 18:40:39 +00005389 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005390 if (LHS->isObjCUnqualifiedIdOrClass() ||
5391 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005392 return true;
5393
John McCall8b07ec22010-05-15 11:32:37 +00005394 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005395 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5396 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005397 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005398
5399 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5400 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5401 QualType(RHSOPT,0));
5402
John McCall8b07ec22010-05-15 11:32:37 +00005403 // If we have 2 user-defined types, fall into that path.
5404 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005405 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005406
Steve Naroff8e6aee52009-07-23 01:01:38 +00005407 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005408}
5409
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005410/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005411/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005412/// arguments in block literals. When passed as arguments, passing 'A*' where
5413/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5414/// not OK. For the return type, the opposite is not OK.
5415bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5416 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005417 const ObjCObjectPointerType *RHSOPT,
5418 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005419 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005420 return true;
5421
5422 if (LHSOPT->isObjCBuiltinType()) {
5423 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5424 }
5425
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005426 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005427 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5428 QualType(RHSOPT,0),
5429 false);
5430
5431 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5432 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5433 if (LHS && RHS) { // We have 2 user-defined types.
5434 if (LHS != RHS) {
5435 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005436 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005437 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005438 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005439 }
5440 else
5441 return true;
5442 }
5443 return false;
5444}
5445
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005446/// getIntersectionOfProtocols - This routine finds the intersection of set
5447/// of protocols inherited from two distinct objective-c pointer objects.
5448/// It is used to build composite qualifier list of the composite type of
5449/// the conditional expression involving two objective-c pointer objects.
5450static
5451void getIntersectionOfProtocols(ASTContext &Context,
5452 const ObjCObjectPointerType *LHSOPT,
5453 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005454 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005455
John McCall8b07ec22010-05-15 11:32:37 +00005456 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5457 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5458 assert(LHS->getInterface() && "LHS must have an interface base");
5459 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005460
5461 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5462 unsigned LHSNumProtocols = LHS->getNumProtocols();
5463 if (LHSNumProtocols > 0)
5464 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5465 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005466 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005467 Context.CollectInheritedProtocols(LHS->getInterface(),
5468 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005469 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5470 LHSInheritedProtocols.end());
5471 }
5472
5473 unsigned RHSNumProtocols = RHS->getNumProtocols();
5474 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005475 ObjCProtocolDecl **RHSProtocols =
5476 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005477 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5478 if (InheritedProtocolSet.count(RHSProtocols[i]))
5479 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005480 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005481 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005482 Context.CollectInheritedProtocols(RHS->getInterface(),
5483 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005484 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5485 RHSInheritedProtocols.begin(),
5486 E = RHSInheritedProtocols.end(); I != E; ++I)
5487 if (InheritedProtocolSet.count((*I)))
5488 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005489 }
5490}
5491
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005492/// areCommonBaseCompatible - Returns common base class of the two classes if
5493/// one found. Note that this is O'2 algorithm. But it will be called as the
5494/// last type comparison in a ?-exp of ObjC pointer types before a
5495/// warning is issued. So, its invokation is extremely rare.
5496QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005497 const ObjCObjectPointerType *Lptr,
5498 const ObjCObjectPointerType *Rptr) {
5499 const ObjCObjectType *LHS = Lptr->getObjectType();
5500 const ObjCObjectType *RHS = Rptr->getObjectType();
5501 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5502 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005503 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005504 return QualType();
5505
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005506 do {
John McCall8b07ec22010-05-15 11:32:37 +00005507 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005508 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005509 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005510 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5511
5512 QualType Result = QualType(LHS, 0);
5513 if (!Protocols.empty())
5514 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5515 Result = getObjCObjectPointerType(Result);
5516 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005517 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005518 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005519
5520 return QualType();
5521}
5522
John McCall8b07ec22010-05-15 11:32:37 +00005523bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5524 const ObjCObjectType *RHS) {
5525 assert(LHS->getInterface() && "LHS is not an interface type");
5526 assert(RHS->getInterface() && "RHS is not an interface type");
5527
Chris Lattner49af6a42008-04-07 06:51:04 +00005528 // Verify that the base decls are compatible: the RHS must be a subclass of
5529 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005530 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005531 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005532
Chris Lattner49af6a42008-04-07 06:51:04 +00005533 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5534 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005535 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005536 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005537
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005538 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5539 // more detailed analysis is required.
5540 if (RHS->getNumProtocols() == 0) {
5541 // OK, if LHS is a superclass of RHS *and*
5542 // this superclass is assignment compatible with LHS.
5543 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005544 bool IsSuperClass =
5545 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5546 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005547 // OK if conversion of LHS to SuperClass results in narrowing of types
5548 // ; i.e., SuperClass may implement at least one of the protocols
5549 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5550 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5551 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005552 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005553 // If super class has no protocols, it is not a match.
5554 if (SuperClassInheritedProtocols.empty())
5555 return false;
5556
5557 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5558 LHSPE = LHS->qual_end();
5559 LHSPI != LHSPE; LHSPI++) {
5560 bool SuperImplementsProtocol = false;
5561 ObjCProtocolDecl *LHSProto = (*LHSPI);
5562
5563 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5564 SuperClassInheritedProtocols.begin(),
5565 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5566 ObjCProtocolDecl *SuperClassProto = (*I);
5567 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5568 SuperImplementsProtocol = true;
5569 break;
5570 }
5571 }
5572 if (!SuperImplementsProtocol)
5573 return false;
5574 }
5575 return true;
5576 }
5577 return false;
5578 }
Mike Stump11289f42009-09-09 15:08:12 +00005579
John McCall8b07ec22010-05-15 11:32:37 +00005580 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5581 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005582 LHSPI != LHSPE; LHSPI++) {
5583 bool RHSImplementsProtocol = false;
5584
5585 // If the RHS doesn't implement the protocol on the left, the types
5586 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005587 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5588 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005589 RHSPI != RHSPE; RHSPI++) {
5590 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005591 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005592 break;
5593 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005594 }
5595 // FIXME: For better diagnostics, consider passing back the protocol name.
5596 if (!RHSImplementsProtocol)
5597 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005598 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005599 // The RHS implements all protocols listed on the LHS.
5600 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005601}
5602
Steve Naroffb7605152009-02-12 17:52:19 +00005603bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5604 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005605 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5606 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005607
Steve Naroff7cae42b2009-07-10 23:34:53 +00005608 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005609 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005610
5611 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5612 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005613}
5614
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005615bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5616 return canAssignObjCInterfaces(
5617 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5618 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5619}
5620
Mike Stump11289f42009-09-09 15:08:12 +00005621/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005622/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005623/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005624/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005625bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5626 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005627 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00005628 return hasSameType(LHS, RHS);
5629
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005630 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005631}
5632
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005633bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005634 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005635}
5636
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005637bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5638 return !mergeTypes(LHS, RHS, true).isNull();
5639}
5640
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005641/// mergeTransparentUnionType - if T is a transparent union type and a member
5642/// of T is compatible with SubType, return the merged type, else return
5643/// QualType()
5644QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5645 bool OfBlockPointer,
5646 bool Unqualified) {
5647 if (const RecordType *UT = T->getAsUnionType()) {
5648 RecordDecl *UD = UT->getDecl();
5649 if (UD->hasAttr<TransparentUnionAttr>()) {
5650 for (RecordDecl::field_iterator it = UD->field_begin(),
5651 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005652 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005653 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5654 if (!MT.isNull())
5655 return MT;
5656 }
5657 }
5658 }
5659
5660 return QualType();
5661}
5662
5663/// mergeFunctionArgumentTypes - merge two types which appear as function
5664/// argument types
5665QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5666 bool OfBlockPointer,
5667 bool Unqualified) {
5668 // GNU extension: two types are compatible if they appear as a function
5669 // argument, one of the types is a transparent union type and the other
5670 // type is compatible with a union member
5671 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5672 Unqualified);
5673 if (!lmerge.isNull())
5674 return lmerge;
5675
5676 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5677 Unqualified);
5678 if (!rmerge.isNull())
5679 return rmerge;
5680
5681 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5682}
5683
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005684QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005685 bool OfBlockPointer,
5686 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005687 const FunctionType *lbase = lhs->getAs<FunctionType>();
5688 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005689 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5690 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005691 bool allLTypes = true;
5692 bool allRTypes = true;
5693
5694 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005695 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005696 if (OfBlockPointer) {
5697 QualType RHS = rbase->getResultType();
5698 QualType LHS = lbase->getResultType();
5699 bool UnqualifiedResult = Unqualified;
5700 if (!UnqualifiedResult)
5701 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005702 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005703 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005704 else
John McCall8c6b56f2010-12-15 01:06:38 +00005705 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5706 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005707 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005708
5709 if (Unqualified)
5710 retType = retType.getUnqualifiedType();
5711
5712 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5713 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5714 if (Unqualified) {
5715 LRetType = LRetType.getUnqualifiedType();
5716 RRetType = RRetType.getUnqualifiedType();
5717 }
5718
5719 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005720 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005721 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005722 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005723
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005724 // FIXME: double check this
5725 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5726 // rbase->getRegParmAttr() != 0 &&
5727 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005728 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5729 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005730
Douglas Gregor8c940862010-01-18 17:14:39 +00005731 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005732 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005733 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005734
John McCall8c6b56f2010-12-15 01:06:38 +00005735 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005736 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5737 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005738 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5739 return QualType();
5740
John McCall31168b02011-06-15 23:02:42 +00005741 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5742 return QualType();
5743
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005744 // functypes which return are preferred over those that do not.
5745 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5746 allLTypes = false;
5747 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5748 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005749 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5750 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00005751
John McCall31168b02011-06-15 23:02:42 +00005752 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005753
Eli Friedman47f77112008-08-22 00:56:42 +00005754 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005755 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5756 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005757 unsigned lproto_nargs = lproto->getNumArgs();
5758 unsigned rproto_nargs = rproto->getNumArgs();
5759
5760 // Compatible functions must have the same number of arguments
5761 if (lproto_nargs != rproto_nargs)
5762 return QualType();
5763
5764 // Variadic and non-variadic functions aren't compatible
5765 if (lproto->isVariadic() != rproto->isVariadic())
5766 return QualType();
5767
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005768 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5769 return QualType();
5770
Fariborz Jahanian97676972011-09-28 21:52:05 +00005771 if (LangOpts.ObjCAutoRefCount &&
5772 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5773 return QualType();
5774
Eli Friedman47f77112008-08-22 00:56:42 +00005775 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005776 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00005777 for (unsigned i = 0; i < lproto_nargs; i++) {
5778 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5779 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005780 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5781 OfBlockPointer,
5782 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005783 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005784
5785 if (Unqualified)
5786 argtype = argtype.getUnqualifiedType();
5787
Eli Friedman47f77112008-08-22 00:56:42 +00005788 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005789 if (Unqualified) {
5790 largtype = largtype.getUnqualifiedType();
5791 rargtype = rargtype.getUnqualifiedType();
5792 }
5793
Chris Lattner465fa322008-10-05 17:34:18 +00005794 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5795 allLTypes = false;
5796 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5797 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005798 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00005799
Eli Friedman47f77112008-08-22 00:56:42 +00005800 if (allLTypes) return lhs;
5801 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005802
5803 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5804 EPI.ExtInfo = einfo;
5805 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005806 }
5807
5808 if (lproto) allRTypes = false;
5809 if (rproto) allLTypes = false;
5810
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005811 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005812 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005813 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005814 if (proto->isVariadic()) return QualType();
5815 // Check that the types are compatible with the types that
5816 // would result from default argument promotions (C99 6.7.5.3p15).
5817 // The only types actually affected are promotable integer
5818 // types and floats, which would be passed as a different
5819 // type depending on whether the prototype is visible.
5820 unsigned proto_nargs = proto->getNumArgs();
5821 for (unsigned i = 0; i < proto_nargs; ++i) {
5822 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005823
5824 // Look at the promotion type of enum types, since that is the type used
5825 // to pass enum values.
5826 if (const EnumType *Enum = argTy->getAs<EnumType>())
5827 argTy = Enum->getDecl()->getPromotionType();
5828
Eli Friedman47f77112008-08-22 00:56:42 +00005829 if (argTy->isPromotableIntegerType() ||
5830 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5831 return QualType();
5832 }
5833
5834 if (allLTypes) return lhs;
5835 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005836
5837 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5838 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005839 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005840 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005841 }
5842
5843 if (allLTypes) return lhs;
5844 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005845 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005846}
5847
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005848QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005849 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005850 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005851 // C++ [expr]: If an expression initially has the type "reference to T", the
5852 // type is adjusted to "T" prior to any further analysis, the expression
5853 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005854 // expression is an lvalue unless the reference is an rvalue reference and
5855 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005856 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5857 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005858
5859 if (Unqualified) {
5860 LHS = LHS.getUnqualifiedType();
5861 RHS = RHS.getUnqualifiedType();
5862 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005863
Eli Friedman47f77112008-08-22 00:56:42 +00005864 QualType LHSCan = getCanonicalType(LHS),
5865 RHSCan = getCanonicalType(RHS);
5866
5867 // If two types are identical, they are compatible.
5868 if (LHSCan == RHSCan)
5869 return LHS;
5870
John McCall8ccfcb52009-09-24 19:53:00 +00005871 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005872 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5873 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005874 if (LQuals != RQuals) {
5875 // If any of these qualifiers are different, we have a type
5876 // mismatch.
5877 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005878 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5879 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005880 return QualType();
5881
5882 // Exactly one GC qualifier difference is allowed: __strong is
5883 // okay if the other type has no GC qualifier but is an Objective
5884 // C object pointer (i.e. implicitly strong by default). We fix
5885 // this by pretending that the unqualified type was actually
5886 // qualified __strong.
5887 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5888 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5889 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5890
5891 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5892 return QualType();
5893
5894 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5895 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5896 }
5897 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5898 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5899 }
Eli Friedman47f77112008-08-22 00:56:42 +00005900 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005901 }
5902
5903 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005904
Eli Friedmandcca6332009-06-01 01:22:52 +00005905 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5906 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005907
Chris Lattnerfd652912008-01-14 05:45:46 +00005908 // We want to consider the two function types to be the same for these
5909 // comparisons, just force one to the other.
5910 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5911 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005912
5913 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005914 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5915 LHSClass = Type::ConstantArray;
5916 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5917 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005918
John McCall8b07ec22010-05-15 11:32:37 +00005919 // ObjCInterfaces are just specialized ObjCObjects.
5920 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5921 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5922
Nate Begemance4d7fc2008-04-18 23:10:10 +00005923 // Canonicalize ExtVector -> Vector.
5924 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5925 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005926
Chris Lattner95554662008-04-07 05:43:21 +00005927 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005928 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005929 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005930 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005931 // Compatibility is based on the underlying type, not the promotion
5932 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005933 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00005934 QualType TINT = ETy->getDecl()->getIntegerType();
5935 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00005936 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005937 }
John McCall9dd450b2009-09-21 23:43:11 +00005938 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00005939 QualType TINT = ETy->getDecl()->getIntegerType();
5940 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00005941 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005942 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00005943 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00005944 if (OfBlockPointer && !BlockReturnType) {
5945 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5946 return LHS;
5947 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5948 return RHS;
5949 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00005950
Eli Friedman47f77112008-08-22 00:56:42 +00005951 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005952 }
Eli Friedman47f77112008-08-22 00:56:42 +00005953
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005954 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005955 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005956#define TYPE(Class, Base)
5957#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005958#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005959#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5960#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5961#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00005962 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005963
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005964 case Type::LValueReference:
5965 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005966 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00005967 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005968
John McCall8b07ec22010-05-15 11:32:37 +00005969 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005970 case Type::IncompleteArray:
5971 case Type::VariableArray:
5972 case Type::FunctionProto:
5973 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00005974 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005975
Chris Lattnerfd652912008-01-14 05:45:46 +00005976 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005977 {
5978 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005979 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5980 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005981 if (Unqualified) {
5982 LHSPointee = LHSPointee.getUnqualifiedType();
5983 RHSPointee = RHSPointee.getUnqualifiedType();
5984 }
5985 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5986 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005987 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005988 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005989 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005990 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005991 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005992 return getPointerType(ResultType);
5993 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005994 case Type::BlockPointer:
5995 {
5996 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005997 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5998 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005999 if (Unqualified) {
6000 LHSPointee = LHSPointee.getUnqualifiedType();
6001 RHSPointee = RHSPointee.getUnqualifiedType();
6002 }
6003 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6004 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00006005 if (ResultType.isNull()) return QualType();
6006 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6007 return LHS;
6008 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6009 return RHS;
6010 return getBlockPointerType(ResultType);
6011 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00006012 case Type::Atomic:
6013 {
6014 // Merge two pointer types, while trying to preserve typedef info
6015 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6016 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6017 if (Unqualified) {
6018 LHSValue = LHSValue.getUnqualifiedType();
6019 RHSValue = RHSValue.getUnqualifiedType();
6020 }
6021 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6022 Unqualified);
6023 if (ResultType.isNull()) return QualType();
6024 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6025 return LHS;
6026 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6027 return RHS;
6028 return getAtomicType(ResultType);
6029 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006030 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006031 {
6032 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6033 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6034 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6035 return QualType();
6036
6037 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6038 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006039 if (Unqualified) {
6040 LHSElem = LHSElem.getUnqualifiedType();
6041 RHSElem = RHSElem.getUnqualifiedType();
6042 }
6043
6044 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006045 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006046 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6047 return LHS;
6048 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6049 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006050 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6051 ArrayType::ArraySizeModifier(), 0);
6052 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6053 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006054 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6055 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006056 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6057 return LHS;
6058 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6059 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006060 if (LVAT) {
6061 // FIXME: This isn't correct! But tricky to implement because
6062 // the array's size has to be the size of LHS, but the type
6063 // has to be different.
6064 return LHS;
6065 }
6066 if (RVAT) {
6067 // FIXME: This isn't correct! But tricky to implement because
6068 // the array's size has to be the size of RHS, but the type
6069 // has to be different.
6070 return RHS;
6071 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006072 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6073 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006074 return getIncompleteArrayType(ResultType,
6075 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006076 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006077 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006078 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006079 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006080 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006081 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006082 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006083 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006084 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006085 case Type::Complex:
6086 // Distinct complex types are incompatible.
6087 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006088 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006089 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006090 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6091 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006092 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006093 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006094 case Type::ObjCObject: {
6095 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006096 // FIXME: This should be type compatibility, e.g. whether
6097 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006098 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6099 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6100 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006101 return LHS;
6102
Eli Friedman47f77112008-08-22 00:56:42 +00006103 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006104 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006105 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006106 if (OfBlockPointer) {
6107 if (canAssignObjCInterfacesInBlockPointer(
6108 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006109 RHS->getAs<ObjCObjectPointerType>(),
6110 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006111 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006112 return QualType();
6113 }
John McCall9dd450b2009-09-21 23:43:11 +00006114 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6115 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006116 return LHS;
6117
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006118 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006119 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006120 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006121
David Blaikie8a40f702012-01-17 06:56:22 +00006122 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006123}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006124
Fariborz Jahanian97676972011-09-28 21:52:05 +00006125bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6126 const FunctionProtoType *FromFunctionType,
6127 const FunctionProtoType *ToFunctionType) {
6128 if (FromFunctionType->hasAnyConsumedArgs() !=
6129 ToFunctionType->hasAnyConsumedArgs())
6130 return false;
6131 FunctionProtoType::ExtProtoInfo FromEPI =
6132 FromFunctionType->getExtProtoInfo();
6133 FunctionProtoType::ExtProtoInfo ToEPI =
6134 ToFunctionType->getExtProtoInfo();
6135 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6136 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6137 ArgIdx != NumArgs; ++ArgIdx) {
6138 if (FromEPI.ConsumedArguments[ArgIdx] !=
6139 ToEPI.ConsumedArguments[ArgIdx])
6140 return false;
6141 }
6142 return true;
6143}
6144
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006145/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6146/// 'RHS' attributes and returns the merged version; including for function
6147/// return types.
6148QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6149 QualType LHSCan = getCanonicalType(LHS),
6150 RHSCan = getCanonicalType(RHS);
6151 // If two types are identical, they are compatible.
6152 if (LHSCan == RHSCan)
6153 return LHS;
6154 if (RHSCan->isFunctionType()) {
6155 if (!LHSCan->isFunctionType())
6156 return QualType();
6157 QualType OldReturnType =
6158 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6159 QualType NewReturnType =
6160 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6161 QualType ResReturnType =
6162 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6163 if (ResReturnType.isNull())
6164 return QualType();
6165 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6166 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6167 // In either case, use OldReturnType to build the new function type.
6168 const FunctionType *F = LHS->getAs<FunctionType>();
6169 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006170 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6171 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006172 QualType ResultType
6173 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006174 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006175 return ResultType;
6176 }
6177 }
6178 return QualType();
6179 }
6180
6181 // If the qualifiers are different, the types can still be merged.
6182 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6183 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6184 if (LQuals != RQuals) {
6185 // If any of these qualifiers are different, we have a type mismatch.
6186 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6187 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6188 return QualType();
6189
6190 // Exactly one GC qualifier difference is allowed: __strong is
6191 // okay if the other type has no GC qualifier but is an Objective
6192 // C object pointer (i.e. implicitly strong by default). We fix
6193 // this by pretending that the unqualified type was actually
6194 // qualified __strong.
6195 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6196 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6197 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6198
6199 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6200 return QualType();
6201
6202 if (GC_L == Qualifiers::Strong)
6203 return LHS;
6204 if (GC_R == Qualifiers::Strong)
6205 return RHS;
6206 return QualType();
6207 }
6208
6209 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6210 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6211 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6212 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6213 if (ResQT == LHSBaseQT)
6214 return LHS;
6215 if (ResQT == RHSBaseQT)
6216 return RHS;
6217 }
6218 return QualType();
6219}
6220
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006221//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006222// Integer Predicates
6223//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006224
Jay Foad39c79802011-01-12 09:06:06 +00006225unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006226 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006227 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006228 if (T->isBooleanType())
6229 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006230 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006231 return (unsigned)getTypeSize(T);
6232}
6233
6234QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006235 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006236
6237 // Turn <4 x signed int> -> <4 x unsigned int>
6238 if (const VectorType *VTy = T->getAs<VectorType>())
6239 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006240 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006241
6242 // For enums, we return the unsigned version of the base type.
6243 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006244 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006245
6246 const BuiltinType *BTy = T->getAs<BuiltinType>();
6247 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006248 switch (BTy->getKind()) {
6249 case BuiltinType::Char_S:
6250 case BuiltinType::SChar:
6251 return UnsignedCharTy;
6252 case BuiltinType::Short:
6253 return UnsignedShortTy;
6254 case BuiltinType::Int:
6255 return UnsignedIntTy;
6256 case BuiltinType::Long:
6257 return UnsignedLongTy;
6258 case BuiltinType::LongLong:
6259 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006260 case BuiltinType::Int128:
6261 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006262 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006263 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006264 }
6265}
6266
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006267ASTMutationListener::~ASTMutationListener() { }
6268
Chris Lattnerecd79c62009-06-14 00:45:47 +00006269
6270//===----------------------------------------------------------------------===//
6271// Builtin Type Computation
6272//===----------------------------------------------------------------------===//
6273
6274/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006275/// pointer over the consumed characters. This returns the resultant type. If
6276/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6277/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6278/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006279///
6280/// RequiresICE is filled in on return to indicate whether the value is required
6281/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006282static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006283 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006284 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006285 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006286 // Modifiers.
6287 int HowLong = 0;
6288 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006289 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006290
Chris Lattnerdc226c22010-10-01 22:42:38 +00006291 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006292 bool Done = false;
6293 while (!Done) {
6294 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006295 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006296 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006297 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006298 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006299 case 'S':
6300 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6301 assert(!Signed && "Can't use 'S' modifier multiple times!");
6302 Signed = true;
6303 break;
6304 case 'U':
6305 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6306 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6307 Unsigned = true;
6308 break;
6309 case 'L':
6310 assert(HowLong <= 2 && "Can't have LLLL modifier");
6311 ++HowLong;
6312 break;
6313 }
6314 }
6315
6316 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006317
Chris Lattnerecd79c62009-06-14 00:45:47 +00006318 // Read the base type.
6319 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006320 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006321 case 'v':
6322 assert(HowLong == 0 && !Signed && !Unsigned &&
6323 "Bad modifiers used with 'v'!");
6324 Type = Context.VoidTy;
6325 break;
6326 case 'f':
6327 assert(HowLong == 0 && !Signed && !Unsigned &&
6328 "Bad modifiers used with 'f'!");
6329 Type = Context.FloatTy;
6330 break;
6331 case 'd':
6332 assert(HowLong < 2 && !Signed && !Unsigned &&
6333 "Bad modifiers used with 'd'!");
6334 if (HowLong)
6335 Type = Context.LongDoubleTy;
6336 else
6337 Type = Context.DoubleTy;
6338 break;
6339 case 's':
6340 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6341 if (Unsigned)
6342 Type = Context.UnsignedShortTy;
6343 else
6344 Type = Context.ShortTy;
6345 break;
6346 case 'i':
6347 if (HowLong == 3)
6348 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6349 else if (HowLong == 2)
6350 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6351 else if (HowLong == 1)
6352 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6353 else
6354 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6355 break;
6356 case 'c':
6357 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6358 if (Signed)
6359 Type = Context.SignedCharTy;
6360 else if (Unsigned)
6361 Type = Context.UnsignedCharTy;
6362 else
6363 Type = Context.CharTy;
6364 break;
6365 case 'b': // boolean
6366 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6367 Type = Context.BoolTy;
6368 break;
6369 case 'z': // size_t.
6370 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6371 Type = Context.getSizeType();
6372 break;
6373 case 'F':
6374 Type = Context.getCFConstantStringType();
6375 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006376 case 'G':
6377 Type = Context.getObjCIdType();
6378 break;
6379 case 'H':
6380 Type = Context.getObjCSelType();
6381 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006382 case 'a':
6383 Type = Context.getBuiltinVaListType();
6384 assert(!Type.isNull() && "builtin va list type not initialized!");
6385 break;
6386 case 'A':
6387 // This is a "reference" to a va_list; however, what exactly
6388 // this means depends on how va_list is defined. There are two
6389 // different kinds of va_list: ones passed by value, and ones
6390 // passed by reference. An example of a by-value va_list is
6391 // x86, where va_list is a char*. An example of by-ref va_list
6392 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6393 // we want this argument to be a char*&; for x86-64, we want
6394 // it to be a __va_list_tag*.
6395 Type = Context.getBuiltinVaListType();
6396 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006397 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006398 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006399 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006400 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006401 break;
6402 case 'V': {
6403 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006404 unsigned NumElements = strtoul(Str, &End, 10);
6405 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006406 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006407
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006408 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6409 RequiresICE, false);
6410 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006411
6412 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006413 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006414 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006415 break;
6416 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006417 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006418 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6419 false);
6420 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006421 Type = Context.getComplexType(ElementType);
6422 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006423 }
6424 case 'Y' : {
6425 Type = Context.getPointerDiffType();
6426 break;
6427 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006428 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006429 Type = Context.getFILEType();
6430 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006431 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006432 return QualType();
6433 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006434 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006435 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006436 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006437 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006438 else
6439 Type = Context.getjmp_bufType();
6440
Mike Stump2adb4da2009-07-28 23:47:15 +00006441 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006442 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006443 return QualType();
6444 }
6445 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006446 case 'K':
6447 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6448 Type = Context.getucontext_tType();
6449
6450 if (Type.isNull()) {
6451 Error = ASTContext::GE_Missing_ucontext;
6452 return QualType();
6453 }
6454 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006455 }
Mike Stump11289f42009-09-09 15:08:12 +00006456
Chris Lattnerdc226c22010-10-01 22:42:38 +00006457 // If there are modifiers and if we're allowed to parse them, go for it.
6458 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006459 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006460 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006461 default: Done = true; --Str; break;
6462 case '*':
6463 case '&': {
6464 // Both pointers and references can have their pointee types
6465 // qualified with an address space.
6466 char *End;
6467 unsigned AddrSpace = strtoul(Str, &End, 10);
6468 if (End != Str && AddrSpace != 0) {
6469 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6470 Str = End;
6471 }
6472 if (c == '*')
6473 Type = Context.getPointerType(Type);
6474 else
6475 Type = Context.getLValueReferenceType(Type);
6476 break;
6477 }
6478 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6479 case 'C':
6480 Type = Type.withConst();
6481 break;
6482 case 'D':
6483 Type = Context.getVolatileType(Type);
6484 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006485 case 'R':
6486 Type = Type.withRestrict();
6487 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006488 }
6489 }
Chris Lattner84733392010-10-01 07:13:18 +00006490
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006491 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006492 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006493
Chris Lattnerecd79c62009-06-14 00:45:47 +00006494 return Type;
6495}
6496
6497/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006498QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006499 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006500 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006501 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006502
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006503 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006504
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006505 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006506 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006507 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6508 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006509 if (Error != GE_None)
6510 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006511
6512 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6513
Chris Lattnerecd79c62009-06-14 00:45:47 +00006514 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006515 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006516 if (Error != GE_None)
6517 return QualType();
6518
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006519 // If this argument is required to be an IntegerConstantExpression and the
6520 // caller cares, fill in the bitmask we return.
6521 if (RequiresICE && IntegerConstantArgs)
6522 *IntegerConstantArgs |= 1 << ArgTypes.size();
6523
Chris Lattnerecd79c62009-06-14 00:45:47 +00006524 // Do array -> pointer decay. The builtin should use the decayed type.
6525 if (Ty->isArrayType())
6526 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006527
Chris Lattnerecd79c62009-06-14 00:45:47 +00006528 ArgTypes.push_back(Ty);
6529 }
6530
6531 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6532 "'.' should only occur at end of builtin type list!");
6533
John McCall991eb4b2010-12-21 00:44:39 +00006534 FunctionType::ExtInfo EI;
6535 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6536
6537 bool Variadic = (TypeStr[0] == '.');
6538
6539 // We really shouldn't be making a no-proto type here, especially in C++.
6540 if (ArgTypes.empty() && Variadic)
6541 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006542
John McCalldb40c7f2010-12-14 08:05:40 +00006543 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006544 EPI.ExtInfo = EI;
6545 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006546
6547 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006548}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006549
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006550GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6551 GVALinkage External = GVA_StrongExternal;
6552
6553 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006554 switch (L) {
6555 case NoLinkage:
6556 case InternalLinkage:
6557 case UniqueExternalLinkage:
6558 return GVA_Internal;
6559
6560 case ExternalLinkage:
6561 switch (FD->getTemplateSpecializationKind()) {
6562 case TSK_Undeclared:
6563 case TSK_ExplicitSpecialization:
6564 External = GVA_StrongExternal;
6565 break;
6566
6567 case TSK_ExplicitInstantiationDefinition:
6568 return GVA_ExplicitTemplateInstantiation;
6569
6570 case TSK_ExplicitInstantiationDeclaration:
6571 case TSK_ImplicitInstantiation:
6572 External = GVA_TemplateInstantiation;
6573 break;
6574 }
6575 }
6576
6577 if (!FD->isInlined())
6578 return External;
6579
David Blaikiebbafb8a2012-03-11 07:00:24 +00006580 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006581 // GNU or C99 inline semantics. Determine whether this symbol should be
6582 // externally visible.
6583 if (FD->isInlineDefinitionExternallyVisible())
6584 return External;
6585
6586 // C99 inline semantics, where the symbol is not externally visible.
6587 return GVA_C99Inline;
6588 }
6589
6590 // C++0x [temp.explicit]p9:
6591 // [ Note: The intent is that an inline function that is the subject of
6592 // an explicit instantiation declaration will still be implicitly
6593 // instantiated when used so that the body can be considered for
6594 // inlining, but that no out-of-line copy of the inline function would be
6595 // generated in the translation unit. -- end note ]
6596 if (FD->getTemplateSpecializationKind()
6597 == TSK_ExplicitInstantiationDeclaration)
6598 return GVA_C99Inline;
6599
6600 return GVA_CXXInline;
6601}
6602
6603GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6604 // If this is a static data member, compute the kind of template
6605 // specialization. Otherwise, this variable is not part of a
6606 // template.
6607 TemplateSpecializationKind TSK = TSK_Undeclared;
6608 if (VD->isStaticDataMember())
6609 TSK = VD->getTemplateSpecializationKind();
6610
6611 Linkage L = VD->getLinkage();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006612 if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006613 VD->getType()->getLinkage() == UniqueExternalLinkage)
6614 L = UniqueExternalLinkage;
6615
6616 switch (L) {
6617 case NoLinkage:
6618 case InternalLinkage:
6619 case UniqueExternalLinkage:
6620 return GVA_Internal;
6621
6622 case ExternalLinkage:
6623 switch (TSK) {
6624 case TSK_Undeclared:
6625 case TSK_ExplicitSpecialization:
6626 return GVA_StrongExternal;
6627
6628 case TSK_ExplicitInstantiationDeclaration:
6629 llvm_unreachable("Variable should not be instantiated");
6630 // Fall through to treat this like any other instantiation.
6631
6632 case TSK_ExplicitInstantiationDefinition:
6633 return GVA_ExplicitTemplateInstantiation;
6634
6635 case TSK_ImplicitInstantiation:
6636 return GVA_TemplateInstantiation;
6637 }
6638 }
6639
David Blaikie8a40f702012-01-17 06:56:22 +00006640 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006641}
6642
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006643bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006644 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6645 if (!VD->isFileVarDecl())
6646 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006647 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006648 return false;
6649
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006650 // Weak references don't produce any output by themselves.
6651 if (D->hasAttr<WeakRefAttr>())
6652 return false;
6653
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006654 // Aliases and used decls are required.
6655 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6656 return true;
6657
6658 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6659 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006660 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006661 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006662
6663 // Constructors and destructors are required.
6664 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6665 return true;
6666
6667 // The key function for a class is required.
6668 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6669 const CXXRecordDecl *RD = MD->getParent();
6670 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6671 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6672 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6673 return true;
6674 }
6675 }
6676
6677 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6678
6679 // static, static inline, always_inline, and extern inline functions can
6680 // always be deferred. Normal inline functions can be deferred in C99/C++.
6681 // Implicit template instantiations can also be deferred in C++.
6682 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00006683 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006684 return false;
6685 return true;
6686 }
Douglas Gregor87d81242011-09-10 00:22:34 +00006687
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006688 const VarDecl *VD = cast<VarDecl>(D);
6689 assert(VD->isFileVarDecl() && "Expected file scoped var");
6690
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006691 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6692 return false;
6693
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006694 // Structs that have non-trivial constructors or destructors are required.
6695
6696 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006697 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006698 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6699 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006700 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6701 RD->hasTrivialCopyConstructor() &&
6702 RD->hasTrivialMoveConstructor() &&
6703 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006704 return true;
6705 }
6706 }
6707
6708 GVALinkage L = GetGVALinkageForVariable(VD);
6709 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6710 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6711 return false;
6712 }
6713
6714 return true;
6715}
Charles Davis53c59df2010-08-16 03:33:14 +00006716
Charles Davis99202b32010-11-09 18:04:24 +00006717CallingConv ASTContext::getDefaultMethodCallConv() {
6718 // Pass through to the C++ ABI object
6719 return ABI->getDefaultMethodCallConv();
6720}
6721
Jay Foad39c79802011-01-12 09:06:06 +00006722bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006723 // Pass through to the C++ ABI object
6724 return ABI->isNearlyEmpty(RD);
6725}
6726
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006727MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00006728 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006729 case CXXABI_ARM:
6730 case CXXABI_Itanium:
6731 return createItaniumMangleContext(*this, getDiagnostics());
6732 case CXXABI_Microsoft:
6733 return createMicrosoftMangleContext(*this, getDiagnostics());
6734 }
David Blaikie83d382b2011-09-23 05:06:16 +00006735 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006736}
6737
Charles Davis53c59df2010-08-16 03:33:14 +00006738CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006739
6740size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00006741 return ASTRecordLayouts.getMemorySize()
6742 + llvm::capacity_in_bytes(ObjCLayouts)
6743 + llvm::capacity_in_bytes(KeyFunctions)
6744 + llvm::capacity_in_bytes(ObjCImpls)
6745 + llvm::capacity_in_bytes(BlockVarCopyInits)
6746 + llvm::capacity_in_bytes(DeclAttrs)
6747 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6748 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6749 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6750 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6751 + llvm::capacity_in_bytes(OverriddenMethods)
6752 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006753 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00006754 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006755}
Ted Kremenek540017e2011-10-06 05:00:56 +00006756
Douglas Gregor63798542012-02-20 19:44:39 +00006757unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
6758 CXXRecordDecl *Lambda = CallOperator->getParent();
6759 return LambdaMangleContexts[Lambda->getDeclContext()]
6760 .getManglingNumber(CallOperator);
6761}
6762
6763
Ted Kremenek540017e2011-10-06 05:00:56 +00006764void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6765 ParamIndices[D] = index;
6766}
6767
6768unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6769 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6770 assert(I != ParamIndices.end() &&
6771 "ParmIndices lacks entry set by ParmVarDecl");
6772 return I->second;
6773}