blob: 0d6f6e612c9ffd3ab500033f45039caac31b327c [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff67391b82007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlssond8499822007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek7d39c9a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis53c59df2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000035#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000036
Chris Lattnerddc135e2006-11-10 06:34:16 +000037using namespace clang;
38
Douglas Gregor9672f922010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Steve Naroff0af91202007-04-27 21:51:21 +000052enum FloatingRank {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +000053 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Steve Naroff0af91202007-04-27 21:51:21 +000054};
55
Douglas Gregor7dbfb462010-06-16 21:09:37 +000056void
57ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
58 TemplateTemplateParmDecl *Parm) {
59 ID.AddInteger(Parm->getDepth());
60 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +000061 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +000062
63 TemplateParameterList *Params = Parm->getTemplateParameters();
64 ID.AddInteger(Params->size());
65 for (TemplateParameterList::const_iterator P = Params->begin(),
66 PEnd = Params->end();
67 P != PEnd; ++P) {
68 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
69 ID.AddInteger(0);
70 ID.AddBoolean(TTP->isParameterPack());
71 continue;
72 }
73
74 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
75 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +000076 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +000077 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +000081 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
82 QualType T = NTTP->getExpansionType(I);
83 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
84 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +000085 } else
86 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +000087 continue;
88 }
89
90 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
91 ID.AddInteger(2);
92 Profile(ID, TTP);
93 }
94}
95
96TemplateTemplateParmDecl *
97ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +000098 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +000099 // Check if we already have a canonical template template parameter.
100 llvm::FoldingSetNodeID ID;
101 CanonicalTemplateTemplateParm::Profile(ID, TTP);
102 void *InsertPos = 0;
103 CanonicalTemplateTemplateParm *Canonical
104 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
105 if (Canonical)
106 return Canonical->getParam();
107
108 // Build a canonical template parameter list.
109 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000110 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000111 CanonParams.reserve(Params->size());
112 for (TemplateParameterList::const_iterator P = Params->begin(),
113 PEnd = Params->end();
114 P != PEnd; ++P) {
115 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
116 CanonParams.push_back(
117 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000118 SourceLocation(),
119 SourceLocation(),
120 TTP->getDepth(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000121 TTP->getIndex(), 0, false,
122 TTP->isParameterPack()));
123 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000124 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
125 QualType T = getCanonicalType(NTTP->getType());
126 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
127 NonTypeTemplateParmDecl *Param;
128 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000129 SmallVector<QualType, 2> ExpandedTypes;
130 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000131 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
132 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
133 ExpandedTInfos.push_back(
134 getTrivialTypeSourceInfo(ExpandedTypes.back()));
135 }
136
137 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000138 SourceLocation(),
139 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000140 NTTP->getDepth(),
141 NTTP->getPosition(), 0,
142 T,
143 TInfo,
144 ExpandedTypes.data(),
145 ExpandedTypes.size(),
146 ExpandedTInfos.data());
147 } else {
148 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000149 SourceLocation(),
150 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000151 NTTP->getDepth(),
152 NTTP->getPosition(), 0,
153 T,
154 NTTP->isParameterPack(),
155 TInfo);
156 }
157 CanonParams.push_back(Param);
158
159 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000160 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
161 cast<TemplateTemplateParmDecl>(*P)));
162 }
163
164 TemplateTemplateParmDecl *CanonTTP
165 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
166 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000167 TTP->getPosition(),
168 TTP->isParameterPack(),
169 0,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000170 TemplateParameterList::Create(*this, SourceLocation(),
171 SourceLocation(),
172 CanonParams.data(),
173 CanonParams.size(),
174 SourceLocation()));
175
176 // Get the new insert position for the node we care about.
177 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
178 assert(Canonical == 0 && "Shouldn't be in the map!");
179 (void)Canonical;
180
181 // Create the canonical template template parameter entry.
182 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
183 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
184 return CanonTTP;
185}
186
Charles Davis53c59df2010-08-16 03:33:14 +0000187CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCall86353412010-08-21 22:46:04 +0000188 if (!LangOpts.CPlusPlus) return 0;
189
Charles Davis6bcb07a2010-08-19 02:18:14 +0000190 switch (T.getCXXABI()) {
John McCall86353412010-08-21 22:46:04 +0000191 case CXXABI_ARM:
192 return CreateARMCXXABI(*this);
193 case CXXABI_Itanium:
Charles Davis53c59df2010-08-16 03:33:14 +0000194 return CreateItaniumCXXABI(*this);
Charles Davis6bcb07a2010-08-19 02:18:14 +0000195 case CXXABI_Microsoft:
196 return CreateMicrosoftCXXABI(*this);
197 }
David Blaikie8a40f702012-01-17 06:56:22 +0000198 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000199}
200
Douglas Gregore8bbc122011-09-02 00:18:52 +0000201static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000202 const LangOptions &LOpts) {
203 if (LOpts.FakeAddressSpaceMap) {
204 // The fake address space map must have a distinct entry for each
205 // language-specific address space.
206 static const unsigned FakeAddrSpaceMap[] = {
207 1, // opencl_global
208 2, // opencl_local
209 3 // opencl_constant
210 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000211 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000212 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000213 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000214 }
215}
216
Douglas Gregor7018d5b2011-09-01 20:23:19 +0000217ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000218 const TargetInfo *t,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000219 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner15ba9492009-06-14 01:54:56 +0000220 Builtin::Context &builtins,
Douglas Gregore8bbc122011-09-02 00:18:52 +0000221 unsigned size_reserve,
222 bool DelayInitialization)
223 : FunctionProtoTypes(this_()),
224 TemplateSpecializationTypes(this_()),
225 DependentTemplateSpecializationTypes(this_()),
226 SubstTemplateTemplateParmPacks(this_()),
227 GlobalNestedNameSpecifier(0),
228 Int128Decl(0), UInt128Decl(0),
Douglas Gregord53ae832012-01-17 18:09:05 +0000229 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000230 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000231 FILEDecl(0),
Rafael Espindola6cfa82b2011-11-13 21:51:09 +0000232 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
233 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
234 cudaConfigureCallDecl(0),
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000235 NullTypeSourceInfo(QualType()),
236 FirstLocalImport(), LastLocalImport(),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000237 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000238 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000239 Idents(idents), Selectors(sels),
240 BuiltinInfo(builtins),
241 DeclarationNames(*this),
Douglas Gregorc0b07282011-09-27 22:38:19 +0000242 ExternalSource(0), Listener(0),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000243 LastSDM(0, 0),
244 UniqueBlockByRefTypeID(0)
245{
Mike Stump11289f42009-09-09 15:08:12 +0000246 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbar221fa942008-08-11 04:54:23 +0000247 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000248
249 if (!DelayInitialization) {
250 assert(t && "No target supplied for ASTContext initialization");
251 InitBuiltinTypes(*t);
252 }
Daniel Dunbar221fa942008-08-11 04:54:23 +0000253}
254
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000255ASTContext::~ASTContext() {
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000256 // Release the DenseMaps associated with DeclContext objects.
257 // FIXME: Is this the ideal solution?
258 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000259
Douglas Gregor5b11d492010-07-25 17:53:33 +0000260 // Call all of the deallocation functions.
261 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
262 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor1a809332010-05-23 18:26:36 +0000263
Ted Kremenek076baeb2010-06-08 23:00:58 +0000264 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000265 // because they can contain DenseMaps.
266 for (llvm::DenseMap<const ObjCContainerDecl*,
267 const ASTRecordLayout*>::iterator
268 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
269 // Increment in loop to prevent using deallocated memory.
270 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
271 R->Destroy(*this);
272
Ted Kremenek076baeb2010-06-08 23:00:58 +0000273 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
274 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
275 // Increment in loop to prevent using deallocated memory.
276 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
277 R->Destroy(*this);
278 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000279
280 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
281 AEnd = DeclAttrs.end();
282 A != AEnd; ++A)
283 A->second->~AttrVec();
284}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000285
Douglas Gregor1a809332010-05-23 18:26:36 +0000286void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
287 Deallocations.push_back(std::make_pair(Callback, Data));
288}
289
Mike Stump11289f42009-09-09 15:08:12 +0000290void
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000291ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000292 ExternalSource.reset(Source.take());
293}
294
Chris Lattner4eb445d2007-01-26 01:27:23 +0000295void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000296 llvm::errs() << "\n*** AST Context Stats:\n";
297 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000298
Douglas Gregora30d0462009-05-26 14:40:08 +0000299 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000300#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000301#define ABSTRACT_TYPE(Name, Parent)
302#include "clang/AST/TypeNodes.def"
303 0 // Extra
304 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000305
Chris Lattner4eb445d2007-01-26 01:27:23 +0000306 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
307 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000308 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000309 }
310
Douglas Gregora30d0462009-05-26 14:40:08 +0000311 unsigned Idx = 0;
312 unsigned TotalBytes = 0;
313#define TYPE(Name, Parent) \
314 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000315 llvm::errs() << " " << counts[Idx] << " " << #Name \
316 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000317 TotalBytes += counts[Idx] * sizeof(Name##Type); \
318 ++Idx;
319#define ABSTRACT_TYPE(Name, Parent)
320#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000321
Chandler Carruth3c147a72011-07-04 05:32:14 +0000322 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
323
Douglas Gregor7454c562010-07-02 20:37:36 +0000324 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000325 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
326 << NumImplicitDefaultConstructors
327 << " implicit default constructors created\n";
328 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
329 << NumImplicitCopyConstructors
330 << " implicit copy constructors created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000331 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000332 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
333 << NumImplicitMoveConstructors
334 << " implicit move constructors created\n";
335 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
336 << NumImplicitCopyAssignmentOperators
337 << " implicit copy assignment operators created\n";
Alexis Huntfcaeae42011-05-25 20:50:04 +0000338 if (getLangOptions().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000339 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
340 << NumImplicitMoveAssignmentOperators
341 << " implicit move assignment operators created\n";
342 llvm::errs() << NumImplicitDestructorsDeclared << "/"
343 << NumImplicitDestructors
344 << " implicit destructors created\n";
345
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000346 if (ExternalSource.get()) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000347 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000348 ExternalSource->PrintStats();
349 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000350
Douglas Gregor5b11d492010-07-25 17:53:33 +0000351 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000352}
353
Douglas Gregor801c99d2011-08-12 06:49:56 +0000354TypedefDecl *ASTContext::getInt128Decl() const {
355 if (!Int128Decl) {
356 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
357 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
358 getTranslationUnitDecl(),
359 SourceLocation(),
360 SourceLocation(),
361 &Idents.get("__int128_t"),
362 TInfo);
363 }
364
365 return Int128Decl;
366}
367
368TypedefDecl *ASTContext::getUInt128Decl() const {
369 if (!UInt128Decl) {
370 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
371 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
372 getTranslationUnitDecl(),
373 SourceLocation(),
374 SourceLocation(),
375 &Idents.get("__uint128_t"),
376 TInfo);
377 }
378
379 return UInt128Decl;
380}
Chris Lattner4eb445d2007-01-26 01:27:23 +0000381
John McCall48f2d582009-10-23 23:03:21 +0000382void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +0000383 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +0000384 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +0000385 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000386}
387
Douglas Gregore8bbc122011-09-02 00:18:52 +0000388void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
389 assert((!this->Target || this->Target == &Target) &&
390 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +0000391 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +0000392
Douglas Gregore8bbc122011-09-02 00:18:52 +0000393 this->Target = &Target;
394
395 ABI.reset(createCXXABI(Target));
396 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
397
Chris Lattner970e54e2006-11-12 00:37:36 +0000398 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +0000399 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +0000400
Chris Lattner970e54e2006-11-12 00:37:36 +0000401 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +0000402 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +0000403 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +0000404 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +0000405 InitBuiltinType(CharTy, BuiltinType::Char_S);
406 else
407 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +0000408 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +0000409 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
410 InitBuiltinType(ShortTy, BuiltinType::Short);
411 InitBuiltinType(IntTy, BuiltinType::Int);
412 InitBuiltinType(LongTy, BuiltinType::Long);
413 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000414
Chris Lattner970e54e2006-11-12 00:37:36 +0000415 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +0000416 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
417 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
418 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
419 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
420 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +0000421
Chris Lattner970e54e2006-11-12 00:37:36 +0000422 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +0000423 InitBuiltinType(FloatTy, BuiltinType::Float);
424 InitBuiltinType(DoubleTy, BuiltinType::Double);
425 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000426
Chris Lattnerf122cef2009-04-30 02:43:43 +0000427 // GNU extension, 128-bit integers.
428 InitBuiltinType(Int128Ty, BuiltinType::Int128);
429 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
430
Chris Lattnerad3467e2010-12-25 23:25:43 +0000431 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedman786d0872011-04-30 19:24:24 +0000432 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattnerad3467e2010-12-25 23:25:43 +0000433 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
434 else // -fshort-wchar makes wchar_t be unsigned.
435 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
436 } else // C99
Chris Lattner007cb022009-02-26 23:43:47 +0000437 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000438
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000439 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
440 InitBuiltinType(Char16Ty, BuiltinType::Char16);
441 else // C99
442 Char16Ty = getFromTargetType(Target.getChar16Type());
443
444 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
445 InitBuiltinType(Char32Ty, BuiltinType::Char32);
446 else // C99
447 Char32Ty = getFromTargetType(Target.getChar32Type());
448
Douglas Gregor4619e432008-12-05 23:32:09 +0000449 // Placeholder type for type-dependent expressions whose type is
450 // completely unknown. No code should ever check a type against
451 // DependentTy and users should never see it; however, it is here to
452 // help diagnose failures to properly check for type-dependent
453 // expressions.
454 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000455
John McCall36e7fe32010-10-12 00:20:44 +0000456 // Placeholder type for functions.
457 InitBuiltinType(OverloadTy, BuiltinType::Overload);
458
John McCall0009fcc2011-04-26 20:42:42 +0000459 // Placeholder type for bound members.
460 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
461
John McCall526ab472011-10-25 17:37:35 +0000462 // Placeholder type for pseudo-objects.
463 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
464
John McCall31996342011-04-07 08:22:57 +0000465 // "any" type; useful for debugger-like clients.
466 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
467
John McCall8a6b59a2011-10-17 18:09:15 +0000468 // Placeholder type for unbridged ARC casts.
469 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
470
Chris Lattner970e54e2006-11-12 00:37:36 +0000471 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +0000472 FloatComplexTy = getComplexType(FloatTy);
473 DoubleComplexTy = getComplexType(DoubleTy);
474 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000475
Steve Naroff66e9f332007-10-15 14:41:52 +0000476 BuiltinVaListType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000477
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000478 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +0000479 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
480 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +0000481 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000482
483 // Builtin type for __objc_yes and __objc_no
484 ObjCBuiltinBoolTy = SignedCharTy;
485
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000486 ObjCConstantStringType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +0000487
Fariborz Jahanian797f24c2007-10-29 22:57:28 +0000488 // void * type
489 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +0000490
491 // nullptr type (C++0x 2.14.7)
492 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000493
494 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
495 InitBuiltinType(HalfTy, BuiltinType::Half);
Chris Lattner970e54e2006-11-12 00:37:36 +0000496}
497
David Blaikie9c902b52011-09-25 23:23:43 +0000498DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000499 return SourceMgr.getDiagnostics();
500}
501
Douglas Gregor561eceb2010-08-30 16:49:28 +0000502AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
503 AttrVec *&Result = DeclAttrs[D];
504 if (!Result) {
505 void *Mem = Allocate(sizeof(AttrVec));
506 Result = new (Mem) AttrVec;
507 }
508
509 return *Result;
510}
511
512/// \brief Erase the attributes corresponding to the given declaration.
513void ASTContext::eraseDeclAttrs(const Decl *D) {
514 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
515 if (Pos != DeclAttrs.end()) {
516 Pos->second->~AttrVec();
517 DeclAttrs.erase(Pos);
518 }
519}
520
Douglas Gregor86d142a2009-10-08 07:24:58 +0000521MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +0000522ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000523 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor3c74d412009-10-14 20:14:33 +0000524 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000525 = InstantiatedFromStaticDataMember.find(Var);
526 if (Pos == InstantiatedFromStaticDataMember.end())
527 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000528
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000529 return Pos->second;
530}
531
Mike Stump11289f42009-09-09 15:08:12 +0000532void
Douglas Gregor86d142a2009-10-08 07:24:58 +0000533ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000534 TemplateSpecializationKind TSK,
535 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000536 assert(Inst->isStaticDataMember() && "Not a static data member");
537 assert(Tmpl->isStaticDataMember() && "Not a static data member");
538 assert(!InstantiatedFromStaticDataMember[Inst] &&
539 "Already noted what static data member was instantiated from");
Douglas Gregor86d142a2009-10-08 07:24:58 +0000540 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +0000541 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000542}
543
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000544FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
545 const FunctionDecl *FD){
546 assert(FD && "Specialization is 0");
547 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +0000548 = ClassScopeSpecializationPattern.find(FD);
549 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000550 return 0;
551
552 return Pos->second;
553}
554
555void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
556 FunctionDecl *Pattern) {
557 assert(FD && "Specialization is 0");
558 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +0000559 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000560}
561
John McCalle61f2ba2009-11-18 02:36:19 +0000562NamedDecl *
John McCallb96ec562009-12-04 22:46:56 +0000563ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCalle61f2ba2009-11-18 02:36:19 +0000564 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCallb96ec562009-12-04 22:46:56 +0000565 = InstantiatedFromUsingDecl.find(UUD);
566 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000567 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000568
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000569 return Pos->second;
570}
571
572void
John McCallb96ec562009-12-04 22:46:56 +0000573ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
574 assert((isa<UsingDecl>(Pattern) ||
575 isa<UnresolvedUsingValueDecl>(Pattern) ||
576 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
577 "pattern decl is not a using decl");
578 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
579 InstantiatedFromUsingDecl[Inst] = Pattern;
580}
581
582UsingShadowDecl *
583ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
584 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
585 = InstantiatedFromUsingShadowDecl.find(Inst);
586 if (Pos == InstantiatedFromUsingShadowDecl.end())
587 return 0;
588
589 return Pos->second;
590}
591
592void
593ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
594 UsingShadowDecl *Pattern) {
595 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
596 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +0000597}
598
Anders Carlsson5da84842009-09-01 04:26:58 +0000599FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
600 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
601 = InstantiatedFromUnnamedFieldDecl.find(Field);
602 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
603 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000604
Anders Carlsson5da84842009-09-01 04:26:58 +0000605 return Pos->second;
606}
607
608void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
609 FieldDecl *Tmpl) {
610 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
611 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
612 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
613 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +0000614
Anders Carlsson5da84842009-09-01 04:26:58 +0000615 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
616}
617
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000618bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
619 const FieldDecl *LastFD) const {
620 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000621 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian595ec5d2011-04-27 17:14:21 +0000622}
623
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000624bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
625 const FieldDecl *LastFD) const {
626 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000627 FD->getBitWidthValue(*this) == 0 &&
628 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000629}
630
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000631bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
632 const FieldDecl *LastFD) const {
633 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000634 FD->getBitWidthValue(*this) &&
635 LastFD->getBitWidthValue(*this));
Fariborz Jahanian84335f72011-05-04 18:51:37 +0000636}
637
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000638bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000639 const FieldDecl *LastFD) const {
640 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000641 LastFD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000642}
643
Chad Rosierf01a7dd2011-08-04 23:34:15 +0000644bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000645 const FieldDecl *LastFD) const {
646 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +0000647 FD->getBitWidthValue(*this));
Fariborz Jahanianb7a28792011-05-06 21:56:12 +0000648}
649
Douglas Gregor832940b2010-03-02 23:58:15 +0000650ASTContext::overridden_cxx_method_iterator
651ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
652 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
653 = OverriddenMethods.find(Method);
654 if (Pos == OverriddenMethods.end())
655 return 0;
656
657 return Pos->second.begin();
658}
659
660ASTContext::overridden_cxx_method_iterator
661ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
662 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
663 = OverriddenMethods.find(Method);
664 if (Pos == OverriddenMethods.end())
665 return 0;
666
667 return Pos->second.end();
668}
669
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +0000670unsigned
671ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
672 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
673 = OverriddenMethods.find(Method);
674 if (Pos == OverriddenMethods.end())
675 return 0;
676
677 return Pos->second.size();
678}
679
Douglas Gregor832940b2010-03-02 23:58:15 +0000680void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
681 const CXXMethodDecl *Overridden) {
682 OverriddenMethods[Method].push_back(Overridden);
683}
684
Douglas Gregor0f2a3602011-12-03 00:30:27 +0000685void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
686 assert(!Import->NextLocalImport && "Import declaration already in the chain");
687 assert(!Import->isFromASTFile() && "Non-local import declaration");
688 if (!FirstLocalImport) {
689 FirstLocalImport = Import;
690 LastLocalImport = Import;
691 return;
692 }
693
694 LastLocalImport->NextLocalImport = Import;
695 LastLocalImport = Import;
696}
697
Chris Lattner53cfe802007-07-18 17:52:12 +0000698//===----------------------------------------------------------------------===//
699// Type Sizing and Analysis
700//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +0000701
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000702/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
703/// scalar floating point type.
704const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +0000705 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000706 assert(BT && "Not a floating point type!");
707 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000708 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000709 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +0000710 case BuiltinType::Float: return Target->getFloatFormat();
711 case BuiltinType::Double: return Target->getDoubleFormat();
712 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000713 }
714}
715
Ken Dyck160146e2010-01-27 17:10:57 +0000716/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattner68061312009-01-24 21:53:27 +0000717/// specified decl. Note that bitfields do not have a valid alignment, so
718/// this method will assert on them.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000719/// If @p RefAsPointee, references are treated like their underlying type
720/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad39c79802011-01-12 09:06:06 +0000721CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000722 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +0000723
John McCall94268702010-10-08 18:24:19 +0000724 bool UseAlignAttrOnly = false;
725 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
726 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +0000727
John McCall94268702010-10-08 18:24:19 +0000728 // __attribute__((aligned)) can increase or decrease alignment
729 // *except* on a struct or struct member, where it only increases
730 // alignment unless 'packed' is also specified.
731 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +0000732 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +0000733 // ignore that possibility; Sema should diagnose it.
734 if (isa<FieldDecl>(D)) {
735 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
736 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
737 } else {
738 UseAlignAttrOnly = true;
739 }
740 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +0000741 else if (isa<FieldDecl>(D))
742 UseAlignAttrOnly =
743 D->hasAttr<PackedAttr>() ||
744 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +0000745
John McCall4e819612011-01-20 07:57:12 +0000746 // If we're using the align attribute only, just ignore everything
747 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +0000748 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +0000749 // do nothing
750
John McCall94268702010-10-08 18:24:19 +0000751 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +0000752 QualType T = VD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000753 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000754 if (RefAsPointee)
755 T = RT->getPointeeType();
756 else
757 T = getPointerType(RT->getPointeeType());
758 }
759 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall33ddac02011-01-19 10:06:00 +0000760 // Adjust alignments of declarations with array type by the
761 // large-array alignment on the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +0000762 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall33ddac02011-01-19 10:06:00 +0000763 const ArrayType *arrayType;
764 if (MinWidth && (arrayType = getAsArrayType(T))) {
765 if (isa<VariableArrayType>(arrayType))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000766 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall33ddac02011-01-19 10:06:00 +0000767 else if (isa<ConstantArrayType>(arrayType) &&
768 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregore8bbc122011-09-02 00:18:52 +0000769 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedman19a546c2009-02-22 02:56:25 +0000770
John McCall33ddac02011-01-19 10:06:00 +0000771 // Walk through any array types while we're at it.
772 T = getBaseElementType(arrayType);
773 }
Chad Rosier99ee7822011-07-26 07:03:04 +0000774 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedman19a546c2009-02-22 02:56:25 +0000775 }
John McCall4e819612011-01-20 07:57:12 +0000776
777 // Fields can be subject to extra alignment constraints, like if
778 // the field is packed, the struct is packed, or the struct has a
779 // a max-field-alignment constraint (#pragma pack). So calculate
780 // the actual alignment of the field within the struct, and then
781 // (as we're expected to) constrain that by the alignment of the type.
782 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
783 // So calculate the alignment of the field.
784 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
785
786 // Start with the record's overall alignment.
Ken Dyck7ad11e72011-02-15 02:32:40 +0000787 unsigned fieldAlign = toBits(layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +0000788
789 // Use the GCD of that and the offset within the record.
790 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
791 if (offset > 0) {
792 // Alignment is always a power of 2, so the GCD will be a power of 2,
793 // which means we get to do this crazy thing instead of Euclid's.
794 uint64_t lowBitOfOffset = offset & (~offset + 1);
795 if (lowBitOfOffset < fieldAlign)
796 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
797 }
798
799 Align = std::min(Align, fieldAlign);
Charles Davis3fc51072010-02-23 04:52:00 +0000800 }
Chris Lattner68061312009-01-24 21:53:27 +0000801 }
Eli Friedman19a546c2009-02-22 02:56:25 +0000802
Ken Dyckcc56c542011-01-15 18:38:59 +0000803 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +0000804}
Chris Lattner9a8d1d92008-06-30 18:32:54 +0000805
John McCall87fe5d52010-05-20 01:18:31 +0000806std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000807ASTContext::getTypeInfoInChars(const Type *T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000808 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckcc56c542011-01-15 18:38:59 +0000809 return std::make_pair(toCharUnitsFromBits(Info.first),
810 toCharUnitsFromBits(Info.second));
John McCall87fe5d52010-05-20 01:18:31 +0000811}
812
813std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +0000814ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +0000815 return getTypeInfoInChars(T.getTypePtr());
816}
817
Chris Lattner983a8bb2007-07-13 22:13:22 +0000818/// getTypeSize - Return the size of the specified type, in bits. This method
819/// does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +0000820///
821/// FIXME: Pointers into different addr spaces could have different sizes and
822/// alignment requirements: getPointerInfo should take an AddrSpace, this
823/// should take a QualType, &c.
Chris Lattner4481b422007-07-14 01:29:45 +0000824std::pair<uint64_t, unsigned>
Jay Foad39c79802011-01-12 09:06:06 +0000825ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5b9a3d52009-02-27 18:32:39 +0000826 uint64_t Width=0;
827 unsigned Align=8;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000828 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000829#define TYPE(Class, Base)
830#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +0000831#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000832#define DEPENDENT_TYPE(Class, Base) case Type::Class:
833#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +0000834 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000835
Chris Lattner355332d2007-07-13 22:27:08 +0000836 case Type::FunctionNoProto:
837 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +0000838 // GCC extension: alignof(function) = 32 bits
839 Width = 0;
840 Align = 32;
841 break;
842
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000843 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +0000844 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +0000845 Width = 0;
846 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
847 break;
848
Steve Naroff5c131802007-08-30 01:06:46 +0000849 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +0000850 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000851
Chris Lattner37e05872008-03-05 18:54:05 +0000852 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +0000853 uint64_t Size = CAT->getSize().getZExtValue();
854 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) && "Overflow in array type bit size evaluation");
855 Width = EltInfo.first*Size;
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000856 Align = EltInfo.second;
Argyrios Kyrtzidisae40e4e2011-04-26 21:05:39 +0000857 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000858 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +0000859 }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000860 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000861 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +0000862 const VectorType *VT = cast<VectorType>(T);
863 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
864 Width = EltInfo.first*VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +0000865 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +0000866 // If the alignment is not a power of 2, round up to the next power of 2.
867 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +0000868 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +0000869 Align = llvm::NextPowerOf2(Align);
870 Width = llvm::RoundUpToAlignment(Width, Align);
871 }
Chris Lattnerf2e101f2007-07-19 22:06:24 +0000872 break;
873 }
Chris Lattner647fb222007-07-18 18:26:58 +0000874
Chris Lattner7570e9c2008-03-08 08:52:55 +0000875 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +0000876 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +0000877 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +0000878 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +0000879 // GCC extension: alignof(void) = 8 bits.
880 Width = 0;
881 Align = 8;
882 break;
883
Chris Lattner6a4f7452007-12-19 19:23:28 +0000884 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000885 Width = Target->getBoolWidth();
886 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000887 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000888 case BuiltinType::Char_S:
889 case BuiltinType::Char_U:
890 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000891 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000892 Width = Target->getCharWidth();
893 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000894 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +0000895 case BuiltinType::WChar_S:
896 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000897 Width = Target->getWCharWidth();
898 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +0000899 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000900 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000901 Width = Target->getChar16Width();
902 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000903 break;
904 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000905 Width = Target->getChar32Width();
906 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +0000907 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000908 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000909 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000910 Width = Target->getShortWidth();
911 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000912 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000913 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000914 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000915 Width = Target->getIntWidth();
916 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000917 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000918 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000919 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000920 Width = Target->getLongWidth();
921 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000922 break;
Chris Lattner355332d2007-07-13 22:27:08 +0000923 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +0000924 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000925 Width = Target->getLongLongWidth();
926 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000927 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +0000928 case BuiltinType::Int128:
929 case BuiltinType::UInt128:
930 Width = 128;
931 Align = 128; // int128_t is 128-bit aligned on all targets.
932 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000933 case BuiltinType::Half:
934 Width = Target->getHalfWidth();
935 Align = Target->getHalfAlign();
936 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +0000937 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000938 Width = Target->getFloatWidth();
939 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000940 break;
941 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000942 Width = Target->getDoubleWidth();
943 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000944 break;
945 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000946 Width = Target->getLongDoubleWidth();
947 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +0000948 break;
Sebastian Redl576fd422009-05-10 18:38:11 +0000949 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000950 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
951 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +0000952 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000953 case BuiltinType::ObjCId:
954 case BuiltinType::ObjCClass:
955 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000956 Width = Target->getPointerWidth(0);
957 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +0000958 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +0000959 }
Chris Lattner48f84b82007-07-15 23:46:53 +0000960 break;
Steve Narofffb4330f2009-06-17 22:40:22 +0000961 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000962 Width = Target->getPointerWidth(0);
963 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +0000964 break;
Steve Naroff921a45c2008-09-24 15:05:44 +0000965 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000966 unsigned AS = getTargetAddressSpace(
967 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000968 Width = Target->getPointerWidth(AS);
969 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +0000970 break;
971 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000972 case Type::LValueReference:
973 case Type::RValueReference: {
974 // alignof and sizeof should never enter this code path here, so we go
975 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000976 unsigned AS = getTargetAddressSpace(
977 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000978 Width = Target->getPointerWidth(AS);
979 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +0000980 break;
981 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000982 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000983 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000984 Width = Target->getPointerWidth(AS);
985 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +0000986 break;
987 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000988 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +0000989 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump11289f42009-09-09 15:08:12 +0000990 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson32440a02009-05-17 02:06:04 +0000991 getTypeInfo(getPointerDiffType());
Charles Davis53c59df2010-08-16 03:33:14 +0000992 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +0000993 Align = PtrDiffInfo.second;
994 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +0000995 }
Chris Lattner647fb222007-07-18 18:26:58 +0000996 case Type::Complex: {
997 // Complex types have the same alignment as their elements, but twice the
998 // size.
Mike Stump11289f42009-09-09 15:08:12 +0000999 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner37e05872008-03-05 18:54:05 +00001000 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner7570e9c2008-03-08 08:52:55 +00001001 Width = EltInfo.first*2;
Chris Lattner647fb222007-07-18 18:26:58 +00001002 Align = EltInfo.second;
1003 break;
1004 }
John McCall8b07ec22010-05-15 11:32:37 +00001005 case Type::ObjCObject:
1006 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001007 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001008 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001009 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001010 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001011 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001012 break;
1013 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001014 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001015 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001016 const TagType *TT = cast<TagType>(T);
1017
1018 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001019 Width = 8;
1020 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001021 break;
1022 }
Mike Stump11289f42009-09-09 15:08:12 +00001023
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001024 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner8b23c252008-04-06 22:05:18 +00001025 return getTypeInfo(ET->getDecl()->getIntegerType());
1026
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001027 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner8b23c252008-04-06 22:05:18 +00001028 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001029 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001030 Align = toBits(Layout.getAlignment());
Chris Lattner49a953a2007-07-23 22:46:22 +00001031 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001032 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001033
Chris Lattner63d2b362009-10-22 05:17:15 +00001034 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001035 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1036 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001037
Richard Smith30482bc2011-02-20 03:19:35 +00001038 case Type::Auto: {
1039 const AutoType *A = cast<AutoType>(T);
1040 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001041 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001042 }
1043
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001044 case Type::Paren:
1045 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1046
Douglas Gregoref462e62009-04-30 17:32:17 +00001047 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001048 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregorf5bae222010-08-27 00:11:28 +00001049 std::pair<uint64_t, unsigned> Info
1050 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001051 // If the typedef has an aligned attribute on it, it overrides any computed
1052 // alignment we have. This violates the GCC documentation (which says that
1053 // attribute(aligned) can only round up) but matches its implementation.
1054 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1055 Align = AttrAlign;
1056 else
1057 Align = Info.second;
Douglas Gregorf5bae222010-08-27 00:11:28 +00001058 Width = Info.first;
Douglas Gregordc572a32009-03-30 22:58:21 +00001059 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001060 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001061
1062 case Type::TypeOfExpr:
1063 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1064 .getTypePtr());
1065
1066 case Type::TypeOf:
1067 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1068
Anders Carlsson81df7b82009-06-24 19:06:50 +00001069 case Type::Decltype:
1070 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1071 .getTypePtr());
1072
Alexis Hunte852b102011-05-24 22:41:36 +00001073 case Type::UnaryTransform:
1074 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1075
Abramo Bagnara6150c882010-05-11 21:36:43 +00001076 case Type::Elaborated:
1077 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001078
John McCall81904512011-01-06 01:58:22 +00001079 case Type::Attributed:
1080 return getTypeInfo(
1081 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1082
Richard Smith3f1b5d02011-05-05 21:57:07 +00001083 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00001084 assert(getCanonicalType(T) != T &&
Douglas Gregoref462e62009-04-30 17:32:17 +00001085 "Cannot request the size of a dependent type");
Richard Smith3f1b5d02011-05-05 21:57:07 +00001086 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1087 // A type alias template specialization may refer to a typedef with the
1088 // aligned attribute on it.
1089 if (TST->isTypeAlias())
1090 return getTypeInfo(TST->getAliasedType().getTypePtr());
1091 else
1092 return getTypeInfo(getCanonicalType(T));
1093 }
1094
Eli Friedman0dfb8892011-10-06 23:00:33 +00001095 case Type::Atomic: {
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001096 std::pair<uint64_t, unsigned> Info
1097 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1098 Width = Info.first;
1099 Align = Info.second;
1100 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1101 llvm::isPowerOf2_64(Width)) {
1102 // We can potentially perform lock-free atomic operations for this
1103 // type; promote the alignment appropriately.
1104 // FIXME: We could potentially promote the width here as well...
1105 // is that worthwhile? (Non-struct atomic types generally have
1106 // power-of-two size anyway, but structs might not. Requires a bit
1107 // of implementation work to make sure we zero out the extra bits.)
1108 Align = static_cast<unsigned>(Width);
1109 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001110 }
1111
Douglas Gregoref462e62009-04-30 17:32:17 +00001112 }
Mike Stump11289f42009-09-09 15:08:12 +00001113
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001114 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner7570e9c2008-03-08 08:52:55 +00001115 return std::make_pair(Width, Align);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001116}
1117
Ken Dyckcc56c542011-01-15 18:38:59 +00001118/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1119CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1120 return CharUnits::fromQuantity(BitSize / getCharWidth());
1121}
1122
Ken Dyckb0fcc592011-02-11 01:54:29 +00001123/// toBits - Convert a size in characters to a size in characters.
1124int64_t ASTContext::toBits(CharUnits CharSize) const {
1125 return CharSize.getQuantity() * getCharWidth();
1126}
1127
Ken Dyck8c89d592009-12-22 14:23:30 +00001128/// getTypeSizeInChars - Return the size of the specified type, in characters.
1129/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001130CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001131 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001132}
Jay Foad39c79802011-01-12 09:06:06 +00001133CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001134 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyck8c89d592009-12-22 14:23:30 +00001135}
1136
Ken Dycka6046ab2010-01-26 17:25:18 +00001137/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001138/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001139CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001140 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001141}
Jay Foad39c79802011-01-12 09:06:06 +00001142CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001143 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001144}
1145
Chris Lattnera3402cd2009-01-27 18:08:34 +00001146/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1147/// type for the current target in bits. This can be different than the ABI
1148/// alignment in cases where it is beneficial for performance to overalign
1149/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001150unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattnera3402cd2009-01-27 18:08:34 +00001151 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman7ab09572009-05-25 21:27:19 +00001152
1153 // Double and long long should be naturally aligned if possible.
John McCall9dd450b2009-09-21 23:43:11 +00001154 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00001155 T = CT->getElementType().getTypePtr();
1156 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1157 T->isSpecificBuiltinType(BuiltinType::LongLong))
1158 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1159
Chris Lattnera3402cd2009-01-27 18:08:34 +00001160 return ABIAlign;
1161}
1162
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001163/// DeepCollectObjCIvars -
1164/// This routine first collects all declared, but not synthesized, ivars in
1165/// super class and then collects all ivars, including those synthesized for
1166/// current class. This routine is used for implementation of current class
1167/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001168///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001169void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1170 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00001171 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00001172 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1173 DeepCollectObjCIvars(SuperClass, false, Ivars);
1174 if (!leafClass) {
1175 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1176 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001177 Ivars.push_back(*I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001178 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001179 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00001180 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001181 Iv= Iv->getNextIvar())
1182 Ivars.push_back(Iv);
1183 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00001184}
1185
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001186/// CollectInheritedProtocols - Collect all protocols in current class and
1187/// those inherited by it.
1188void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00001189 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001190 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001191 // We can use protocol_iterator here instead of
1192 // all_referenced_protocol_iterator since we are walking all categories.
1193 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1194 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001195 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001196 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001197 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001198 PE = Proto->protocol_end(); P != PE; ++P) {
Douglas Gregor33b24292012-01-01 18:09:12 +00001199 Protocols.insert((*P)->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001200 CollectInheritedProtocols(*P, Protocols);
1201 }
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00001202 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001203
1204 // Categories of this Interface.
1205 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1206 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1207 CollectInheritedProtocols(CDeclChain, Protocols);
1208 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1209 while (SD) {
1210 CollectInheritedProtocols(SD, Protocols);
1211 SD = SD->getSuperClass();
1212 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001213 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001214 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001215 PE = OC->protocol_end(); P != PE; ++P) {
1216 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001217 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001218 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1219 PE = Proto->protocol_end(); P != PE; ++P)
1220 CollectInheritedProtocols(*P, Protocols);
1221 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001222 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001223 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1224 PE = OP->protocol_end(); P != PE; ++P) {
1225 ObjCProtocolDecl *Proto = (*P);
Douglas Gregor33b24292012-01-01 18:09:12 +00001226 Protocols.insert(Proto->getCanonicalDecl());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001227 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1228 PE = Proto->protocol_end(); P != PE; ++P)
1229 CollectInheritedProtocols(*P, Protocols);
1230 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00001231 }
1232}
1233
Jay Foad39c79802011-01-12 09:06:06 +00001234unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001235 unsigned count = 0;
1236 // Count ivars declared in class extension.
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001237 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1238 CDecl = CDecl->getNextClassExtension())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001239 count += CDecl->ivar_size();
1240
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00001241 // Count ivar defined in this class's implementation. This
1242 // includes synthesized ivars.
1243 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00001244 count += ImplDecl->ivar_size();
1245
Fariborz Jahanian7c809592009-06-04 01:19:09 +00001246 return count;
1247}
1248
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00001249bool ASTContext::isSentinelNullExpr(const Expr *E) {
1250 if (!E)
1251 return false;
1252
1253 // nullptr_t is always treated as null.
1254 if (E->getType()->isNullPtrType()) return true;
1255
1256 if (E->getType()->isAnyPointerType() &&
1257 E->IgnoreParenCasts()->isNullPointerConstant(*this,
1258 Expr::NPC_ValueDependentIsNull))
1259 return true;
1260
1261 // Unfortunately, __null has type 'int'.
1262 if (isa<GNUNullExpr>(E)) return true;
1263
1264 return false;
1265}
1266
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001267/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1268ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1269 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1270 I = ObjCImpls.find(D);
1271 if (I != ObjCImpls.end())
1272 return cast<ObjCImplementationDecl>(I->second);
1273 return 0;
1274}
1275/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1276ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1277 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1278 I = ObjCImpls.find(D);
1279 if (I != ObjCImpls.end())
1280 return cast<ObjCCategoryImplDecl>(I->second);
1281 return 0;
1282}
1283
1284/// \brief Set the implementation of ObjCInterfaceDecl.
1285void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1286 ObjCImplementationDecl *ImplD) {
1287 assert(IFaceD && ImplD && "Passed null params");
1288 ObjCImpls[IFaceD] = ImplD;
1289}
1290/// \brief Set the implementation of ObjCCategoryDecl.
1291void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1292 ObjCCategoryImplDecl *ImplD) {
1293 assert(CatD && ImplD && "Passed null params");
1294 ObjCImpls[CatD] = ImplD;
1295}
1296
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00001297ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1298 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1299 return ID;
1300 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1301 return CD->getClassInterface();
1302 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1303 return IMD->getClassInterface();
1304
1305 return 0;
1306}
1307
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001308/// \brief Get the copy initialization expression of VarDecl,or NULL if
1309/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00001310Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001311 assert(VD && "Passed null params");
1312 assert(VD->hasAttr<BlocksAttr>() &&
1313 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00001314 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001315 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001316 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1317}
1318
1319/// \brief Set the copy inialization expression of a block var decl.
1320void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1321 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00001322 assert(VD->hasAttr<BlocksAttr>() &&
1323 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00001324 BlockVarCopyInits[VD] = Init;
1325}
1326
John McCallbcd03502009-12-07 02:54:59 +00001327/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001328///
John McCallbcd03502009-12-07 02:54:59 +00001329/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001330/// the TypeLoc wrappers.
1331///
1332/// \param T the type that will be the basis for type source info. This type
1333/// should refer to how the declarator was written in source code, not to
1334/// what type semantic analysis resolved the declarator to.
John McCallbcd03502009-12-07 02:54:59 +00001335TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001336 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00001337 if (!DataSize)
1338 DataSize = TypeLoc::getFullDataSizeForType(T);
1339 else
1340 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00001341 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00001342
John McCallbcd03502009-12-07 02:54:59 +00001343 TypeSourceInfo *TInfo =
1344 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1345 new (TInfo) TypeSourceInfo(T);
1346 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00001347}
1348
John McCallbcd03502009-12-07 02:54:59 +00001349TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001350 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00001351 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00001352 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00001353 return DI;
1354}
1355
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001356const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001357ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001358 return getObjCLayout(D, 0);
1359}
1360
1361const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00001362ASTContext::getASTObjCImplementationLayout(
1363 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00001364 return getObjCLayout(D->getClassInterface(), D);
1365}
1366
Chris Lattner983a8bb2007-07-13 22:13:22 +00001367//===----------------------------------------------------------------------===//
1368// Type creation/memoization methods
1369//===----------------------------------------------------------------------===//
1370
Jay Foad39c79802011-01-12 09:06:06 +00001371QualType
John McCall33ddac02011-01-19 10:06:00 +00001372ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1373 unsigned fastQuals = quals.getFastQualifiers();
1374 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00001375
1376 // Check if we've already instantiated this type.
1377 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001378 ExtQuals::Profile(ID, baseType, quals);
1379 void *insertPos = 0;
1380 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1381 assert(eq->getQualifiers() == quals);
1382 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001383 }
1384
John McCall33ddac02011-01-19 10:06:00 +00001385 // If the base type is not canonical, make the appropriate canonical type.
1386 QualType canon;
1387 if (!baseType->isCanonicalUnqualified()) {
1388 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00001389 canonSplit.Quals.addConsistentQualifiers(quals);
1390 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001391
1392 // Re-find the insert position.
1393 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1394 }
1395
1396 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1397 ExtQualNodes.InsertNode(eq, insertPos);
1398 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00001399}
1400
Jay Foad39c79802011-01-12 09:06:06 +00001401QualType
1402ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001403 QualType CanT = getCanonicalType(T);
1404 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00001405 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00001406
John McCall8ccfcb52009-09-24 19:53:00 +00001407 // If we are composing extended qualifiers together, merge together
1408 // into one ExtQuals node.
1409 QualifierCollector Quals;
1410 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001411
John McCall8ccfcb52009-09-24 19:53:00 +00001412 // If this type already has an address space specified, it cannot get
1413 // another one.
1414 assert(!Quals.hasAddressSpace() &&
1415 "Type cannot be in multiple addr spaces!");
1416 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00001417
John McCall8ccfcb52009-09-24 19:53:00 +00001418 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00001419}
1420
Chris Lattnerd60183d2009-02-18 22:53:11 +00001421QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00001422 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001423 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00001424 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001425 return T;
Mike Stump11289f42009-09-09 15:08:12 +00001426
John McCall53fa7142010-12-24 02:08:15 +00001427 if (const PointerType *ptr = T->getAs<PointerType>()) {
1428 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00001429 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00001430 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1431 return getPointerType(ResultType);
1432 }
1433 }
Mike Stump11289f42009-09-09 15:08:12 +00001434
John McCall8ccfcb52009-09-24 19:53:00 +00001435 // If we are composing extended qualifiers together, merge together
1436 // into one ExtQuals node.
1437 QualifierCollector Quals;
1438 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00001439
John McCall8ccfcb52009-09-24 19:53:00 +00001440 // If this type already has an ObjCGC specified, it cannot get
1441 // another one.
1442 assert(!Quals.hasObjCGCAttr() &&
1443 "Type cannot have multiple ObjCGCs!");
1444 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00001445
John McCall8ccfcb52009-09-24 19:53:00 +00001446 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00001447}
Chris Lattner983a8bb2007-07-13 22:13:22 +00001448
John McCall4f5019e2010-12-19 02:44:49 +00001449const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1450 FunctionType::ExtInfo Info) {
1451 if (T->getExtInfo() == Info)
1452 return T;
1453
1454 QualType Result;
1455 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1456 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1457 } else {
1458 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1459 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1460 EPI.ExtInfo = Info;
1461 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1462 FPT->getNumArgs(), EPI);
1463 }
1464
1465 return cast<FunctionType>(Result.getTypePtr());
1466}
1467
Chris Lattnerc6395932007-06-22 20:56:16 +00001468/// getComplexType - Return the uniqued reference to the type for a complex
1469/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00001470QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00001471 // Unique pointers, to guarantee there is only one pointer of a particular
1472 // structure.
1473 llvm::FoldingSetNodeID ID;
1474 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001475
Chris Lattnerc6395932007-06-22 20:56:16 +00001476 void *InsertPos = 0;
1477 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1478 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001479
Chris Lattnerc6395932007-06-22 20:56:16 +00001480 // If the pointee type isn't canonical, this won't be a canonical type either,
1481 // so fill in the canonical type field.
1482 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001483 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001484 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001485
Chris Lattnerc6395932007-06-22 20:56:16 +00001486 // Get the new insert position for the node we care about.
1487 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001488 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00001489 }
John McCall90d1c2d2009-09-24 23:30:46 +00001490 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00001491 Types.push_back(New);
1492 ComplexTypes.InsertNode(New, InsertPos);
1493 return QualType(New, 0);
1494}
1495
Chris Lattner970e54e2006-11-12 00:37:36 +00001496/// getPointerType - Return the uniqued reference to the type for a pointer to
1497/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001498QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001499 // Unique pointers, to guarantee there is only one pointer of a particular
1500 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001501 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00001502 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001503
Chris Lattner67521df2007-01-27 01:29:36 +00001504 void *InsertPos = 0;
1505 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001506 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001507
Chris Lattner7ccecb92006-11-12 08:50:50 +00001508 // If the pointee type isn't canonical, this won't be a canonical type either,
1509 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001510 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001511 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00001512 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001513
Chris Lattner67521df2007-01-27 01:29:36 +00001514 // Get the new insert position for the node we care about.
1515 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001516 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner67521df2007-01-27 01:29:36 +00001517 }
John McCall90d1c2d2009-09-24 23:30:46 +00001518 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00001519 Types.push_back(New);
1520 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001521 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00001522}
1523
Mike Stump11289f42009-09-09 15:08:12 +00001524/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00001525/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00001526QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00001527 assert(T->isFunctionType() && "block of function types only");
1528 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00001529 // structure.
1530 llvm::FoldingSetNodeID ID;
1531 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00001532
Steve Naroffec33ed92008-08-27 16:04:49 +00001533 void *InsertPos = 0;
1534 if (BlockPointerType *PT =
1535 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1536 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001537
1538 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00001539 // type either so fill in the canonical type field.
1540 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00001541 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00001542 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00001543
Steve Naroffec33ed92008-08-27 16:04:49 +00001544 // Get the new insert position for the node we care about.
1545 BlockPointerType *NewIP =
1546 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001547 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00001548 }
John McCall90d1c2d2009-09-24 23:30:46 +00001549 BlockPointerType *New
1550 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00001551 Types.push_back(New);
1552 BlockPointerTypes.InsertNode(New, InsertPos);
1553 return QualType(New, 0);
1554}
1555
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001556/// getLValueReferenceType - Return the uniqued reference to the type for an
1557/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001558QualType
1559ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00001560 assert(getCanonicalType(T) != OverloadTy &&
1561 "Unresolved overloaded function type");
1562
Bill Wendling3708c182007-05-27 10:15:43 +00001563 // Unique pointers, to guarantee there is only one pointer of a particular
1564 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001565 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001566 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001567
1568 void *InsertPos = 0;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001569 if (LValueReferenceType *RT =
1570 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00001571 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001572
John McCallfc93cf92009-10-22 22:37:11 +00001573 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1574
Bill Wendling3708c182007-05-27 10:15:43 +00001575 // If the referencee type isn't canonical, this won't be a canonical type
1576 // either, so fill in the canonical type field.
1577 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001578 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1579 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1580 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001581
Bill Wendling3708c182007-05-27 10:15:43 +00001582 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001583 LValueReferenceType *NewIP =
1584 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001585 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00001586 }
1587
John McCall90d1c2d2009-09-24 23:30:46 +00001588 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00001589 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1590 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00001591 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001592 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00001593
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001594 return QualType(New, 0);
1595}
1596
1597/// getRValueReferenceType - Return the uniqued reference to the type for an
1598/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00001599QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001600 // Unique pointers, to guarantee there is only one pointer of a particular
1601 // structure.
1602 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00001603 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001604
1605 void *InsertPos = 0;
1606 if (RValueReferenceType *RT =
1607 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1608 return QualType(RT, 0);
1609
John McCallfc93cf92009-10-22 22:37:11 +00001610 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1611
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001612 // If the referencee type isn't canonical, this won't be a canonical type
1613 // either, so fill in the canonical type field.
1614 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00001615 if (InnerRef || !T.isCanonical()) {
1616 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1617 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001618
1619 // Get the new insert position for the node we care about.
1620 RValueReferenceType *NewIP =
1621 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001622 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001623 }
1624
John McCall90d1c2d2009-09-24 23:30:46 +00001625 RValueReferenceType *New
1626 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001627 Types.push_back(New);
1628 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00001629 return QualType(New, 0);
1630}
1631
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001632/// getMemberPointerType - Return the uniqued reference to the type for a
1633/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00001634QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001635 // Unique pointers, to guarantee there is only one pointer of a particular
1636 // structure.
1637 llvm::FoldingSetNodeID ID;
1638 MemberPointerType::Profile(ID, T, Cls);
1639
1640 void *InsertPos = 0;
1641 if (MemberPointerType *PT =
1642 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1643 return QualType(PT, 0);
1644
1645 // If the pointee or class type isn't canonical, this won't be a canonical
1646 // type either, so fill in the canonical type field.
1647 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00001648 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001649 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1650
1651 // Get the new insert position for the node we care about.
1652 MemberPointerType *NewIP =
1653 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001654 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001655 }
John McCall90d1c2d2009-09-24 23:30:46 +00001656 MemberPointerType *New
1657 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001658 Types.push_back(New);
1659 MemberPointerTypes.InsertNode(New, InsertPos);
1660 return QualType(New, 0);
1661}
1662
Mike Stump11289f42009-09-09 15:08:12 +00001663/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00001664/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00001665QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00001666 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001667 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001668 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00001669 assert((EltTy->isDependentType() ||
1670 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001671 "Constant array of VLAs is illegal!");
1672
Chris Lattnere2df3f92009-05-13 04:12:56 +00001673 // Convert the array size into a canonical width matching the pointer size for
1674 // the target.
1675 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001676 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001677 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00001678
Chris Lattner23b7eb62007-06-15 23:05:46 +00001679 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00001680 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00001681
Chris Lattner36f8e652007-01-27 08:31:04 +00001682 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001683 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001684 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001685 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001686
John McCall33ddac02011-01-19 10:06:00 +00001687 // If the element type isn't canonical or has qualifiers, this won't
1688 // be a canonical type either, so fill in the canonical type field.
1689 QualType Canon;
1690 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1691 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001692 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001693 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001694 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00001695
Chris Lattner36f8e652007-01-27 08:31:04 +00001696 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00001697 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00001698 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001699 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00001700 }
Mike Stump11289f42009-09-09 15:08:12 +00001701
John McCall90d1c2d2009-09-24 23:30:46 +00001702 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001703 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00001704 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00001705 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00001706 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00001707}
1708
John McCall06549462011-01-18 08:40:38 +00001709/// getVariableArrayDecayedType - Turns the given type, which may be
1710/// variably-modified, into the corresponding type with all the known
1711/// sizes replaced with [*].
1712QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1713 // Vastly most common case.
1714 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001715
John McCall06549462011-01-18 08:40:38 +00001716 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001717
John McCall06549462011-01-18 08:40:38 +00001718 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00001719 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00001720 switch (ty->getTypeClass()) {
1721#define TYPE(Class, Base)
1722#define ABSTRACT_TYPE(Class, Base)
1723#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1724#include "clang/AST/TypeNodes.def"
1725 llvm_unreachable("didn't desugar past all non-canonical types?");
1726
1727 // These types should never be variably-modified.
1728 case Type::Builtin:
1729 case Type::Complex:
1730 case Type::Vector:
1731 case Type::ExtVector:
1732 case Type::DependentSizedExtVector:
1733 case Type::ObjCObject:
1734 case Type::ObjCInterface:
1735 case Type::ObjCObjectPointer:
1736 case Type::Record:
1737 case Type::Enum:
1738 case Type::UnresolvedUsing:
1739 case Type::TypeOfExpr:
1740 case Type::TypeOf:
1741 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00001742 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00001743 case Type::DependentName:
1744 case Type::InjectedClassName:
1745 case Type::TemplateSpecialization:
1746 case Type::DependentTemplateSpecialization:
1747 case Type::TemplateTypeParm:
1748 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00001749 case Type::Auto:
John McCall06549462011-01-18 08:40:38 +00001750 case Type::PackExpansion:
1751 llvm_unreachable("type should never be variably-modified");
1752
1753 // These types can be variably-modified but should never need to
1754 // further decay.
1755 case Type::FunctionNoProto:
1756 case Type::FunctionProto:
1757 case Type::BlockPointer:
1758 case Type::MemberPointer:
1759 return type;
1760
1761 // These types can be variably-modified. All these modifications
1762 // preserve structure except as noted by comments.
1763 // TODO: if we ever care about optimizing VLAs, there are no-op
1764 // optimizations available here.
1765 case Type::Pointer:
1766 result = getPointerType(getVariableArrayDecayedType(
1767 cast<PointerType>(ty)->getPointeeType()));
1768 break;
1769
1770 case Type::LValueReference: {
1771 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1772 result = getLValueReferenceType(
1773 getVariableArrayDecayedType(lv->getPointeeType()),
1774 lv->isSpelledAsLValue());
1775 break;
1776 }
1777
1778 case Type::RValueReference: {
1779 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1780 result = getRValueReferenceType(
1781 getVariableArrayDecayedType(lv->getPointeeType()));
1782 break;
1783 }
1784
Eli Friedman0dfb8892011-10-06 23:00:33 +00001785 case Type::Atomic: {
1786 const AtomicType *at = cast<AtomicType>(ty);
1787 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1788 break;
1789 }
1790
John McCall06549462011-01-18 08:40:38 +00001791 case Type::ConstantArray: {
1792 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1793 result = getConstantArrayType(
1794 getVariableArrayDecayedType(cat->getElementType()),
1795 cat->getSize(),
1796 cat->getSizeModifier(),
1797 cat->getIndexTypeCVRQualifiers());
1798 break;
1799 }
1800
1801 case Type::DependentSizedArray: {
1802 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1803 result = getDependentSizedArrayType(
1804 getVariableArrayDecayedType(dat->getElementType()),
1805 dat->getSizeExpr(),
1806 dat->getSizeModifier(),
1807 dat->getIndexTypeCVRQualifiers(),
1808 dat->getBracketsRange());
1809 break;
1810 }
1811
1812 // Turn incomplete types into [*] types.
1813 case Type::IncompleteArray: {
1814 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1815 result = getVariableArrayType(
1816 getVariableArrayDecayedType(iat->getElementType()),
1817 /*size*/ 0,
1818 ArrayType::Normal,
1819 iat->getIndexTypeCVRQualifiers(),
1820 SourceRange());
1821 break;
1822 }
1823
1824 // Turn VLA types into [*] types.
1825 case Type::VariableArray: {
1826 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1827 result = getVariableArrayType(
1828 getVariableArrayDecayedType(vat->getElementType()),
1829 /*size*/ 0,
1830 ArrayType::Star,
1831 vat->getIndexTypeCVRQualifiers(),
1832 vat->getBracketsRange());
1833 break;
1834 }
1835 }
1836
1837 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00001838 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00001839}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001840
Steve Naroffcadebd02007-08-30 18:14:25 +00001841/// getVariableArrayType - Returns a non-unique reference to the type for a
1842/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00001843QualType ASTContext::getVariableArrayType(QualType EltTy,
1844 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00001845 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001846 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00001847 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001848 // Since we don't unique expressions, it isn't possible to unique VLA's
1849 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00001850 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001851
John McCall33ddac02011-01-19 10:06:00 +00001852 // Be sure to pull qualifiers off the element type.
1853 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1854 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00001855 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00001856 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00001857 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00001858 }
1859
John McCall90d1c2d2009-09-24 23:30:46 +00001860 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00001861 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00001862
1863 VariableArrayTypes.push_back(New);
1864 Types.push_back(New);
1865 return QualType(New, 0);
1866}
1867
Douglas Gregor4619e432008-12-05 23:32:09 +00001868/// getDependentSizedArrayType - Returns a non-unique reference to
1869/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00001870/// type.
John McCall33ddac02011-01-19 10:06:00 +00001871QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1872 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00001873 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001874 unsigned elementTypeQuals,
1875 SourceRange brackets) const {
1876 assert((!numElements || numElements->isTypeDependent() ||
1877 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00001878 "Size must be type- or value-dependent!");
1879
John McCall33ddac02011-01-19 10:06:00 +00001880 // Dependently-sized array types that do not have a specified number
1881 // of elements will have their sizes deduced from a dependent
1882 // initializer. We do no canonicalization here at all, which is okay
1883 // because they can't be used in most locations.
1884 if (!numElements) {
1885 DependentSizedArrayType *newType
1886 = new (*this, TypeAlignment)
1887 DependentSizedArrayType(*this, elementType, QualType(),
1888 numElements, ASM, elementTypeQuals,
1889 brackets);
1890 Types.push_back(newType);
1891 return QualType(newType, 0);
1892 }
1893
1894 // Otherwise, we actually build a new type every time, but we
1895 // also build a canonical type.
1896
1897 SplitQualType canonElementType = getCanonicalType(elementType).split();
1898
1899 void *insertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00001900 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001901 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00001902 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001903 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001904
John McCall33ddac02011-01-19 10:06:00 +00001905 // Look for an existing type with these properties.
1906 DependentSizedArrayType *canonTy =
1907 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001908
John McCall33ddac02011-01-19 10:06:00 +00001909 // If we don't have one, build one.
1910 if (!canonTy) {
1911 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00001912 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001913 QualType(), numElements, ASM, elementTypeQuals,
1914 brackets);
1915 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1916 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00001917 }
1918
John McCall33ddac02011-01-19 10:06:00 +00001919 // Apply qualifiers from the element type to the array.
1920 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00001921 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00001922
John McCall33ddac02011-01-19 10:06:00 +00001923 // If we didn't need extra canonicalization for the element type,
1924 // then just use that as our result.
John McCall18ce25e2012-02-08 00:46:36 +00001925 if (QualType(canonElementType.Ty, 0) == elementType)
John McCall33ddac02011-01-19 10:06:00 +00001926 return canon;
1927
1928 // Otherwise, we need to build a type which follows the spelling
1929 // of the element type.
1930 DependentSizedArrayType *sugaredType
1931 = new (*this, TypeAlignment)
1932 DependentSizedArrayType(*this, elementType, canon, numElements,
1933 ASM, elementTypeQuals, brackets);
1934 Types.push_back(sugaredType);
1935 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00001936}
1937
John McCall33ddac02011-01-19 10:06:00 +00001938QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00001939 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00001940 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00001941 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00001942 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001943
John McCall33ddac02011-01-19 10:06:00 +00001944 void *insertPos = 0;
1945 if (IncompleteArrayType *iat =
1946 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1947 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00001948
1949 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00001950 // either, so fill in the canonical type field. We also have to pull
1951 // qualifiers off the element type.
1952 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00001953
John McCall33ddac02011-01-19 10:06:00 +00001954 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1955 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00001956 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00001957 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00001958 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001959
1960 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00001961 IncompleteArrayType *existing =
1962 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1963 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00001964 }
Eli Friedmanbd258282008-02-15 18:16:39 +00001965
John McCall33ddac02011-01-19 10:06:00 +00001966 IncompleteArrayType *newType = new (*this, TypeAlignment)
1967 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00001968
John McCall33ddac02011-01-19 10:06:00 +00001969 IncompleteArrayTypes.InsertNode(newType, insertPos);
1970 Types.push_back(newType);
1971 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00001972}
1973
Steve Naroff91fcddb2007-07-18 18:00:27 +00001974/// getVectorType - Return the unique reference to a vector type of
1975/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00001976QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00001977 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00001978 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00001979
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001980 // Check if we've already instantiated a vector of this type.
1981 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00001982 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00001983
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001984 void *InsertPos = 0;
1985 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1986 return QualType(VTP, 0);
1987
1988 // If the element type isn't canonical, this won't be a canonical type either,
1989 // so fill in the canonical type field.
1990 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001991 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00001992 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00001993
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001994 // Get the new insert position for the node we care about.
1995 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001996 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00001997 }
John McCall90d1c2d2009-09-24 23:30:46 +00001998 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00001999 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00002000 VectorTypes.InsertNode(New, InsertPos);
2001 Types.push_back(New);
2002 return QualType(New, 0);
2003}
2004
Nate Begemance4d7fc2008-04-18 23:10:10 +00002005/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00002006/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00002007QualType
2008ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00002009 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00002010
Steve Naroff91fcddb2007-07-18 18:00:27 +00002011 // Check if we've already instantiated a vector of this type.
2012 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00002013 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002014 VectorType::GenericVector);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002015 void *InsertPos = 0;
2016 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2017 return QualType(VTP, 0);
2018
2019 // If the element type isn't canonical, this won't be a canonical type either,
2020 // so fill in the canonical type field.
2021 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002022 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00002023 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00002024
Steve Naroff91fcddb2007-07-18 18:00:27 +00002025 // Get the new insert position for the node we care about.
2026 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002027 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00002028 }
John McCall90d1c2d2009-09-24 23:30:46 +00002029 ExtVectorType *New = new (*this, TypeAlignment)
2030 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00002031 VectorTypes.InsertNode(New, InsertPos);
2032 Types.push_back(New);
2033 return QualType(New, 0);
2034}
2035
Jay Foad39c79802011-01-12 09:06:06 +00002036QualType
2037ASTContext::getDependentSizedExtVectorType(QualType vecType,
2038 Expr *SizeExpr,
2039 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00002040 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00002041 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00002042 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002043
Douglas Gregor352169a2009-07-31 03:54:25 +00002044 void *InsertPos = 0;
2045 DependentSizedExtVectorType *Canon
2046 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2047 DependentSizedExtVectorType *New;
2048 if (Canon) {
2049 // We already have a canonical version of this array type; use it as
2050 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00002051 New = new (*this, TypeAlignment)
2052 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2053 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002054 } else {
2055 QualType CanonVecTy = getCanonicalType(vecType);
2056 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00002057 New = new (*this, TypeAlignment)
2058 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2059 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002060
2061 DependentSizedExtVectorType *CanonCheck
2062 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2063 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2064 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00002065 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2066 } else {
2067 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2068 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00002069 New = new (*this, TypeAlignment)
2070 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00002071 }
2072 }
Mike Stump11289f42009-09-09 15:08:12 +00002073
Douglas Gregor758a8692009-06-17 21:51:59 +00002074 Types.push_back(New);
2075 return QualType(New, 0);
2076}
2077
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002078/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002079///
Jay Foad39c79802011-01-12 09:06:06 +00002080QualType
2081ASTContext::getFunctionNoProtoType(QualType ResultTy,
2082 const FunctionType::ExtInfo &Info) const {
Roman Divacky65b88cd2011-03-01 17:40:53 +00002083 const CallingConv DefaultCC = Info.getCC();
2084 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2085 CC_X86StdCall : DefaultCC;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002086 // Unique functions, to guarantee there is only one function of a particular
2087 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002088 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002089 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00002090
Chris Lattner47955de2007-01-27 08:37:20 +00002091 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002092 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002093 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002094 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002095
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002096 QualType Canonical;
Douglas Gregor8c940862010-01-18 17:14:39 +00002097 if (!ResultTy.isCanonical() ||
John McCallab26cfa2010-02-05 21:31:56 +00002098 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002099 Canonical =
2100 getFunctionNoProtoType(getCanonicalType(ResultTy),
2101 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump11289f42009-09-09 15:08:12 +00002102
Chris Lattner47955de2007-01-27 08:37:20 +00002103 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002104 FunctionNoProtoType *NewIP =
2105 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002106 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00002107 }
Mike Stump11289f42009-09-09 15:08:12 +00002108
Roman Divacky65b88cd2011-03-01 17:40:53 +00002109 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall90d1c2d2009-09-24 23:30:46 +00002110 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divacky65b88cd2011-03-01 17:40:53 +00002111 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Chris Lattner47955de2007-01-27 08:37:20 +00002112 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002113 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002114 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002115}
2116
2117/// getFunctionType - Return a normal function type with a typed argument
2118/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad39c79802011-01-12 09:06:06 +00002119QualType
2120ASTContext::getFunctionType(QualType ResultTy,
2121 const QualType *ArgArray, unsigned NumArgs,
2122 const FunctionProtoType::ExtProtoInfo &EPI) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002123 // Unique functions, to guarantee there is only one function of a particular
2124 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002125 llvm::FoldingSetNodeID ID;
Sebastian Redl31ad7542011-03-13 17:09:40 +00002126 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Chris Lattnerfd4de792007-01-27 01:15:32 +00002127
2128 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002129 if (FunctionProtoType *FTP =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002130 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002131 return QualType(FTP, 0);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002132
2133 // Determine whether the type being created is already canonical or not.
Richard Smith5e580292012-02-10 09:58:53 +00002134 bool isCanonical =
2135 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2136 !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002137 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002138 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002139 isCanonical = false;
2140
Roman Divacky65b88cd2011-03-01 17:40:53 +00002141 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2142 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2143 CC_X86StdCall : DefaultCC;
John McCalldb40c7f2010-12-14 08:05:40 +00002144
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002145 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002146 // The exception spec is not part of the canonical type.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002147 QualType Canonical;
John McCallab26cfa2010-02-05 21:31:56 +00002148 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002149 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002150 CanonicalArgs.reserve(NumArgs);
2151 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00002152 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002153
John McCalldb40c7f2010-12-14 08:05:40 +00002154 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00002155 CanonicalEPI.HasTrailingReturn = false;
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00002156 CanonicalEPI.ExceptionSpecType = EST_None;
2157 CanonicalEPI.NumExceptions = 0;
John McCalldb40c7f2010-12-14 08:05:40 +00002158 CanonicalEPI.ExtInfo
2159 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2160
Chris Lattner76a00cf2008-04-06 22:59:24 +00002161 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foad7d0479f2009-05-21 09:52:38 +00002162 CanonicalArgs.data(), NumArgs,
John McCalldb40c7f2010-12-14 08:05:40 +00002163 CanonicalEPI);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002164
Chris Lattnerfd4de792007-01-27 01:15:32 +00002165 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002166 FunctionProtoType *NewIP =
2167 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002168 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002169 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002170
John McCall31168b02011-06-15 23:02:42 +00002171 // FunctionProtoType objects are allocated with extra bytes after
2172 // them for three variable size arrays at the end:
2173 // - parameter types
2174 // - exception types
2175 // - consumed-arguments flags
2176 // Instead of the exception types, there could be a noexcept
2177 // expression.
John McCalldb40c7f2010-12-14 08:05:40 +00002178 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002179 NumArgs * sizeof(QualType);
2180 if (EPI.ExceptionSpecType == EST_Dynamic)
2181 Size += EPI.NumExceptions * sizeof(QualType);
2182 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00002183 Size += sizeof(Expr*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002184 }
John McCall31168b02011-06-15 23:02:42 +00002185 if (EPI.ConsumedArguments)
2186 Size += NumArgs * sizeof(bool);
2187
John McCalldb40c7f2010-12-14 08:05:40 +00002188 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00002189 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2190 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl31ad7542011-03-13 17:09:40 +00002191 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002192 Types.push_back(FTP);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002193 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002194 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00002195}
Chris Lattneref51c202006-11-10 07:17:23 +00002196
John McCalle78aac42010-03-10 03:28:59 +00002197#ifndef NDEBUG
2198static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2199 if (!isa<CXXRecordDecl>(D)) return false;
2200 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2201 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2202 return true;
2203 if (RD->getDescribedClassTemplate() &&
2204 !isa<ClassTemplateSpecializationDecl>(RD))
2205 return true;
2206 return false;
2207}
2208#endif
2209
2210/// getInjectedClassNameType - Return the unique reference to the
2211/// injected class name type for the specified templated declaration.
2212QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00002213 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00002214 assert(NeedsInjectedClassNameType(Decl));
2215 if (Decl->TypeForDecl) {
2216 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00002217 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00002218 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2219 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2220 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2221 } else {
John McCall424cec92011-01-19 06:33:43 +00002222 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00002223 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00002224 Decl->TypeForDecl = newType;
2225 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00002226 }
2227 return QualType(Decl->TypeForDecl, 0);
2228}
2229
Douglas Gregor83a586e2008-04-13 21:07:44 +00002230/// getTypeDeclType - Return the unique reference to the type for the
2231/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00002232QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00002233 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00002234 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00002235
Richard Smithdda56e42011-04-15 14:24:37 +00002236 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00002237 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00002238
John McCall96f0b5f2010-03-10 06:48:02 +00002239 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2240 "Template type parameter types are always available.");
2241
John McCall81e38502010-02-16 03:57:14 +00002242 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002243 assert(!Record->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002244 "struct/union has previous declaration");
2245 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002246 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00002247 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00002248 assert(!Enum->getPreviousDecl() &&
John McCall96f0b5f2010-03-10 06:48:02 +00002249 "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002250 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00002251 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00002252 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00002253 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2254 Decl->TypeForDecl = newType;
2255 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00002256 } else
John McCall96f0b5f2010-03-10 06:48:02 +00002257 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002258
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00002259 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00002260}
2261
Chris Lattner32d920b2007-01-26 02:01:53 +00002262/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00002263/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002264QualType
Richard Smithdda56e42011-04-15 14:24:37 +00002265ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2266 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002267 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002268
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002269 if (Canonical.isNull())
2270 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00002271 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00002272 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00002273 Decl->TypeForDecl = newType;
2274 Types.push_back(newType);
2275 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00002276}
2277
Jay Foad39c79802011-01-12 09:06:06 +00002278QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002279 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2280
Douglas Gregorec9fd132012-01-14 16:38:05 +00002281 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002282 if (PrevDecl->TypeForDecl)
2283 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2284
John McCall424cec92011-01-19 06:33:43 +00002285 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2286 Decl->TypeForDecl = newType;
2287 Types.push_back(newType);
2288 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002289}
2290
Jay Foad39c79802011-01-12 09:06:06 +00002291QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002292 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2293
Douglas Gregorec9fd132012-01-14 16:38:05 +00002294 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002295 if (PrevDecl->TypeForDecl)
2296 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2297
John McCall424cec92011-01-19 06:33:43 +00002298 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2299 Decl->TypeForDecl = newType;
2300 Types.push_back(newType);
2301 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00002302}
2303
John McCall81904512011-01-06 01:58:22 +00002304QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2305 QualType modifiedType,
2306 QualType equivalentType) {
2307 llvm::FoldingSetNodeID id;
2308 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2309
2310 void *insertPos = 0;
2311 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2312 if (type) return QualType(type, 0);
2313
2314 QualType canon = getCanonicalType(equivalentType);
2315 type = new (*this, TypeAlignment)
2316 AttributedType(canon, attrKind, modifiedType, equivalentType);
2317
2318 Types.push_back(type);
2319 AttributedTypes.InsertNode(type, insertPos);
2320
2321 return QualType(type, 0);
2322}
2323
2324
John McCallcebee162009-10-18 09:09:24 +00002325/// \brief Retrieve a substitution-result type.
2326QualType
2327ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00002328 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00002329 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00002330 && "replacement types must always be canonical");
2331
2332 llvm::FoldingSetNodeID ID;
2333 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2334 void *InsertPos = 0;
2335 SubstTemplateTypeParmType *SubstParm
2336 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2337
2338 if (!SubstParm) {
2339 SubstParm = new (*this, TypeAlignment)
2340 SubstTemplateTypeParmType(Parm, Replacement);
2341 Types.push_back(SubstParm);
2342 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2343 }
2344
2345 return QualType(SubstParm, 0);
2346}
2347
Douglas Gregorada4b792011-01-14 02:55:32 +00002348/// \brief Retrieve a
2349QualType ASTContext::getSubstTemplateTypeParmPackType(
2350 const TemplateTypeParmType *Parm,
2351 const TemplateArgument &ArgPack) {
2352#ifndef NDEBUG
2353 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2354 PEnd = ArgPack.pack_end();
2355 P != PEnd; ++P) {
2356 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2357 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2358 }
2359#endif
2360
2361 llvm::FoldingSetNodeID ID;
2362 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2363 void *InsertPos = 0;
2364 if (SubstTemplateTypeParmPackType *SubstParm
2365 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2366 return QualType(SubstParm, 0);
2367
2368 QualType Canon;
2369 if (!Parm->isCanonicalUnqualified()) {
2370 Canon = getCanonicalType(QualType(Parm, 0));
2371 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2372 ArgPack);
2373 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2374 }
2375
2376 SubstTemplateTypeParmPackType *SubstParm
2377 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2378 ArgPack);
2379 Types.push_back(SubstParm);
2380 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2381 return QualType(SubstParm, 0);
2382}
2383
Douglas Gregoreff93e02009-02-05 23:33:38 +00002384/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00002385/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00002386/// name.
Mike Stump11289f42009-09-09 15:08:12 +00002387QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00002388 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00002389 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00002390 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00002391 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002392 void *InsertPos = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002393 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00002394 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2395
2396 if (TypeParm)
2397 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002398
Chandler Carruth08836322011-05-01 00:51:33 +00002399 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00002400 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00002401 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002402
2403 TemplateTypeParmType *TypeCheck
2404 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2405 assert(!TypeCheck && "Template type parameter canonical type broken");
2406 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00002407 } else
John McCall90d1c2d2009-09-24 23:30:46 +00002408 TypeParm = new (*this, TypeAlignment)
2409 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00002410
2411 Types.push_back(TypeParm);
2412 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2413
2414 return QualType(TypeParm, 0);
2415}
2416
John McCalle78aac42010-03-10 03:28:59 +00002417TypeSourceInfo *
2418ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2419 SourceLocation NameLoc,
2420 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002421 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002422 assert(!Name.getAsDependentTemplateName() &&
2423 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002424 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00002425
2426 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2427 TemplateSpecializationTypeLoc TL
2428 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002429 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00002430 TL.setTemplateNameLoc(NameLoc);
2431 TL.setLAngleLoc(Args.getLAngleLoc());
2432 TL.setRAngleLoc(Args.getRAngleLoc());
2433 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2434 TL.setArgLocInfo(i, Args[i].getLocInfo());
2435 return DI;
2436}
2437
Mike Stump11289f42009-09-09 15:08:12 +00002438QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00002439ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00002440 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002441 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002442 assert(!Template.getAsDependentTemplateName() &&
2443 "No dependent template names here!");
2444
John McCall6b51f282009-11-23 01:53:49 +00002445 unsigned NumArgs = Args.size();
2446
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002447 SmallVector<TemplateArgument, 4> ArgVec;
John McCall0ad16662009-10-29 08:12:44 +00002448 ArgVec.reserve(NumArgs);
2449 for (unsigned i = 0; i != NumArgs; ++i)
2450 ArgVec.push_back(Args[i].getArgument());
2451
John McCall2408e322010-04-27 00:57:59 +00002452 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002453 Underlying);
John McCall0ad16662009-10-29 08:12:44 +00002454}
2455
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002456#ifndef NDEBUG
2457static bool hasAnyPackExpansions(const TemplateArgument *Args,
2458 unsigned NumArgs) {
2459 for (unsigned I = 0; I != NumArgs; ++I)
2460 if (Args[I].isPackExpansion())
2461 return true;
2462
2463 return true;
2464}
2465#endif
2466
John McCall0ad16662009-10-29 08:12:44 +00002467QualType
2468ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregordc572a32009-03-30 22:58:21 +00002469 const TemplateArgument *Args,
2470 unsigned NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002471 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002472 assert(!Template.getAsDependentTemplateName() &&
2473 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00002474 // Look through qualified template names.
2475 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2476 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002477
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002478 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00002479 Template.getAsTemplateDecl() &&
2480 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00002481 QualType CanonType;
2482 if (!Underlying.isNull())
2483 CanonType = getCanonicalType(Underlying);
2484 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002485 // We can get here with an alias template when the specialization contains
2486 // a pack expansion that does not match up with a parameter pack.
2487 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2488 "Caller must compute aliased type");
2489 IsTypeAlias = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00002490 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2491 NumArgs);
2492 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00002493
Douglas Gregora8e02e72009-07-28 23:00:59 +00002494 // Allocate the (non-canonical) template specialization type, but don't
2495 // try to unique it: these types typically have location information that
2496 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00002497 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2498 sizeof(TemplateArgument) * NumArgs +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002499 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00002500 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00002501 TemplateSpecializationType *Spec
Douglas Gregor1f79ca82012-02-03 17:16:23 +00002502 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2503 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00002504
Douglas Gregor8bf42052009-02-09 18:46:07 +00002505 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00002506 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00002507}
2508
Mike Stump11289f42009-09-09 15:08:12 +00002509QualType
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002510ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2511 const TemplateArgument *Args,
Jay Foad39c79802011-01-12 09:06:06 +00002512 unsigned NumArgs) const {
Douglas Gregore16af532011-02-28 18:50:33 +00002513 assert(!Template.getAsDependentTemplateName() &&
2514 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00002515
Douglas Gregore29139c2011-03-03 17:04:51 +00002516 // Look through qualified template names.
2517 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2518 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00002519
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002520 // Build the canonical template specialization type.
2521 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002522 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002523 CanonArgs.reserve(NumArgs);
2524 for (unsigned I = 0; I != NumArgs; ++I)
2525 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2526
2527 // Determine whether this canonical template specialization type already
2528 // exists.
2529 llvm::FoldingSetNodeID ID;
2530 TemplateSpecializationType::Profile(ID, CanonTemplate,
2531 CanonArgs.data(), NumArgs, *this);
2532
2533 void *InsertPos = 0;
2534 TemplateSpecializationType *Spec
2535 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2536
2537 if (!Spec) {
2538 // Allocate a new canonical template specialization type.
2539 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2540 sizeof(TemplateArgument) * NumArgs),
2541 TypeAlignment);
2542 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2543 CanonArgs.data(), NumArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00002544 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00002545 Types.push_back(Spec);
2546 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2547 }
2548
2549 assert(Spec->isDependentType() &&
2550 "Non-dependent template-id type must have a canonical type");
2551 return QualType(Spec, 0);
2552}
2553
2554QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00002555ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2556 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00002557 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00002558 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002559 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00002560
2561 void *InsertPos = 0;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002562 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002563 if (T)
2564 return QualType(T, 0);
2565
Douglas Gregorc42075a2010-02-04 18:10:26 +00002566 QualType Canon = NamedType;
2567 if (!Canon.isCanonical()) {
2568 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002569 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2570 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00002571 (void)CheckT;
2572 }
2573
Abramo Bagnara6150c882010-05-11 21:36:43 +00002574 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00002575 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00002576 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00002577 return QualType(T, 0);
2578}
2579
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002580QualType
Jay Foad39c79802011-01-12 09:06:06 +00002581ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00002582 llvm::FoldingSetNodeID ID;
2583 ParenType::Profile(ID, InnerType);
2584
2585 void *InsertPos = 0;
2586 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2587 if (T)
2588 return QualType(T, 0);
2589
2590 QualType Canon = InnerType;
2591 if (!Canon.isCanonical()) {
2592 Canon = getCanonicalType(InnerType);
2593 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2594 assert(!CheckT && "Paren canonical type broken");
2595 (void)CheckT;
2596 }
2597
2598 T = new (*this) ParenType(InnerType, Canon);
2599 Types.push_back(T);
2600 ParenTypes.InsertNode(T, InsertPos);
2601 return QualType(T, 0);
2602}
2603
Douglas Gregor02085352010-03-31 20:19:30 +00002604QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2605 NestedNameSpecifier *NNS,
2606 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002607 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00002608 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2609
2610 if (Canon.isNull()) {
2611 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor02085352010-03-31 20:19:30 +00002612 ElaboratedTypeKeyword CanonKeyword = Keyword;
2613 if (Keyword == ETK_None)
2614 CanonKeyword = ETK_Typename;
2615
2616 if (CanonNNS != NNS || CanonKeyword != Keyword)
2617 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002618 }
2619
2620 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00002621 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00002622
2623 void *InsertPos = 0;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002624 DependentNameType *T
2625 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00002626 if (T)
2627 return QualType(T, 0);
2628
Douglas Gregor02085352010-03-31 20:19:30 +00002629 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00002630 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002631 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002632 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00002633}
2634
Mike Stump11289f42009-09-09 15:08:12 +00002635QualType
John McCallc392f372010-06-11 00:33:02 +00002636ASTContext::getDependentTemplateSpecializationType(
2637 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00002638 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00002639 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00002640 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00002641 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002642 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00002643 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2644 ArgCopy.push_back(Args[I].getArgument());
2645 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2646 ArgCopy.size(),
2647 ArgCopy.data());
2648}
2649
2650QualType
2651ASTContext::getDependentTemplateSpecializationType(
2652 ElaboratedTypeKeyword Keyword,
2653 NestedNameSpecifier *NNS,
2654 const IdentifierInfo *Name,
2655 unsigned NumArgs,
Jay Foad39c79802011-01-12 09:06:06 +00002656 const TemplateArgument *Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00002657 assert((!NNS || NNS->isDependent()) &&
2658 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00002659
Douglas Gregorc42075a2010-02-04 18:10:26 +00002660 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00002661 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2662 Name, NumArgs, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002663
2664 void *InsertPos = 0;
John McCallc392f372010-06-11 00:33:02 +00002665 DependentTemplateSpecializationType *T
2666 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002667 if (T)
2668 return QualType(T, 0);
2669
John McCallc392f372010-06-11 00:33:02 +00002670 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00002671
John McCallc392f372010-06-11 00:33:02 +00002672 ElaboratedTypeKeyword CanonKeyword = Keyword;
2673 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2674
2675 bool AnyNonCanonArgs = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002676 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00002677 for (unsigned I = 0; I != NumArgs; ++I) {
2678 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2679 if (!CanonArgs[I].structurallyEquals(Args[I]))
2680 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00002681 }
2682
John McCallc392f372010-06-11 00:33:02 +00002683 QualType Canon;
2684 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2685 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2686 Name, NumArgs,
2687 CanonArgs.data());
2688
2689 // Find the insert position again.
2690 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2691 }
2692
2693 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2694 sizeof(TemplateArgument) * NumArgs),
2695 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00002696 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCallc392f372010-06-11 00:33:02 +00002697 Name, NumArgs, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00002698 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00002699 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00002700 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00002701}
2702
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002703QualType ASTContext::getPackExpansionType(QualType Pattern,
2704 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00002705 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002706 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002707
2708 assert(Pattern->containsUnexpandedParameterPack() &&
2709 "Pack expansions must expand one or more parameter packs");
2710 void *InsertPos = 0;
2711 PackExpansionType *T
2712 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2713 if (T)
2714 return QualType(T, 0);
2715
2716 QualType Canon;
2717 if (!Pattern.isCanonical()) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002718 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002719
2720 // Find the insert position again.
2721 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2722 }
2723
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00002724 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00002725 Types.push_back(T);
2726 PackExpansionTypes.InsertNode(T, InsertPos);
2727 return QualType(T, 0);
2728}
2729
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002730/// CmpProtocolNames - Comparison predicate for sorting protocols
2731/// alphabetically.
2732static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2733 const ObjCProtocolDecl *RHS) {
Douglas Gregor77324f32008-11-17 14:58:09 +00002734 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002735}
2736
John McCall8b07ec22010-05-15 11:32:37 +00002737static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCallfc93cf92009-10-22 22:37:11 +00002738 unsigned NumProtocols) {
2739 if (NumProtocols == 0) return true;
2740
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002741 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2742 return false;
2743
John McCallfc93cf92009-10-22 22:37:11 +00002744 for (unsigned i = 1; i != NumProtocols; ++i)
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002745 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2746 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00002747 return false;
2748 return true;
2749}
2750
2751static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002752 unsigned &NumProtocols) {
2753 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump11289f42009-09-09 15:08:12 +00002754
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002755 // Sort protocols, keyed by name.
2756 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2757
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00002758 // Canonicalize.
2759 for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2760 Protocols[I] = Protocols[I]->getCanonicalDecl();
2761
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002762 // Remove duplicates.
2763 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2764 NumProtocols = ProtocolsEnd-Protocols;
2765}
2766
John McCall8b07ec22010-05-15 11:32:37 +00002767QualType ASTContext::getObjCObjectType(QualType BaseType,
2768 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00002769 unsigned NumProtocols) const {
John McCall8b07ec22010-05-15 11:32:37 +00002770 // If the base type is an interface and there aren't any protocols
2771 // to add, then the interface type will do just fine.
2772 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2773 return BaseType;
2774
2775 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00002776 llvm::FoldingSetNodeID ID;
John McCall8b07ec22010-05-15 11:32:37 +00002777 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Narofffb4330f2009-06-17 22:40:22 +00002778 void *InsertPos = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002779 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2780 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002781
John McCall8b07ec22010-05-15 11:32:37 +00002782 // Build the canonical type, which has the canonical base type and
2783 // a sorted-and-uniqued list of protocols.
John McCallfc93cf92009-10-22 22:37:11 +00002784 QualType Canonical;
John McCall8b07ec22010-05-15 11:32:37 +00002785 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2786 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2787 if (!ProtocolsSorted) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002788 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00002789 Protocols + NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002790 unsigned UniqueCount = NumProtocols;
2791
John McCallfc93cf92009-10-22 22:37:11 +00002792 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCall8b07ec22010-05-15 11:32:37 +00002793 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2794 &Sorted[0], UniqueCount);
John McCallfc93cf92009-10-22 22:37:11 +00002795 } else {
John McCall8b07ec22010-05-15 11:32:37 +00002796 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2797 Protocols, NumProtocols);
John McCallfc93cf92009-10-22 22:37:11 +00002798 }
2799
2800 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00002801 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2802 }
2803
2804 unsigned Size = sizeof(ObjCObjectTypeImpl);
2805 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2806 void *Mem = Allocate(Size, TypeAlignment);
2807 ObjCObjectTypeImpl *T =
2808 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2809
2810 Types.push_back(T);
2811 ObjCObjectTypes.InsertNode(T, InsertPos);
2812 return QualType(T, 0);
2813}
2814
2815/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2816/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00002817QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00002818 llvm::FoldingSetNodeID ID;
2819 ObjCObjectPointerType::Profile(ID, ObjectT);
2820
2821 void *InsertPos = 0;
2822 if (ObjCObjectPointerType *QT =
2823 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2824 return QualType(QT, 0);
2825
2826 // Find the canonical object type.
2827 QualType Canonical;
2828 if (!ObjectT.isCanonical()) {
2829 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2830
2831 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00002832 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2833 }
2834
Douglas Gregorf85bee62010-02-08 22:59:26 +00002835 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00002836 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2837 ObjCObjectPointerType *QType =
2838 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00002839
Steve Narofffb4330f2009-06-17 22:40:22 +00002840 Types.push_back(QType);
2841 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00002842 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00002843}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00002844
Douglas Gregor1c283312010-08-11 12:19:30 +00002845/// getObjCInterfaceType - Return the unique reference to the type for the
2846/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002847QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2848 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00002849 if (Decl->TypeForDecl)
2850 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002851
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002852 if (PrevDecl) {
2853 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2854 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2855 return QualType(PrevDecl->TypeForDecl, 0);
2856 }
2857
Douglas Gregor7671e532011-12-16 16:34:57 +00002858 // Prefer the definition, if there is one.
2859 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2860 Decl = Def;
2861
Douglas Gregor1c283312010-08-11 12:19:30 +00002862 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2863 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2864 Decl->TypeForDecl = T;
2865 Types.push_back(T);
2866 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00002867}
2868
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002869/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2870/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00002871/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00002872/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002873/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002874QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002875 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002876 if (tofExpr->isTypeDependent()) {
2877 llvm::FoldingSetNodeID ID;
2878 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00002879
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002880 void *InsertPos = 0;
2881 DependentTypeOfExprType *Canon
2882 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2883 if (Canon) {
2884 // We already have a "canonical" version of an identical, dependent
2885 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002886 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002887 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002888 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002889 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002890 Canon
2891 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00002892 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2893 toe = Canon;
2894 }
2895 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00002896 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00002897 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00002898 }
Steve Naroffa773cd52007-08-01 18:02:17 +00002899 Types.push_back(toe);
2900 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002901}
2902
Steve Naroffa773cd52007-08-01 18:02:17 +00002903/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2904/// TypeOfType AST's. The only motivation to unique these nodes would be
2905/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002906/// an issue. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00002907/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00002908QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002909 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00002910 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00002911 Types.push_back(tot);
2912 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00002913}
2914
Anders Carlssonad6bd352009-06-24 21:24:56 +00002915
Anders Carlsson81df7b82009-06-24 19:06:50 +00002916/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2917/// DecltypeType AST's. The only motivation to unique these nodes would be
2918/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump11289f42009-09-09 15:08:12 +00002919/// an issue. This doesn't effect the type checker, since it operates
David Blaikie876657b2011-11-06 22:28:03 +00002920/// on canonical types (which are always unique).
Douglas Gregor81495f32012-02-12 18:42:33 +00002921QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00002922 DecltypeType *dt;
Douglas Gregor678d76c2011-07-01 01:22:09 +00002923
2924 // C++0x [temp.type]p2:
2925 // If an expression e involves a template parameter, decltype(e) denotes a
2926 // unique dependent type. Two such decltype-specifiers refer to the same
2927 // type only if their expressions are equivalent (14.5.6.1).
2928 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002929 llvm::FoldingSetNodeID ID;
2930 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00002931
Douglas Gregora21f6c32009-07-30 23:36:40 +00002932 void *InsertPos = 0;
2933 DependentDecltypeType *Canon
2934 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2935 if (Canon) {
2936 // We already have a "canonical" version of an equivalent, dependent
2937 // decltype type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00002938 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregora21f6c32009-07-30 23:36:40 +00002939 QualType((DecltypeType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002940 } else {
Douglas Gregora21f6c32009-07-30 23:36:40 +00002941 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00002942 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00002943 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2944 dt = Canon;
2945 }
2946 } else {
Douglas Gregor81495f32012-02-12 18:42:33 +00002947 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
2948 getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00002949 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00002950 Types.push_back(dt);
2951 return QualType(dt, 0);
2952}
2953
Alexis Hunte852b102011-05-24 22:41:36 +00002954/// getUnaryTransformationType - We don't unique these, since the memory
2955/// savings are minimal and these are rare.
2956QualType ASTContext::getUnaryTransformType(QualType BaseType,
2957 QualType UnderlyingType,
2958 UnaryTransformType::UTTKind Kind)
2959 const {
2960 UnaryTransformType *Ty =
Douglas Gregor6c6e6762011-05-25 17:51:54 +00002961 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2962 Kind,
2963 UnderlyingType->isDependentType() ?
Peter Collingbourne15d48ec2012-03-05 16:02:06 +00002964 QualType() : getCanonicalType(UnderlyingType));
Alexis Hunte852b102011-05-24 22:41:36 +00002965 Types.push_back(Ty);
2966 return QualType(Ty, 0);
2967}
2968
Richard Smithb2bc2e62011-02-21 20:05:19 +00002969/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00002970QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smithb2bc2e62011-02-21 20:05:19 +00002971 void *InsertPos = 0;
2972 if (!DeducedType.isNull()) {
2973 // Look in the folding set for an existing type.
2974 llvm::FoldingSetNodeID ID;
2975 AutoType::Profile(ID, DeducedType);
2976 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2977 return QualType(AT, 0);
2978 }
2979
2980 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2981 Types.push_back(AT);
2982 if (InsertPos)
2983 AutoTypes.InsertNode(AT, InsertPos);
2984 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00002985}
2986
Eli Friedman0dfb8892011-10-06 23:00:33 +00002987/// getAtomicType - Return the uniqued reference to the atomic type for
2988/// the given value type.
2989QualType ASTContext::getAtomicType(QualType T) const {
2990 // Unique pointers, to guarantee there is only one pointer of a particular
2991 // structure.
2992 llvm::FoldingSetNodeID ID;
2993 AtomicType::Profile(ID, T);
2994
2995 void *InsertPos = 0;
2996 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
2997 return QualType(AT, 0);
2998
2999 // If the atomic value type isn't canonical, this won't be a canonical type
3000 // either, so fill in the canonical type field.
3001 QualType Canonical;
3002 if (!T.isCanonical()) {
3003 Canonical = getAtomicType(getCanonicalType(T));
3004
3005 // Get the new insert position for the node we care about.
3006 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3007 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3008 }
3009 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3010 Types.push_back(New);
3011 AtomicTypes.InsertNode(New, InsertPos);
3012 return QualType(New, 0);
3013}
3014
Richard Smith02e85f32011-04-14 22:09:26 +00003015/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3016QualType ASTContext::getAutoDeductType() const {
3017 if (AutoDeductTy.isNull())
3018 AutoDeductTy = getAutoType(QualType());
3019 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3020 return AutoDeductTy;
3021}
3022
3023/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3024QualType ASTContext::getAutoRRefDeductType() const {
3025 if (AutoRRefDeductTy.isNull())
3026 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3027 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3028 return AutoRRefDeductTy;
3029}
3030
Chris Lattnerfb072462007-01-23 05:45:31 +00003031/// getTagDeclType - Return the unique reference to the type for the
3032/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00003033QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00003034 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00003035 // FIXME: What is the design on getTagDeclType when it requires casting
3036 // away const? mutable?
3037 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00003038}
3039
Mike Stump11289f42009-09-09 15:08:12 +00003040/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3041/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3042/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00003043CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003044 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00003045}
Chris Lattnerfb072462007-01-23 05:45:31 +00003046
Hans Wennborg27541db2011-10-27 08:29:09 +00003047/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3048CanQualType ASTContext::getIntMaxType() const {
3049 return getFromTargetType(Target->getIntMaxType());
3050}
3051
3052/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3053CanQualType ASTContext::getUIntMaxType() const {
3054 return getFromTargetType(Target->getUIntMaxType());
3055}
3056
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00003057/// getSignedWCharType - Return the type of "signed wchar_t".
3058/// Used when in C++, as a GCC extension.
3059QualType ASTContext::getSignedWCharType() const {
3060 // FIXME: derive from "Target" ?
3061 return WCharTy;
3062}
3063
3064/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3065/// Used when in C++, as a GCC extension.
3066QualType ASTContext::getUnsignedWCharType() const {
3067 // FIXME: derive from "Target" ?
3068 return UnsignedIntTy;
3069}
3070
Hans Wennborg27541db2011-10-27 08:29:09 +00003071/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003072/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3073QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00003074 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00003075}
3076
Chris Lattnera21ad802008-04-02 05:18:44 +00003077//===----------------------------------------------------------------------===//
3078// Type Operators
3079//===----------------------------------------------------------------------===//
3080
Jay Foad39c79802011-01-12 09:06:06 +00003081CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00003082 // Push qualifiers into arrays, and then discard any remaining
3083 // qualifiers.
3084 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003085 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00003086 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00003087 QualType Result;
3088 if (isa<ArrayType>(Ty)) {
3089 Result = getArrayDecayedType(QualType(Ty,0));
3090 } else if (isa<FunctionType>(Ty)) {
3091 Result = getPointerType(QualType(Ty, 0));
3092 } else {
3093 Result = QualType(Ty, 0);
3094 }
3095
3096 return CanQualType::CreateUnsafe(Result);
3097}
3098
John McCall6c9dd522011-01-18 07:41:22 +00003099QualType ASTContext::getUnqualifiedArrayType(QualType type,
3100 Qualifiers &quals) {
3101 SplitQualType splitType = type.getSplitUnqualifiedType();
3102
3103 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3104 // the unqualified desugared type and then drops it on the floor.
3105 // We then have to strip that sugar back off with
3106 // getUnqualifiedDesugaredType(), which is silly.
3107 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00003108 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00003109
3110 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003111 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00003112 quals = splitType.Quals;
3113 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003114 }
3115
John McCall6c9dd522011-01-18 07:41:22 +00003116 // Otherwise, recurse on the array's element type.
3117 QualType elementType = AT->getElementType();
3118 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3119
3120 // If that didn't change the element type, AT has no qualifiers, so we
3121 // can just use the results in splitType.
3122 if (elementType == unqualElementType) {
3123 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00003124 quals = splitType.Quals;
3125 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00003126 }
3127
3128 // Otherwise, add in the qualifiers from the outermost type, then
3129 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00003130 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003131
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003132 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003133 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003134 CAT->getSizeModifier(), 0);
3135 }
3136
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003137 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003138 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003139 }
3140
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003141 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00003142 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00003143 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00003144 VAT->getSizeModifier(),
3145 VAT->getIndexTypeCVRQualifiers(),
3146 VAT->getBracketsRange());
3147 }
3148
3149 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00003150 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00003151 DSAT->getSizeModifier(), 0,
3152 SourceRange());
3153}
3154
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003155/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3156/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3157/// they point to and return true. If T1 and T2 aren't pointer types
3158/// or pointer-to-member types, or if they are not similar at this
3159/// level, returns false and leaves T1 and T2 unchanged. Top-level
3160/// qualifiers on T1 and T2 are ignored. This function will typically
3161/// be called in a loop that successively "unwraps" pointer and
3162/// pointer-to-member types to compare them at each level.
3163bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3164 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3165 *T2PtrType = T2->getAs<PointerType>();
3166 if (T1PtrType && T2PtrType) {
3167 T1 = T1PtrType->getPointeeType();
3168 T2 = T2PtrType->getPointeeType();
3169 return true;
3170 }
3171
3172 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3173 *T2MPType = T2->getAs<MemberPointerType>();
3174 if (T1MPType && T2MPType &&
3175 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3176 QualType(T2MPType->getClass(), 0))) {
3177 T1 = T1MPType->getPointeeType();
3178 T2 = T2MPType->getPointeeType();
3179 return true;
3180 }
3181
3182 if (getLangOptions().ObjC1) {
3183 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3184 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3185 if (T1OPType && T2OPType) {
3186 T1 = T1OPType->getPointeeType();
3187 T2 = T2OPType->getPointeeType();
3188 return true;
3189 }
3190 }
3191
3192 // FIXME: Block pointers, too?
3193
3194 return false;
3195}
3196
Jay Foad39c79802011-01-12 09:06:06 +00003197DeclarationNameInfo
3198ASTContext::getNameForTemplate(TemplateName Name,
3199 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003200 switch (Name.getKind()) {
3201 case TemplateName::QualifiedTemplate:
3202 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003203 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00003204 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3205 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003206
John McCalld9dfe3a2011-06-30 08:33:18 +00003207 case TemplateName::OverloadedTemplate: {
3208 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3209 // DNInfo work in progress: CHECKME: what about DNLoc?
3210 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3211 }
3212
3213 case TemplateName::DependentTemplate: {
3214 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003215 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00003216 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003217 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3218 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00003219 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003220 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3221 // DNInfo work in progress: FIXME: source locations?
3222 DeclarationNameLoc DNLoc;
3223 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3224 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3225 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00003226 }
3227 }
3228
John McCalld9dfe3a2011-06-30 08:33:18 +00003229 case TemplateName::SubstTemplateTemplateParm: {
3230 SubstTemplateTemplateParmStorage *subst
3231 = Name.getAsSubstTemplateTemplateParm();
3232 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3233 NameLoc);
3234 }
3235
3236 case TemplateName::SubstTemplateTemplateParmPack: {
3237 SubstTemplateTemplateParmPackStorage *subst
3238 = Name.getAsSubstTemplateTemplateParmPack();
3239 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3240 NameLoc);
3241 }
3242 }
3243
3244 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00003245}
3246
Jay Foad39c79802011-01-12 09:06:06 +00003247TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00003248 switch (Name.getKind()) {
3249 case TemplateName::QualifiedTemplate:
3250 case TemplateName::Template: {
3251 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003252 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00003253 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003254 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3255
3256 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00003257 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00003258 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00003259
John McCalld9dfe3a2011-06-30 08:33:18 +00003260 case TemplateName::OverloadedTemplate:
3261 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00003262
John McCalld9dfe3a2011-06-30 08:33:18 +00003263 case TemplateName::DependentTemplate: {
3264 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3265 assert(DTN && "Non-dependent template names must refer to template decls.");
3266 return DTN->CanonicalTemplateName;
3267 }
3268
3269 case TemplateName::SubstTemplateTemplateParm: {
3270 SubstTemplateTemplateParmStorage *subst
3271 = Name.getAsSubstTemplateTemplateParm();
3272 return getCanonicalTemplateName(subst->getReplacement());
3273 }
3274
3275 case TemplateName::SubstTemplateTemplateParmPack: {
3276 SubstTemplateTemplateParmPackStorage *subst
3277 = Name.getAsSubstTemplateTemplateParmPack();
3278 TemplateTemplateParmDecl *canonParameter
3279 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3280 TemplateArgument canonArgPack
3281 = getCanonicalTemplateArgument(subst->getArgumentPack());
3282 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3283 }
3284 }
3285
3286 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00003287}
3288
Douglas Gregoradee3e32009-11-11 23:06:43 +00003289bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3290 X = getCanonicalTemplateName(X);
3291 Y = getCanonicalTemplateName(Y);
3292 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3293}
3294
Mike Stump11289f42009-09-09 15:08:12 +00003295TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00003296ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00003297 switch (Arg.getKind()) {
3298 case TemplateArgument::Null:
3299 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003300
Douglas Gregora8e02e72009-07-28 23:00:59 +00003301 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00003302 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00003303
Douglas Gregora8e02e72009-07-28 23:00:59 +00003304 case TemplateArgument::Declaration:
John McCall0ad16662009-10-29 08:12:44 +00003305 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003306
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003307 case TemplateArgument::Template:
3308 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003309
3310 case TemplateArgument::TemplateExpansion:
3311 return TemplateArgument(getCanonicalTemplateName(
3312 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00003313 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00003314
Douglas Gregora8e02e72009-07-28 23:00:59 +00003315 case TemplateArgument::Integral:
John McCall0ad16662009-10-29 08:12:44 +00003316 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003317 getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00003318
Douglas Gregora8e02e72009-07-28 23:00:59 +00003319 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00003320 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00003321
Douglas Gregora8e02e72009-07-28 23:00:59 +00003322 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00003323 if (Arg.pack_size() == 0)
3324 return Arg;
3325
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003326 TemplateArgument *CanonArgs
3327 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00003328 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003329 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00003330 AEnd = Arg.pack_end();
3331 A != AEnd; (void)++A, ++Idx)
3332 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00003333
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003334 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregora8e02e72009-07-28 23:00:59 +00003335 }
3336 }
3337
3338 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00003339 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00003340}
3341
Douglas Gregor333489b2009-03-27 23:10:48 +00003342NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00003343ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00003344 if (!NNS)
Douglas Gregor333489b2009-03-27 23:10:48 +00003345 return 0;
3346
3347 switch (NNS->getKind()) {
3348 case NestedNameSpecifier::Identifier:
3349 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00003350 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00003351 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3352 NNS->getAsIdentifier());
3353
3354 case NestedNameSpecifier::Namespace:
3355 // A namespace is canonical; build a nested-name-specifier with
3356 // this namespace and no prefix.
Douglas Gregor7b26ff92011-02-24 02:36:08 +00003357 return NestedNameSpecifier::Create(*this, 0,
3358 NNS->getAsNamespace()->getOriginalNamespace());
3359
3360 case NestedNameSpecifier::NamespaceAlias:
3361 // A namespace is canonical; build a nested-name-specifier with
3362 // this namespace and no prefix.
3363 return NestedNameSpecifier::Create(*this, 0,
3364 NNS->getAsNamespaceAlias()->getNamespace()
3365 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00003366
3367 case NestedNameSpecifier::TypeSpec:
3368 case NestedNameSpecifier::TypeSpecWithTemplate: {
3369 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003370
3371 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3372 // break it apart into its prefix and identifier, then reconsititute those
3373 // as the canonical nested-name-specifier. This is required to canonicalize
3374 // a dependent nested-name-specifier involving typedefs of dependent-name
3375 // types, e.g.,
3376 // typedef typename T::type T1;
3377 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00003378 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3379 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00003380 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00003381
Eli Friedman5358a0a2012-03-03 04:09:56 +00003382 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3383 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3384 // first place?
John McCall33ddac02011-01-19 10:06:00 +00003385 return NestedNameSpecifier::Create(*this, 0, false,
3386 const_cast<Type*>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00003387 }
3388
3389 case NestedNameSpecifier::Global:
3390 // The global specifier is canonical and unique.
3391 return NNS;
3392 }
3393
David Blaikie8a40f702012-01-17 06:56:22 +00003394 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00003395}
3396
Chris Lattner7adf0762008-08-04 07:31:14 +00003397
Jay Foad39c79802011-01-12 09:06:06 +00003398const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003399 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003400 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003401 // Handle the common positive case fast.
3402 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3403 return AT;
3404 }
Mike Stump11289f42009-09-09 15:08:12 +00003405
John McCall8ccfcb52009-09-24 19:53:00 +00003406 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00003407 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattner7adf0762008-08-04 07:31:14 +00003408 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003409
John McCall8ccfcb52009-09-24 19:53:00 +00003410 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00003411 // implements C99 6.7.3p8: "If the specification of an array type includes
3412 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00003413
Chris Lattner7adf0762008-08-04 07:31:14 +00003414 // If we get here, we either have type qualifiers on the type, or we have
3415 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00003416 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00003417
John McCall33ddac02011-01-19 10:06:00 +00003418 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003419 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00003420
Chris Lattner7adf0762008-08-04 07:31:14 +00003421 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00003422 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
John McCall33ddac02011-01-19 10:06:00 +00003423 if (ATy == 0 || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00003424 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00003425
Chris Lattner7adf0762008-08-04 07:31:14 +00003426 // Otherwise, we have an array and we have qualifiers on it. Push the
3427 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00003428 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00003429
Chris Lattner7adf0762008-08-04 07:31:14 +00003430 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3431 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3432 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003433 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00003434 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3435 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3436 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003437 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00003438
Mike Stump11289f42009-09-09 15:08:12 +00003439 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00003440 = dyn_cast<DependentSizedArrayType>(ATy))
3441 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00003442 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003443 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00003444 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003445 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003446 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00003447
Chris Lattner7adf0762008-08-04 07:31:14 +00003448 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00003449 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00003450 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00003451 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00003452 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00003453 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00003454}
3455
Douglas Gregor84280642011-07-12 04:42:08 +00003456QualType ASTContext::getAdjustedParameterType(QualType T) {
3457 // C99 6.7.5.3p7:
3458 // A declaration of a parameter as "array of type" shall be
3459 // adjusted to "qualified pointer to type", where the type
3460 // qualifiers (if any) are those specified within the [ and ] of
3461 // the array type derivation.
3462 if (T->isArrayType())
3463 return getArrayDecayedType(T);
3464
3465 // C99 6.7.5.3p8:
3466 // A declaration of a parameter as "function returning type"
3467 // shall be adjusted to "pointer to function returning type", as
3468 // in 6.3.2.1.
3469 if (T->isFunctionType())
3470 return getPointerType(T);
3471
3472 return T;
3473}
3474
3475QualType ASTContext::getSignatureParameterType(QualType T) {
3476 T = getVariableArrayDecayedType(T);
3477 T = getAdjustedParameterType(T);
3478 return T.getUnqualifiedType();
3479}
3480
Chris Lattnera21ad802008-04-02 05:18:44 +00003481/// getArrayDecayedType - Return the properly qualified result of decaying the
3482/// specified array type to a pointer. This operation is non-trivial when
3483/// handling typedefs etc. The canonical type of "T" must be an array type,
3484/// this returns a pointer to a properly qualified element of the array.
3485///
3486/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00003487QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00003488 // Get the element type with 'getAsArrayType' so that we don't lose any
3489 // typedefs in the element type of the array. This also handles propagation
3490 // of type qualifiers from the array type into the element type if present
3491 // (C99 6.7.3p8).
3492 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3493 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00003494
Chris Lattner7adf0762008-08-04 07:31:14 +00003495 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00003496
3497 // int x[restrict 4] -> int *restrict
John McCall8ccfcb52009-09-24 19:53:00 +00003498 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnera21ad802008-04-02 05:18:44 +00003499}
3500
John McCall33ddac02011-01-19 10:06:00 +00003501QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3502 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00003503}
3504
John McCall33ddac02011-01-19 10:06:00 +00003505QualType ASTContext::getBaseElementType(QualType type) const {
3506 Qualifiers qs;
3507 while (true) {
3508 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003509 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00003510 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00003511
John McCall33ddac02011-01-19 10:06:00 +00003512 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00003513 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003514 }
Mike Stump11289f42009-09-09 15:08:12 +00003515
John McCall33ddac02011-01-19 10:06:00 +00003516 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00003517}
3518
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003519/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00003520uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00003521ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3522 uint64_t ElementCount = 1;
3523 do {
3524 ElementCount *= CA->getSize().getZExtValue();
3525 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3526 } while (CA);
3527 return ElementCount;
3528}
3529
Steve Naroff0af91202007-04-27 21:51:21 +00003530/// getFloatingRank - Return a relative rank for floating point types.
3531/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00003532static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00003533 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00003534 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00003535
John McCall9dd450b2009-09-21 23:43:11 +00003536 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3537 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003538 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003539 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00003540 case BuiltinType::Float: return FloatRank;
3541 case BuiltinType::Double: return DoubleRank;
3542 case BuiltinType::LongDouble: return LongDoubleRank;
Steve Naroffe4718892007-04-27 18:30:00 +00003543 }
3544}
3545
Mike Stump11289f42009-09-09 15:08:12 +00003546/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3547/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00003548/// 'typeDomain' is a real floating point or complex type.
3549/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003550QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3551 QualType Domain) const {
3552 FloatingRank EltRank = getFloatingRank(Size);
3553 if (Domain->isComplexType()) {
3554 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003555 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00003556 case FloatRank: return FloatComplexTy;
3557 case DoubleRank: return DoubleComplexTy;
3558 case LongDoubleRank: return LongDoubleComplexTy;
3559 }
Steve Naroff0af91202007-04-27 21:51:21 +00003560 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003561
3562 assert(Domain->isRealFloatingType() && "Unknown domain!");
3563 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00003564 case HalfRank: llvm_unreachable("Half ranks are not valid here");
Chris Lattnerb9dfb032008-04-06 23:58:54 +00003565 case FloatRank: return FloatTy;
3566 case DoubleRank: return DoubleTy;
3567 case LongDoubleRank: return LongDoubleTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00003568 }
David Blaikief47fa302012-01-17 02:30:50 +00003569 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00003570}
3571
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003572/// getFloatingTypeOrder - Compare the rank of the two specified floating
3573/// point types, ignoring the domain of the type (i.e. 'double' ==
3574/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003575/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003576int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00003577 FloatingRank LHSR = getFloatingRank(LHS);
3578 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00003579
Chris Lattnerb90739d2008-04-06 23:38:49 +00003580 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003581 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00003582 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00003583 return 1;
3584 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00003585}
3586
Chris Lattner76a00cf2008-04-06 22:59:24 +00003587/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3588/// routine will assert if passed a built-in type that isn't an integer or enum,
3589/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00003590unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00003591 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00003592
Chris Lattner76a00cf2008-04-06 22:59:24 +00003593 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003594 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003595 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003596 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003597 case BuiltinType::Char_S:
3598 case BuiltinType::Char_U:
3599 case BuiltinType::SChar:
3600 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003601 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003602 case BuiltinType::Short:
3603 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003604 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003605 case BuiltinType::Int:
3606 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003607 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003608 case BuiltinType::Long:
3609 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003610 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003611 case BuiltinType::LongLong:
3612 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00003613 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00003614 case BuiltinType::Int128:
3615 case BuiltinType::UInt128:
3616 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00003617 }
3618}
3619
Eli Friedman629ffb92009-08-20 04:21:42 +00003620/// \brief Whether this is a promotable bitfield reference according
3621/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3622///
3623/// \returns the type this bit-field will promote to, or NULL if no
3624/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00003625QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00003626 if (E->isTypeDependent() || E->isValueDependent())
3627 return QualType();
3628
Eli Friedman629ffb92009-08-20 04:21:42 +00003629 FieldDecl *Field = E->getBitField();
3630 if (!Field)
3631 return QualType();
3632
3633 QualType FT = Field->getType();
3634
Richard Smithcaf33902011-10-10 18:28:20 +00003635 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00003636 uint64_t IntSize = getTypeSize(IntTy);
3637 // GCC extension compatibility: if the bit-field size is less than or equal
3638 // to the size of int, it gets promoted no matter what its type is.
3639 // For instance, unsigned long bf : 4 gets promoted to signed int.
3640 if (BitWidth < IntSize)
3641 return IntTy;
3642
3643 if (BitWidth == IntSize)
3644 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3645
3646 // Types bigger than int are not subject to promotions, and therefore act
3647 // like the base type.
3648 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3649 // is ridiculous.
3650 return QualType();
3651}
3652
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003653/// getPromotedIntegerType - Returns the type that Promotable will
3654/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3655/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00003656QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003657 assert(!Promotable.isNull());
3658 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00003659 if (const EnumType *ET = Promotable->getAs<EnumType>())
3660 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00003661
3662 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3663 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3664 // (3.9.1) can be converted to a prvalue of the first of the following
3665 // types that can represent all the values of its underlying type:
3666 // int, unsigned int, long int, unsigned long int, long long int, or
3667 // unsigned long long int [...]
3668 // FIXME: Is there some better way to compute this?
3669 if (BT->getKind() == BuiltinType::WChar_S ||
3670 BT->getKind() == BuiltinType::WChar_U ||
3671 BT->getKind() == BuiltinType::Char16 ||
3672 BT->getKind() == BuiltinType::Char32) {
3673 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3674 uint64_t FromSize = getTypeSize(BT);
3675 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3676 LongLongTy, UnsignedLongLongTy };
3677 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3678 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3679 if (FromSize < ToSize ||
3680 (FromSize == ToSize &&
3681 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3682 return PromoteTypes[Idx];
3683 }
3684 llvm_unreachable("char type should fit into long long");
3685 }
3686 }
3687
3688 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003689 if (Promotable->isSignedIntegerType())
3690 return IntTy;
3691 uint64_t PromotableSize = getTypeSize(Promotable);
3692 uint64_t IntSize = getTypeSize(IntTy);
3693 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3694 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3695}
3696
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003697/// \brief Recurses in pointer/array types until it finds an objc retainable
3698/// type and returns its ownership.
3699Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3700 while (!T.isNull()) {
3701 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3702 return T.getObjCLifetime();
3703 if (T->isArrayType())
3704 T = getBaseElementType(T);
3705 else if (const PointerType *PT = T->getAs<PointerType>())
3706 T = PT->getPointeeType();
3707 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00003708 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00003709 else
3710 break;
3711 }
3712
3713 return Qualifiers::OCL_None;
3714}
3715
Mike Stump11289f42009-09-09 15:08:12 +00003716/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003717/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00003718/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00003719int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00003720 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3721 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003722 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003723
Chris Lattner76a00cf2008-04-06 22:59:24 +00003724 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3725 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00003726
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003727 unsigned LHSRank = getIntegerRank(LHSC);
3728 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00003729
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003730 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3731 if (LHSRank == RHSRank) return 0;
3732 return LHSRank > RHSRank ? 1 : -1;
3733 }
Mike Stump11289f42009-09-09 15:08:12 +00003734
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003735 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3736 if (LHSUnsigned) {
3737 // If the unsigned [LHS] type is larger, return it.
3738 if (LHSRank >= RHSRank)
3739 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00003740
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003741 // If the signed type can represent all values of the unsigned type, it
3742 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003743 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003744 return -1;
3745 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00003746
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003747 // If the unsigned [RHS] type is larger, return it.
3748 if (RHSRank >= LHSRank)
3749 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00003750
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003751 // If the signed type can represent all values of the unsigned type, it
3752 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00003753 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00003754 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00003755}
Anders Carlsson98f07902007-08-17 05:31:46 +00003756
Anders Carlsson6d417272009-11-14 21:45:58 +00003757static RecordDecl *
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003758CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3759 DeclContext *DC, IdentifierInfo *Id) {
3760 SourceLocation Loc;
Anders Carlsson6d417272009-11-14 21:45:58 +00003761 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003762 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003763 else
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003764 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson6d417272009-11-14 21:45:58 +00003765}
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003766
Mike Stump11289f42009-09-09 15:08:12 +00003767// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad39c79802011-01-12 09:06:06 +00003768QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00003769 if (!CFConstantStringTypeDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00003770 CFConstantStringTypeDecl =
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003771 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003772 &Idents.get("NSConstantString"));
John McCallae580fe2010-02-05 01:33:36 +00003773 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00003774
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003775 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00003776
Anders Carlsson98f07902007-08-17 05:31:46 +00003777 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00003778 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlsson9c1011c2007-11-19 00:25:30 +00003779 // int flags;
3780 FieldTypes[1] = IntTy;
Anders Carlsson98f07902007-08-17 05:31:46 +00003781 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00003782 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson98f07902007-08-17 05:31:46 +00003783 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00003784 FieldTypes[3] = LongTy;
3785
Anders Carlsson98f07902007-08-17 05:31:46 +00003786 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00003787 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00003788 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003789 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00003790 SourceLocation(), 0,
John McCallbcd03502009-12-07 02:54:59 +00003791 FieldTypes[i], /*TInfo=*/0,
Mike Stump11289f42009-09-09 15:08:12 +00003792 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003793 /*Mutable=*/false,
3794 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003795 Field->setAccess(AS_public);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003796 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00003797 }
3798
Douglas Gregord5058122010-02-11 01:19:42 +00003799 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson98f07902007-08-17 05:31:46 +00003800 }
Mike Stump11289f42009-09-09 15:08:12 +00003801
Anders Carlsson98f07902007-08-17 05:31:46 +00003802 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif412af032007-09-11 15:32:40 +00003803}
Anders Carlsson87c149b2007-10-11 01:00:40 +00003804
Douglas Gregor512b0772009-04-23 22:29:11 +00003805void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003806 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor512b0772009-04-23 22:29:11 +00003807 assert(Rec && "Invalid CFConstantStringType");
3808 CFConstantStringTypeDecl = Rec->getDecl();
3809}
3810
Jay Foad39c79802011-01-12 09:06:06 +00003811QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00003812 if (BlockDescriptorType)
3813 return getTagDeclType(BlockDescriptorType);
3814
3815 RecordDecl *T;
3816 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003817 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003818 &Idents.get("__block_descriptor"));
John McCallae580fe2010-02-05 01:33:36 +00003819 T->startDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003820
3821 QualType FieldTypes[] = {
3822 UnsignedLongTy,
3823 UnsignedLongTy,
3824 };
3825
3826 const char *FieldNames[] = {
3827 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003828 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00003829 };
3830
3831 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003832 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpd0153282009-10-20 02:12:22 +00003833 SourceLocation(),
3834 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003835 FieldTypes[i], /*TInfo=*/0,
Mike Stumpd0153282009-10-20 02:12:22 +00003836 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003837 /*Mutable=*/false,
3838 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003839 Field->setAccess(AS_public);
Mike Stumpd0153282009-10-20 02:12:22 +00003840 T->addDecl(Field);
3841 }
3842
Douglas Gregord5058122010-02-11 01:19:42 +00003843 T->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00003844
3845 BlockDescriptorType = T;
3846
3847 return getTagDeclType(BlockDescriptorType);
3848}
3849
Jay Foad39c79802011-01-12 09:06:06 +00003850QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003851 if (BlockDescriptorExtendedType)
3852 return getTagDeclType(BlockDescriptorExtendedType);
3853
3854 RecordDecl *T;
3855 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003856 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson6d417272009-11-14 21:45:58 +00003857 &Idents.get("__block_descriptor_withcopydispose"));
John McCallae580fe2010-02-05 01:33:36 +00003858 T->startDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003859
3860 QualType FieldTypes[] = {
3861 UnsignedLongTy,
3862 UnsignedLongTy,
3863 getPointerType(VoidPtrTy),
3864 getPointerType(VoidPtrTy)
3865 };
3866
3867 const char *FieldNames[] = {
3868 "reserved",
3869 "Size",
3870 "CopyFuncPtr",
3871 "DestroyFuncPtr"
3872 };
3873
3874 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003875 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003876 SourceLocation(),
3877 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003878 FieldTypes[i], /*TInfo=*/0,
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003879 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003880 /*Mutable=*/false,
3881 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003882 Field->setAccess(AS_public);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003883 T->addDecl(Field);
3884 }
3885
Douglas Gregord5058122010-02-11 01:19:42 +00003886 T->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00003887
3888 BlockDescriptorExtendedType = T;
3889
3890 return getTagDeclType(BlockDescriptorExtendedType);
3891}
3892
Jay Foad39c79802011-01-12 09:06:06 +00003893bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCall31168b02011-06-15 23:02:42 +00003894 if (Ty->isObjCRetainableType())
Mike Stump94967902009-10-21 18:16:27 +00003895 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003896 if (getLangOptions().CPlusPlus) {
3897 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3898 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntfcaeae42011-05-25 20:50:04 +00003899 return RD->hasConstCopyConstructor();
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00003900
3901 }
3902 }
Mike Stump94967902009-10-21 18:16:27 +00003903 return false;
3904}
3905
Jay Foad39c79802011-01-12 09:06:06 +00003906QualType
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003907ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stump94967902009-10-21 18:16:27 +00003908 // type = struct __Block_byref_1_X {
Mike Stump7fe9cc12009-10-21 03:49:08 +00003909 // void *__isa;
Mike Stump94967902009-10-21 18:16:27 +00003910 // struct __Block_byref_1_X *__forwarding;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003911 // unsigned int __flags;
3912 // unsigned int __size;
Eli Friedman04831922010-08-22 01:00:03 +00003913 // void *__copy_helper; // as needed
3914 // void *__destroy_help // as needed
Mike Stump94967902009-10-21 18:16:27 +00003915 // int X;
Mike Stump7fe9cc12009-10-21 03:49:08 +00003916 // } *
3917
Mike Stump94967902009-10-21 18:16:27 +00003918 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3919
3920 // FIXME: Move up
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003921 SmallString<36> Name;
Benjamin Kramer1402ce32009-10-24 09:57:09 +00003922 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3923 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stump94967902009-10-21 18:16:27 +00003924 RecordDecl *T;
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003925 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stump94967902009-10-21 18:16:27 +00003926 T->startDefinition();
3927 QualType Int32Ty = IntTy;
3928 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3929 QualType FieldTypes[] = {
3930 getPointerType(VoidPtrTy),
3931 getPointerType(getTagDeclType(T)),
3932 Int32Ty,
3933 Int32Ty,
3934 getPointerType(VoidPtrTy),
3935 getPointerType(VoidPtrTy),
3936 Ty
3937 };
3938
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003939 StringRef FieldNames[] = {
Mike Stump94967902009-10-21 18:16:27 +00003940 "__isa",
3941 "__forwarding",
3942 "__flags",
3943 "__size",
3944 "__copy_helper",
3945 "__destroy_helper",
3946 DeclName,
3947 };
3948
3949 for (size_t i = 0; i < 7; ++i) {
3950 if (!HasCopyAndDispose && i >=4 && i <= 5)
3951 continue;
3952 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003953 SourceLocation(),
Mike Stump94967902009-10-21 18:16:27 +00003954 &Idents.get(FieldNames[i]),
John McCallbcd03502009-12-07 02:54:59 +00003955 FieldTypes[i], /*TInfo=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00003956 /*BitWidth=*/0, /*Mutable=*/false,
3957 /*HasInit=*/false);
John McCall4d4dcc82010-04-30 21:35:41 +00003958 Field->setAccess(AS_public);
Mike Stump94967902009-10-21 18:16:27 +00003959 T->addDecl(Field);
3960 }
3961
Douglas Gregord5058122010-02-11 01:19:42 +00003962 T->completeDefinition();
Mike Stump94967902009-10-21 18:16:27 +00003963
3964 return getPointerType(getTagDeclType(T));
Mike Stump7fe9cc12009-10-21 03:49:08 +00003965}
3966
Douglas Gregorbab8a962011-09-08 01:46:34 +00003967TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3968 if (!ObjCInstanceTypeDecl)
3969 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3970 getTranslationUnitDecl(),
3971 SourceLocation(),
3972 SourceLocation(),
3973 &Idents.get("instancetype"),
3974 getTrivialTypeSourceInfo(getObjCIdType()));
3975 return ObjCInstanceTypeDecl;
3976}
3977
Anders Carlsson18acd442007-10-29 06:33:42 +00003978// This returns true if a type has been typedefed to BOOL:
3979// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00003980static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00003981 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00003982 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3983 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00003984
Anders Carlssond8499822007-10-29 05:01:08 +00003985 return false;
3986}
3987
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003988/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003989/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00003990CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00003991 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3992 return CharUnits::Zero();
3993
Ken Dyck40775002010-01-11 17:06:35 +00003994 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00003995
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003996 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00003997 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00003998 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003999 // Treat arrays as pointers, since that's how they're passed in.
4000 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00004001 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00004002 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00004003}
4004
4005static inline
4006std::string charUnitsToString(const CharUnits &CU) {
4007 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004008}
4009
John McCall351762c2011-02-07 10:33:21 +00004010/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00004011/// declaration.
John McCall351762c2011-02-07 10:33:21 +00004012std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4013 std::string S;
4014
David Chisnall950a9512009-11-17 19:33:30 +00004015 const BlockDecl *Decl = Expr->getBlockDecl();
4016 QualType BlockTy =
4017 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4018 // Encode result type.
John McCall8e346702010-06-04 19:02:56 +00004019 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00004020 // Compute size of all parameters.
4021 // Start with computing size of a pointer in number of bytes.
4022 // FIXME: There might(should) be a better way of doing this computation!
4023 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004024 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4025 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian590c3522010-04-08 18:06:22 +00004026 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall950a9512009-11-17 19:33:30 +00004027 E = Decl->param_end(); PI != E; ++PI) {
4028 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004029 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck40775002010-01-11 17:06:35 +00004030 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00004031 ParmOffset += sz;
4032 }
4033 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00004034 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00004035 // Block pointer and offset.
4036 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00004037
4038 // Argument types.
4039 ParmOffset = PtrSize;
4040 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4041 Decl->param_end(); PI != E; ++PI) {
4042 ParmVarDecl *PVDecl = *PI;
4043 QualType PType = PVDecl->getOriginalType();
4044 if (const ArrayType *AT =
4045 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4046 // Use array's original type only if it has known number of
4047 // elements.
4048 if (!isa<ConstantArrayType>(AT))
4049 PType = PVDecl->getType();
4050 } else if (PType->isFunctionType())
4051 PType = PVDecl->getType();
4052 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00004053 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004054 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00004055 }
John McCall351762c2011-02-07 10:33:21 +00004056
4057 return S;
David Chisnall950a9512009-11-17 19:33:30 +00004058}
4059
Douglas Gregora9d84932011-05-27 01:19:52 +00004060bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall50e4eba2010-12-30 14:05:53 +00004061 std::string& S) {
4062 // Encode result type.
4063 getObjCEncodingForType(Decl->getResultType(), S);
4064 CharUnits ParmOffset;
4065 // Compute size of all parameters.
4066 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4067 E = Decl->param_end(); PI != E; ++PI) {
4068 QualType PType = (*PI)->getType();
4069 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004070 if (sz.isZero())
4071 return true;
4072
David Chisnall50e4eba2010-12-30 14:05:53 +00004073 assert (sz.isPositive() &&
Douglas Gregora9d84932011-05-27 01:19:52 +00004074 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00004075 ParmOffset += sz;
4076 }
4077 S += charUnitsToString(ParmOffset);
4078 ParmOffset = CharUnits::Zero();
4079
4080 // Argument types.
4081 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4082 E = Decl->param_end(); PI != E; ++PI) {
4083 ParmVarDecl *PVDecl = *PI;
4084 QualType PType = PVDecl->getOriginalType();
4085 if (const ArrayType *AT =
4086 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4087 // Use array's original type only if it has known number of
4088 // elements.
4089 if (!isa<ConstantArrayType>(AT))
4090 PType = PVDecl->getType();
4091 } else if (PType->isFunctionType())
4092 PType = PVDecl->getType();
4093 getObjCEncodingForType(PType, S);
4094 S += charUnitsToString(ParmOffset);
4095 ParmOffset += getObjCEncodingTypeSize(PType);
4096 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004097
4098 return false;
David Chisnall50e4eba2010-12-30 14:05:53 +00004099}
4100
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004101/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4102/// method parameter or return type. If Extended, include class names and
4103/// block object types.
4104void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4105 QualType T, std::string& S,
4106 bool Extended) const {
4107 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4108 getObjCEncodingForTypeQualifier(QT, S);
4109 // Encode parameter type.
4110 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4111 true /*OutermostType*/,
4112 false /*EncodingProperty*/,
4113 false /*StructField*/,
4114 Extended /*EncodeBlockParameters*/,
4115 Extended /*EncodeClassNames*/);
4116}
4117
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004118/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004119/// declaration.
Douglas Gregora9d84932011-05-27 01:19:52 +00004120bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004121 std::string& S,
4122 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004123 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004124 // Encode return type.
4125 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4126 Decl->getResultType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004127 // Compute size of all parameters.
4128 // Start with computing size of a pointer in number of bytes.
4129 // FIXME: There might(should) be a better way of doing this computation!
4130 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00004131 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004132 // The first two arguments (self and _cmd) are pointers; account for
4133 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00004134 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004135 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004136 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00004137 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00004138 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00004139 if (sz.isZero())
4140 return true;
4141
Ken Dyck40775002010-01-11 17:06:35 +00004142 assert (sz.isPositive() &&
4143 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004144 ParmOffset += sz;
4145 }
Ken Dyck40775002010-01-11 17:06:35 +00004146 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004147 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00004148 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00004149
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004150 // Argument types.
4151 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004152 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00004153 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004154 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00004155 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00004156 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00004157 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4158 // Use array's original type only if it has known number of
4159 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00004160 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00004161 PType = PVDecl->getType();
4162 } else if (PType->isFunctionType())
4163 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004164 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4165 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00004166 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00004167 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004168 }
Douglas Gregora9d84932011-05-27 01:19:52 +00004169
4170 return false;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00004171}
4172
Daniel Dunbar4932b362008-08-28 04:38:10 +00004173/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004174/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00004175/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4176/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00004177/// Property attributes are stored as a comma-delimited C string. The simple
4178/// attributes readonly and bycopy are encoded as single characters. The
4179/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4180/// encoded as single characters, followed by an identifier. Property types
4181/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00004182/// these attributes are defined by the following enumeration:
4183/// @code
4184/// enum PropertyAttributes {
4185/// kPropertyReadOnly = 'R', // property is read-only.
4186/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4187/// kPropertyByref = '&', // property is a reference to the value last assigned
4188/// kPropertyDynamic = 'D', // property is dynamic
4189/// kPropertyGetter = 'G', // followed by getter selector name
4190/// kPropertySetter = 'S', // followed by setter selector name
4191/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4192/// kPropertyType = 't' // followed by old-style type encoding.
4193/// kPropertyWeak = 'W' // 'weak' property
4194/// kPropertyStrong = 'P' // property GC'able
4195/// kPropertyNonAtomic = 'N' // property non-atomic
4196/// };
4197/// @endcode
Mike Stump11289f42009-09-09 15:08:12 +00004198void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbar4932b362008-08-28 04:38:10 +00004199 const Decl *Container,
Jay Foad39c79802011-01-12 09:06:06 +00004200 std::string& S) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004201 // Collect information from the property implementation decl(s).
4202 bool Dynamic = false;
4203 ObjCPropertyImplDecl *SynthesizePID = 0;
4204
4205 // FIXME: Duplicated code due to poor abstraction.
4206 if (Container) {
Mike Stump11289f42009-09-09 15:08:12 +00004207 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbar4932b362008-08-28 04:38:10 +00004208 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4209 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004210 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004211 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004212 ObjCPropertyImplDecl *PID = *i;
4213 if (PID->getPropertyDecl() == PD) {
4214 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4215 Dynamic = true;
4216 } else {
4217 SynthesizePID = PID;
4218 }
4219 }
4220 }
4221 } else {
Chris Lattner465fa322008-10-05 17:34:18 +00004222 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004223 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004224 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00004225 i != e; ++i) {
Daniel Dunbar4932b362008-08-28 04:38:10 +00004226 ObjCPropertyImplDecl *PID = *i;
4227 if (PID->getPropertyDecl() == PD) {
4228 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4229 Dynamic = true;
4230 } else {
4231 SynthesizePID = PID;
4232 }
4233 }
Mike Stump11289f42009-09-09 15:08:12 +00004234 }
Daniel Dunbar4932b362008-08-28 04:38:10 +00004235 }
4236 }
4237
4238 // FIXME: This is not very efficient.
4239 S = "T";
4240
4241 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004242 // GCC has some special rules regarding encoding of properties which
4243 // closely resembles encoding of ivars.
Mike Stump11289f42009-09-09 15:08:12 +00004244 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004245 true /* outermost type */,
4246 true /* encoding for property */);
Daniel Dunbar4932b362008-08-28 04:38:10 +00004247
4248 if (PD->isReadOnly()) {
4249 S += ",R";
4250 } else {
4251 switch (PD->getSetterKind()) {
4252 case ObjCPropertyDecl::Assign: break;
4253 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00004254 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00004255 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00004256 }
4257 }
4258
4259 // It really isn't clear at all what this means, since properties
4260 // are "dynamic by default".
4261 if (Dynamic)
4262 S += ",D";
4263
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004264 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4265 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00004266
Daniel Dunbar4932b362008-08-28 04:38:10 +00004267 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4268 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00004269 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004270 }
4271
4272 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4273 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00004274 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004275 }
4276
4277 if (SynthesizePID) {
4278 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4279 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00004280 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00004281 }
4282
4283 // FIXME: OBJCGC: weak & strong
4284}
4285
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004286/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00004287/// Another legacy compatibility encoding: 32-bit longs are encoded as
4288/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004289/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4290///
4291void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00004292 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00004293 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00004294 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004295 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00004296 else
Jay Foad39c79802011-01-12 09:06:06 +00004297 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004298 PointeeTy = IntTy;
4299 }
4300 }
4301}
4302
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004303void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad39c79802011-01-12 09:06:06 +00004304 const FieldDecl *Field) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004305 // We follow the behavior of gcc, expanding structures which are
4306 // directly pointed to, and expanding embedded structures. Note that
4307 // these rules are sufficient to prevent recursive encoding of the
4308 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00004309 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahaniandaef00b2008-12-22 23:22:27 +00004310 true /* outermost type */);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004311}
4312
David Chisnallb190a2c2010-06-04 01:10:52 +00004313static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4314 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00004315 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnallb190a2c2010-06-04 01:10:52 +00004316 case BuiltinType::Void: return 'v';
4317 case BuiltinType::Bool: return 'B';
4318 case BuiltinType::Char_U:
4319 case BuiltinType::UChar: return 'C';
4320 case BuiltinType::UShort: return 'S';
4321 case BuiltinType::UInt: return 'I';
4322 case BuiltinType::ULong:
Jay Foad39c79802011-01-12 09:06:06 +00004323 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004324 case BuiltinType::UInt128: return 'T';
4325 case BuiltinType::ULongLong: return 'Q';
4326 case BuiltinType::Char_S:
4327 case BuiltinType::SChar: return 'c';
4328 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00004329 case BuiltinType::WChar_S:
4330 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00004331 case BuiltinType::Int: return 'i';
4332 case BuiltinType::Long:
Jay Foad39c79802011-01-12 09:06:06 +00004333 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00004334 case BuiltinType::LongLong: return 'q';
4335 case BuiltinType::Int128: return 't';
4336 case BuiltinType::Float: return 'f';
4337 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00004338 case BuiltinType::LongDouble: return 'D';
David Chisnallb190a2c2010-06-04 01:10:52 +00004339 }
4340}
4341
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004342static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4343 EnumDecl *Enum = ET->getDecl();
4344
4345 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4346 if (!Enum->isFixed())
4347 return 'i';
4348
4349 // The encoding of a fixed enum type matches its fixed underlying type.
4350 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4351}
4352
Jay Foad39c79802011-01-12 09:06:06 +00004353static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00004354 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00004355 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004356 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00004357 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4358 // The GNU runtime requires more information; bitfields are encoded as b,
4359 // then the offset (in bits) of the first element, then the type of the
4360 // bitfield, then the size in bits. For example, in this structure:
4361 //
4362 // struct
4363 // {
4364 // int integer;
4365 // int flags:2;
4366 // };
4367 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4368 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4369 // information is not especially sensible, but we're stuck with it for
4370 // compatibility with GCC, although providing it breaks anything that
4371 // actually uses runtime introspection and wants to work on both runtimes...
4372 if (!Ctx->getLangOptions().NeXTRuntime) {
4373 const RecordDecl *RD = FD->getParent();
4374 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00004375 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004376 if (const EnumType *ET = T->getAs<EnumType>())
4377 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnall6f0a7d22010-12-26 20:12:30 +00004378 else
Jay Foad39c79802011-01-12 09:06:06 +00004379 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnallb190a2c2010-06-04 01:10:52 +00004380 }
Richard Smithcaf33902011-10-10 18:28:20 +00004381 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004382}
4383
Daniel Dunbar07d07852009-10-18 21:17:35 +00004384// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004385void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4386 bool ExpandPointedToStructures,
4387 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00004388 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00004389 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004390 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004391 bool StructField,
4392 bool EncodeBlockParameters,
4393 bool EncodeClassNames) const {
David Chisnallb190a2c2010-06-04 01:10:52 +00004394 if (T->getAs<BuiltinType>()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004395 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004396 return EncodeBitField(this, S, T, FD);
4397 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004398 return;
4399 }
Mike Stump11289f42009-09-09 15:08:12 +00004400
John McCall9dd450b2009-09-21 23:43:11 +00004401 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlsson39b2e132009-04-09 21:55:45 +00004402 S += 'j';
Mike Stump11289f42009-09-09 15:08:12 +00004403 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlsson39b2e132009-04-09 21:55:45 +00004404 false);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004405 return;
4406 }
Fariborz Jahaniand25c2192009-11-23 20:40:50 +00004407
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004408 // encoding for pointer or r3eference types.
4409 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004410 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian89b660c2009-11-30 18:43:52 +00004411 if (PT->isObjCSelType()) {
4412 S += ':';
4413 return;
4414 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004415 PointeeTy = PT->getPointeeType();
4416 }
4417 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4418 PointeeTy = RT->getPointeeType();
4419 if (!PointeeTy.isNull()) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004420 bool isReadOnly = false;
4421 // For historical/compatibility reasons, the read-only qualifier of the
4422 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4423 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00004424 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00004425 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004426 if (OutermostType && T.isConstQualified()) {
4427 isReadOnly = true;
4428 S += 'r';
4429 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00004430 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004431 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004432 while (P->getAs<PointerType>())
4433 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004434 if (P.isConstQualified()) {
4435 isReadOnly = true;
4436 S += 'r';
4437 }
4438 }
4439 if (isReadOnly) {
4440 // Another legacy compatibility encoding. Some ObjC qualifier and type
4441 // combinations need to be rearranged.
4442 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004443 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00004444 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004445 }
Mike Stump11289f42009-09-09 15:08:12 +00004446
Anders Carlssond8499822007-10-29 05:01:08 +00004447 if (PointeeTy->isCharType()) {
4448 // char pointer types should be encoded as '*' unless it is a
4449 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00004450 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00004451 S += '*';
4452 return;
4453 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004454 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00004455 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4456 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4457 S += '#';
4458 return;
4459 }
4460 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4461 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4462 S += '@';
4463 return;
4464 }
4465 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00004466 }
Anders Carlssond8499822007-10-29 05:01:08 +00004467 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00004468 getLegacyIntegralTypeEncoding(PointeeTy);
4469
Mike Stump11289f42009-09-09 15:08:12 +00004470 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004471 NULL);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004472 return;
4473 }
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00004474
Chris Lattnere7cabb92009-07-13 00:10:46 +00004475 if (const ArrayType *AT =
4476 // Ignore type qualifiers etc.
4477 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004478 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004479 // Incomplete arrays are encoded as a pointer to the array element.
4480 S += '^';
4481
Mike Stump11289f42009-09-09 15:08:12 +00004482 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004483 false, ExpandStructures, FD);
4484 } else {
4485 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00004486
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004487 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4488 if (getTypeSize(CAT->getElementType()) == 0)
4489 S += '0';
4490 else
4491 S += llvm::utostr(CAT->getSize().getZExtValue());
4492 } else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00004493 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004494 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4495 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00004496 S += '0';
4497 }
Mike Stump11289f42009-09-09 15:08:12 +00004498
4499 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00004500 false, ExpandStructures, FD);
4501 S += ']';
4502 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004503 return;
4504 }
Mike Stump11289f42009-09-09 15:08:12 +00004505
John McCall9dd450b2009-09-21 23:43:11 +00004506 if (T->getAs<FunctionType>()) {
Anders Carlssondf4cc612007-10-30 00:06:20 +00004507 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004508 return;
4509 }
Mike Stump11289f42009-09-09 15:08:12 +00004510
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004511 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00004512 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004513 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00004514 // Anonymous structures print as '?'
4515 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4516 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004517 if (ClassTemplateSpecializationDecl *Spec
4518 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4519 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4520 std::string TemplateArgsStr
4521 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004522 TemplateArgs.data(),
4523 TemplateArgs.size(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00004524 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00004525
4526 S += TemplateArgsStr;
4527 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00004528 } else {
4529 S += '?';
4530 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00004531 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004532 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004533 if (!RDecl->isUnion()) {
4534 getObjCEncodingForStructureImpl(RDecl, S, FD);
4535 } else {
4536 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4537 FieldEnd = RDecl->field_end();
4538 Field != FieldEnd; ++Field) {
4539 if (FD) {
4540 S += '"';
4541 S += Field->getNameAsString();
4542 S += '"';
4543 }
Mike Stump11289f42009-09-09 15:08:12 +00004544
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004545 // Special case bit-fields.
4546 if (Field->isBitField()) {
4547 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4548 (*Field));
4549 } else {
4550 QualType qt = Field->getType();
4551 getLegacyIntegralTypeEncoding(qt);
4552 getObjCEncodingForTypeImpl(qt, S, false, true,
4553 FD, /*OutermostType*/false,
4554 /*EncodingProperty*/false,
4555 /*StructField*/true);
4556 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004557 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00004558 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00004559 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00004560 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004561 return;
4562 }
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004563
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004564 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004565 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00004566 EncodeBitField(this, S, T, FD);
Fariborz Jahanian5c767722009-01-13 01:18:13 +00004567 else
Douglas Gregor8b7d4032011-09-08 17:18:35 +00004568 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnere7cabb92009-07-13 00:10:46 +00004569 return;
4570 }
Mike Stump11289f42009-09-09 15:08:12 +00004571
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004572 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff49140cb2009-02-02 18:24:29 +00004573 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004574 if (EncodeBlockParameters) {
4575 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4576
4577 S += '<';
4578 // Block return type
4579 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4580 ExpandPointedToStructures, ExpandStructures,
4581 FD,
4582 false /* OutermostType */,
4583 EncodingProperty,
4584 false /* StructField */,
4585 EncodeBlockParameters,
4586 EncodeClassNames);
4587 // Block self
4588 S += "@?";
4589 // Block parameters
4590 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4591 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4592 E = FPT->arg_type_end(); I && (I != E); ++I) {
4593 getObjCEncodingForTypeImpl(*I, S,
4594 ExpandPointedToStructures,
4595 ExpandStructures,
4596 FD,
4597 false /* OutermostType */,
4598 EncodingProperty,
4599 false /* StructField */,
4600 EncodeBlockParameters,
4601 EncodeClassNames);
4602 }
4603 }
4604 S += '>';
4605 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004606 return;
4607 }
Mike Stump11289f42009-09-09 15:08:12 +00004608
John McCall8b07ec22010-05-15 11:32:37 +00004609 // Ignore protocol qualifiers when mangling at this level.
4610 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4611 T = OT->getBaseType();
4612
John McCall8ccfcb52009-09-24 19:53:00 +00004613 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004614 // @encode(class_name)
John McCall8ccfcb52009-09-24 19:53:00 +00004615 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004616 S += '{';
4617 const IdentifierInfo *II = OI->getIdentifier();
4618 S += II->getName();
4619 S += '=';
Jordy Rosea91768e2011-07-22 02:08:32 +00004620 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004621 DeepCollectObjCIvars(OI, true, Ivars);
4622 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004623 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004624 if (Field->isBitField())
4625 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004626 else
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004627 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004628 }
4629 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00004630 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00004631 }
Mike Stump11289f42009-09-09 15:08:12 +00004632
John McCall9dd450b2009-09-21 23:43:11 +00004633 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004634 if (OPT->isObjCIdType()) {
4635 S += '@';
4636 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004637 }
Mike Stump11289f42009-09-09 15:08:12 +00004638
Steve Narofff0c86112009-10-28 22:03:49 +00004639 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4640 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4641 // Since this is a binary compatibility issue, need to consult with runtime
4642 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004643 S += '#';
4644 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004645 }
Mike Stump11289f42009-09-09 15:08:12 +00004646
Chris Lattnere7cabb92009-07-13 00:10:46 +00004647 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004648 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00004649 ExpandPointedToStructures,
4650 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004651 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004652 // Note that we do extended encoding of protocol qualifer list
4653 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004654 S += '"';
Steve Naroffaccc4882009-07-20 17:56:53 +00004655 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4656 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004657 S += '<';
4658 S += (*I)->getNameAsString();
4659 S += '>';
4660 }
4661 S += '"';
4662 }
4663 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00004664 }
Mike Stump11289f42009-09-09 15:08:12 +00004665
Chris Lattnere7cabb92009-07-13 00:10:46 +00004666 QualType PointeeTy = OPT->getPointeeType();
4667 if (!EncodingProperty &&
4668 isa<TypedefType>(PointeeTy.getTypePtr())) {
4669 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00004670 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00004671 // {...};
4672 S += '^';
Mike Stump11289f42009-09-09 15:08:12 +00004673 getObjCEncodingForTypeImpl(PointeeTy, S,
4674 false, ExpandPointedToStructures,
Chris Lattnere7cabb92009-07-13 00:10:46 +00004675 NULL);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004676 return;
4677 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004678
4679 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00004680 if (OPT->getInterfaceDecl() &&
4681 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004682 S += '"';
Steve Narofff0c86112009-10-28 22:03:49 +00004683 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroffaccc4882009-07-20 17:56:53 +00004684 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4685 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00004686 S += '<';
4687 S += (*I)->getNameAsString();
4688 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00004689 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00004690 S += '"';
4691 }
4692 return;
4693 }
Mike Stump11289f42009-09-09 15:08:12 +00004694
John McCalla9e6e8d2010-05-17 23:56:34 +00004695 // gcc just blithely ignores member pointers.
4696 // TODO: maybe there should be a mangling for these
4697 if (T->getAs<MemberPointerType>())
4698 return;
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00004699
4700 if (T->isVectorType()) {
4701 // This matches gcc's encoding, even though technically it is
4702 // insufficient.
4703 // FIXME. We should do a better job than gcc.
4704 return;
4705 }
4706
David Blaikie83d382b2011-09-23 05:06:16 +00004707 llvm_unreachable("@encode for type not implemented!");
Anders Carlssond8499822007-10-29 05:01:08 +00004708}
4709
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004710void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4711 std::string &S,
4712 const FieldDecl *FD,
4713 bool includeVBases) const {
4714 assert(RDecl && "Expected non-null RecordDecl");
4715 assert(!RDecl->isUnion() && "Should not be called for unions");
4716 if (!RDecl->getDefinition())
4717 return;
4718
4719 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4720 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4721 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4722
4723 if (CXXRec) {
4724 for (CXXRecordDecl::base_class_iterator
4725 BI = CXXRec->bases_begin(),
4726 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4727 if (!BI->isVirtual()) {
4728 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004729 if (base->isEmpty())
4730 continue;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004731 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4732 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4733 std::make_pair(offs, base));
4734 }
4735 }
4736 }
4737
4738 unsigned i = 0;
4739 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4740 FieldEnd = RDecl->field_end();
4741 Field != FieldEnd; ++Field, ++i) {
4742 uint64_t offs = layout.getFieldOffset(i);
4743 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4744 std::make_pair(offs, *Field));
4745 }
4746
4747 if (CXXRec && includeVBases) {
4748 for (CXXRecordDecl::base_class_iterator
4749 BI = CXXRec->vbases_begin(),
4750 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
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.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00004755 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4756 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4757 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004758 }
4759 }
4760
4761 CharUnits size;
4762 if (CXXRec) {
4763 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4764 } else {
4765 size = layout.getSize();
4766 }
4767
4768 uint64_t CurOffs = 0;
4769 std::multimap<uint64_t, NamedDecl *>::iterator
4770 CurLayObj = FieldOrBaseOffsets.begin();
4771
Argyrios Kyrtzidisc7e50c52011-08-22 16:03:14 +00004772 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4773 (CurLayObj == FieldOrBaseOffsets.end() &&
4774 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004775 assert(CXXRec && CXXRec->isDynamicClass() &&
4776 "Offset 0 was empty but no VTable ?");
4777 if (FD) {
4778 S += "\"_vptr$";
4779 std::string recname = CXXRec->getNameAsString();
4780 if (recname.empty()) recname = "?";
4781 S += recname;
4782 S += '"';
4783 }
4784 S += "^^?";
4785 CurOffs += getTypeSize(VoidPtrTy);
4786 }
4787
4788 if (!RDecl->hasFlexibleArrayMember()) {
4789 // Mark the end of the structure.
4790 uint64_t offs = toBits(size);
4791 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4792 std::make_pair(offs, (NamedDecl*)0));
4793 }
4794
4795 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4796 assert(CurOffs <= CurLayObj->first);
4797
4798 if (CurOffs < CurLayObj->first) {
4799 uint64_t padding = CurLayObj->first - CurOffs;
4800 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4801 // packing/alignment of members is different that normal, in which case
4802 // the encoding will be out-of-sync with the real layout.
4803 // If the runtime switches to just consider the size of types without
4804 // taking into account alignment, we could make padding explicit in the
4805 // encoding (e.g. using arrays of chars). The encoding strings would be
4806 // longer then though.
4807 CurOffs += padding;
4808 }
4809
4810 NamedDecl *dcl = CurLayObj->second;
4811 if (dcl == 0)
4812 break; // reached end of structure.
4813
4814 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4815 // We expand the bases without their virtual bases since those are going
4816 // in the initial structure. Note that this differs from gcc which
4817 // expands virtual bases each time one is encountered in the hierarchy,
4818 // making the encoding type bigger than it really is.
4819 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00004820 assert(!base->isEmpty());
4821 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004822 } else {
4823 FieldDecl *field = cast<FieldDecl>(dcl);
4824 if (FD) {
4825 S += '"';
4826 S += field->getNameAsString();
4827 S += '"';
4828 }
4829
4830 if (field->isBitField()) {
4831 EncodeBitField(this, S, field->getType(), field);
Richard Smithcaf33902011-10-10 18:28:20 +00004832 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00004833 } else {
4834 QualType qt = field->getType();
4835 getLegacyIntegralTypeEncoding(qt);
4836 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4837 /*OutermostType*/false,
4838 /*EncodingProperty*/false,
4839 /*StructField*/true);
4840 CurOffs += getTypeSize(field->getType());
4841 }
4842 }
4843 }
4844}
4845
Mike Stump11289f42009-09-09 15:08:12 +00004846void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00004847 std::string& S) const {
4848 if (QT & Decl::OBJC_TQ_In)
4849 S += 'n';
4850 if (QT & Decl::OBJC_TQ_Inout)
4851 S += 'N';
4852 if (QT & Decl::OBJC_TQ_Out)
4853 S += 'o';
4854 if (QT & Decl::OBJC_TQ_Bycopy)
4855 S += 'O';
4856 if (QT & Decl::OBJC_TQ_Byref)
4857 S += 'R';
4858 if (QT & Decl::OBJC_TQ_Oneway)
4859 S += 'V';
4860}
4861
Chris Lattnere7cabb92009-07-13 00:10:46 +00004862void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlsson87c149b2007-10-11 01:00:40 +00004863 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004864
Anders Carlsson87c149b2007-10-11 01:00:40 +00004865 BuiltinVaListType = T;
4866}
4867
Douglas Gregor3ea72692011-08-12 05:46:01 +00004868TypedefDecl *ASTContext::getObjCIdDecl() const {
4869 if (!ObjCIdDecl) {
4870 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4871 T = getObjCObjectPointerType(T);
4872 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4873 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4874 getTranslationUnitDecl(),
4875 SourceLocation(), SourceLocation(),
4876 &Idents.get("id"), IdInfo);
4877 }
4878
4879 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00004880}
4881
Douglas Gregor52e02802011-08-12 06:17:30 +00004882TypedefDecl *ASTContext::getObjCSelDecl() const {
4883 if (!ObjCSelDecl) {
4884 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4885 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4886 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4887 getTranslationUnitDecl(),
4888 SourceLocation(), SourceLocation(),
4889 &Idents.get("SEL"), SelInfo);
4890 }
4891 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00004892}
4893
Douglas Gregor0a586182011-08-12 05:59:41 +00004894TypedefDecl *ASTContext::getObjCClassDecl() const {
4895 if (!ObjCClassDecl) {
4896 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4897 T = getObjCObjectPointerType(T);
4898 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4899 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4900 getTranslationUnitDecl(),
4901 SourceLocation(), SourceLocation(),
4902 &Idents.get("Class"), ClassInfo);
4903 }
4904
4905 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00004906}
4907
Douglas Gregord53ae832012-01-17 18:09:05 +00004908ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4909 if (!ObjCProtocolClassDecl) {
4910 ObjCProtocolClassDecl
4911 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4912 SourceLocation(),
4913 &Idents.get("Protocol"),
4914 /*PrevDecl=*/0,
4915 SourceLocation(), true);
4916 }
4917
4918 return ObjCProtocolClassDecl;
4919}
4920
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004921void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00004922 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00004923 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00004924
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004925 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00004926}
4927
John McCalld28ae272009-12-02 08:04:21 +00004928/// \brief Retrieve the template name that corresponds to a non-empty
4929/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00004930TemplateName
4931ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4932 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00004933 unsigned size = End - Begin;
4934 assert(size > 1 && "set is not overloaded!");
4935
4936 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4937 size * sizeof(FunctionTemplateDecl*));
4938 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4939
4940 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00004941 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00004942 NamedDecl *D = *I;
4943 assert(isa<FunctionTemplateDecl>(D) ||
4944 (isa<UsingShadowDecl>(D) &&
4945 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4946 *Storage++ = D;
4947 }
4948
4949 return TemplateName(OT);
4950}
4951
Douglas Gregordc572a32009-03-30 22:58:21 +00004952/// \brief Retrieve the template name that represents a qualified
4953/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00004954TemplateName
4955ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4956 bool TemplateKeyword,
4957 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00004958 assert(NNS && "Missing nested-name-specifier in qualified template name");
4959
Douglas Gregorc42075a2010-02-04 18:10:26 +00004960 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00004961 llvm::FoldingSetNodeID ID;
4962 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4963
4964 void *InsertPos = 0;
4965 QualifiedTemplateName *QTN =
4966 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4967 if (!QTN) {
4968 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4969 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4970 }
4971
4972 return TemplateName(QTN);
4973}
4974
4975/// \brief Retrieve the template name that represents a dependent
4976/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00004977TemplateName
4978ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4979 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00004980 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00004981 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00004982
4983 llvm::FoldingSetNodeID ID;
4984 DependentTemplateName::Profile(ID, NNS, Name);
4985
4986 void *InsertPos = 0;
4987 DependentTemplateName *QTN =
4988 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4989
4990 if (QTN)
4991 return TemplateName(QTN);
4992
4993 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4994 if (CanonNNS == NNS) {
4995 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4996 } else {
4997 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4998 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004999 DependentTemplateName *CheckQTN =
5000 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5001 assert(!CheckQTN && "Dependent type name canonicalization broken");
5002 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00005003 }
5004
5005 DependentTemplateNames.InsertNode(QTN, InsertPos);
5006 return TemplateName(QTN);
5007}
5008
Douglas Gregor71395fa2009-11-04 00:56:37 +00005009/// \brief Retrieve the template name that represents a dependent
5010/// template name such as \c MetaFun::template operator+.
5011TemplateName
5012ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00005013 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00005014 assert((!NNS || NNS->isDependent()) &&
5015 "Nested name specifier must be dependent");
5016
5017 llvm::FoldingSetNodeID ID;
5018 DependentTemplateName::Profile(ID, NNS, Operator);
5019
5020 void *InsertPos = 0;
Douglas Gregorc42075a2010-02-04 18:10:26 +00005021 DependentTemplateName *QTN
5022 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00005023
5024 if (QTN)
5025 return TemplateName(QTN);
5026
5027 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5028 if (CanonNNS == NNS) {
5029 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5030 } else {
5031 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5032 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00005033
5034 DependentTemplateName *CheckQTN
5035 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5036 assert(!CheckQTN && "Dependent template name canonicalization broken");
5037 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00005038 }
5039
5040 DependentTemplateNames.InsertNode(QTN, InsertPos);
5041 return TemplateName(QTN);
5042}
5043
Douglas Gregor5590be02011-01-15 06:45:20 +00005044TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00005045ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5046 TemplateName replacement) const {
5047 llvm::FoldingSetNodeID ID;
5048 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5049
5050 void *insertPos = 0;
5051 SubstTemplateTemplateParmStorage *subst
5052 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5053
5054 if (!subst) {
5055 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5056 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5057 }
5058
5059 return TemplateName(subst);
5060}
5061
5062TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00005063ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5064 const TemplateArgument &ArgPack) const {
5065 ASTContext &Self = const_cast<ASTContext &>(*this);
5066 llvm::FoldingSetNodeID ID;
5067 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5068
5069 void *InsertPos = 0;
5070 SubstTemplateTemplateParmPackStorage *Subst
5071 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5072
5073 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00005074 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00005075 ArgPack.pack_size(),
5076 ArgPack.pack_begin());
5077 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5078 }
5079
5080 return TemplateName(Subst);
5081}
5082
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005083/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00005084/// TargetInfo, produce the corresponding type. The unsigned @p Type
5085/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00005086CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005087 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00005088 case TargetInfo::NoInt: return CanQualType();
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005089 case TargetInfo::SignedShort: return ShortTy;
5090 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5091 case TargetInfo::SignedInt: return IntTy;
5092 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5093 case TargetInfo::SignedLong: return LongTy;
5094 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5095 case TargetInfo::SignedLongLong: return LongLongTy;
5096 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5097 }
5098
David Blaikie83d382b2011-09-23 05:06:16 +00005099 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00005100}
Ted Kremenek77c51b22008-07-24 23:58:27 +00005101
5102//===----------------------------------------------------------------------===//
5103// Type Predicates.
5104//===----------------------------------------------------------------------===//
5105
Fariborz Jahanian96207692009-02-18 21:49:28 +00005106/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5107/// garbage collection attribute.
5108///
John McCall553d45a2011-01-12 00:34:59 +00005109Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregor79a91412011-09-13 17:21:33 +00005110 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00005111 return Qualifiers::GCNone;
5112
5113 assert(getLangOptions().ObjC1);
5114 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5115
5116 // Default behaviour under objective-C's gc is for ObjC pointers
5117 // (or pointers to them) be treated as though they were declared
5118 // as __strong.
5119 if (GCAttrs == Qualifiers::GCNone) {
5120 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5121 return Qualifiers::Strong;
5122 else if (Ty->isPointerType())
5123 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5124 } else {
5125 // It's not valid to set GC attributes on anything that isn't a
5126 // pointer.
5127#ifndef NDEBUG
5128 QualType CT = Ty->getCanonicalTypeInternal();
5129 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5130 CT = AT->getElementType();
5131 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5132#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00005133 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00005134 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00005135}
5136
Chris Lattner49af6a42008-04-07 06:51:04 +00005137//===----------------------------------------------------------------------===//
5138// Type Compatibility Testing
5139//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00005140
Mike Stump11289f42009-09-09 15:08:12 +00005141/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005142/// compatible.
5143static bool areCompatVectorTypes(const VectorType *LHS,
5144 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00005145 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00005146 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00005147 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00005148}
5149
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005150bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5151 QualType SecondVec) {
5152 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5153 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5154
5155 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5156 return true;
5157
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005158 // Treat Neon vector types and most AltiVec vector types as if they are the
5159 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005160 const VectorType *First = FirstVec->getAs<VectorType>();
5161 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005162 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005163 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00005164 First->getVectorKind() != VectorType::AltiVecPixel &&
5165 First->getVectorKind() != VectorType::AltiVecBool &&
5166 Second->getVectorKind() != VectorType::AltiVecPixel &&
5167 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005168 return true;
5169
5170 return false;
5171}
5172
Steve Naroff8e6aee52009-07-23 01:01:38 +00005173//===----------------------------------------------------------------------===//
5174// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5175//===----------------------------------------------------------------------===//
5176
5177/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5178/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00005179bool
5180ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5181 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00005182 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005183 return true;
5184 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5185 E = rProto->protocol_end(); PI != E; ++PI)
5186 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5187 return true;
5188 return false;
5189}
5190
Steve Naroff8e6aee52009-07-23 01:01:38 +00005191/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5192/// return true if lhs's protocols conform to rhs's protocol; false
5193/// otherwise.
5194bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5195 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5196 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5197 return false;
5198}
5199
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005200/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5201/// Class<p1, ...>.
5202bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5203 QualType rhs) {
5204 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5205 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5206 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5207
5208 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5209 E = lhsQID->qual_end(); I != E; ++I) {
5210 bool match = false;
5211 ObjCProtocolDecl *lhsProto = *I;
5212 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5213 E = rhsOPT->qual_end(); J != E; ++J) {
5214 ObjCProtocolDecl *rhsProto = *J;
5215 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5216 match = true;
5217 break;
5218 }
5219 }
5220 if (!match)
5221 return false;
5222 }
5223 return true;
5224}
5225
Steve Naroff8e6aee52009-07-23 01:01:38 +00005226/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5227/// ObjCQualifiedIDType.
5228bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5229 bool compare) {
5230 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00005231 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005232 lhs->isObjCIdType() || lhs->isObjCClassType())
5233 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005234 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00005235 rhs->isObjCIdType() || rhs->isObjCClassType())
5236 return true;
5237
5238 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00005239 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005240
Steve Naroff8e6aee52009-07-23 01:01:38 +00005241 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00005242
Steve Naroff8e6aee52009-07-23 01:01:38 +00005243 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00005244 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005245 // make sure we check the class hierarchy.
5246 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5247 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5248 E = lhsQID->qual_end(); I != E; ++I) {
5249 // when comparing an id<P> on lhs with a static type on rhs,
5250 // see if static class implements all of id's protocols, directly or
5251 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005252 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00005253 return false;
5254 }
5255 }
5256 // If there are no qualifiers and no interface, we have an 'id'.
5257 return true;
5258 }
Mike Stump11289f42009-09-09 15:08:12 +00005259 // Both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005260 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5261 E = lhsQID->qual_end(); I != E; ++I) {
5262 ObjCProtocolDecl *lhsProto = *I;
5263 bool match = false;
5264
5265 // when comparing an id<P> on lhs with a static type on rhs,
5266 // see if static class implements all of id's protocols, directly or
5267 // through its super class and categories.
5268 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5269 E = rhsOPT->qual_end(); J != E; ++J) {
5270 ObjCProtocolDecl *rhsProto = *J;
5271 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5272 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5273 match = true;
5274 break;
5275 }
5276 }
Mike Stump11289f42009-09-09 15:08:12 +00005277 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00005278 // make sure we check the class hierarchy.
5279 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5280 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5281 E = lhsQID->qual_end(); I != E; ++I) {
5282 // when comparing an id<P> on lhs with a static type on rhs,
5283 // see if static class implements all of id's protocols, directly or
5284 // through its super class and categories.
Fariborz Jahanian3f8917a2009-08-11 22:02:25 +00005285 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00005286 match = true;
5287 break;
5288 }
5289 }
5290 }
5291 if (!match)
5292 return false;
5293 }
Mike Stump11289f42009-09-09 15:08:12 +00005294
Steve Naroff8e6aee52009-07-23 01:01:38 +00005295 return true;
5296 }
Mike Stump11289f42009-09-09 15:08:12 +00005297
Steve Naroff8e6aee52009-07-23 01:01:38 +00005298 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5299 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5300
Mike Stump11289f42009-09-09 15:08:12 +00005301 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00005302 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005303 // If both the right and left sides have qualifiers.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005304 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5305 E = lhsOPT->qual_end(); I != E; ++I) {
5306 ObjCProtocolDecl *lhsProto = *I;
5307 bool match = false;
5308
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005309 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00005310 // see if static class implements all of id's protocols, directly or
5311 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005312 // First, lhs protocols in the qualifier list must be found, direct
5313 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff8e6aee52009-07-23 01:01:38 +00005314 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5315 E = rhsQID->qual_end(); J != E; ++J) {
5316 ObjCProtocolDecl *rhsProto = *J;
5317 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5318 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5319 match = true;
5320 break;
5321 }
5322 }
5323 if (!match)
5324 return false;
5325 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00005326
5327 // Static class's protocols, or its super class or category protocols
5328 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5329 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5330 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5331 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5332 // This is rather dubious but matches gcc's behavior. If lhs has
5333 // no type qualifier and its class has no static protocol(s)
5334 // assume that it is mismatch.
5335 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5336 return false;
5337 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5338 LHSInheritedProtocols.begin(),
5339 E = LHSInheritedProtocols.end(); I != E; ++I) {
5340 bool match = false;
5341 ObjCProtocolDecl *lhsProto = (*I);
5342 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5343 E = rhsQID->qual_end(); J != E; ++J) {
5344 ObjCProtocolDecl *rhsProto = *J;
5345 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5346 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5347 match = true;
5348 break;
5349 }
5350 }
5351 if (!match)
5352 return false;
5353 }
5354 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00005355 return true;
5356 }
5357 return false;
5358}
5359
Eli Friedman47f77112008-08-22 00:56:42 +00005360/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00005361/// compatible for assignment from RHS to LHS. This handles validation of any
5362/// protocol qualifiers on the LHS or RHS.
5363///
Steve Naroff7cae42b2009-07-10 23:34:53 +00005364bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5365 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00005366 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5367 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5368
Steve Naroff1329fa02009-07-15 18:40:39 +00005369 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00005370 if (LHS->isObjCUnqualifiedIdOrClass() ||
5371 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00005372 return true;
5373
John McCall8b07ec22010-05-15 11:32:37 +00005374 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump11289f42009-09-09 15:08:12 +00005375 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5376 QualType(RHSOPT,0),
Steve Naroff8e6aee52009-07-23 01:01:38 +00005377 false);
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00005378
5379 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5380 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5381 QualType(RHSOPT,0));
5382
John McCall8b07ec22010-05-15 11:32:37 +00005383 // If we have 2 user-defined types, fall into that path.
5384 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff8e6aee52009-07-23 01:01:38 +00005385 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005386
Steve Naroff8e6aee52009-07-23 01:01:38 +00005387 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005388}
5389
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005390/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00005391/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005392/// arguments in block literals. When passed as arguments, passing 'A*' where
5393/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5394/// not OK. For the return type, the opposite is not OK.
5395bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5396 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005397 const ObjCObjectPointerType *RHSOPT,
5398 bool BlockReturnType) {
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005399 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005400 return true;
5401
5402 if (LHSOPT->isObjCBuiltinType()) {
5403 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5404 }
5405
Fariborz Jahanian440a6832010-04-06 17:23:39 +00005406 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005407 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5408 QualType(RHSOPT,0),
5409 false);
5410
5411 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5412 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5413 if (LHS && RHS) { // We have 2 user-defined types.
5414 if (LHS != RHS) {
5415 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005416 return BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005417 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005418 return !BlockReturnType;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005419 }
5420 else
5421 return true;
5422 }
5423 return false;
5424}
5425
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005426/// getIntersectionOfProtocols - This routine finds the intersection of set
5427/// of protocols inherited from two distinct objective-c pointer objects.
5428/// It is used to build composite qualifier list of the composite type of
5429/// the conditional expression involving two objective-c pointer objects.
5430static
5431void getIntersectionOfProtocols(ASTContext &Context,
5432 const ObjCObjectPointerType *LHSOPT,
5433 const ObjCObjectPointerType *RHSOPT,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005434 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005435
John McCall8b07ec22010-05-15 11:32:37 +00005436 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5437 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5438 assert(LHS->getInterface() && "LHS must have an interface base");
5439 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005440
5441 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5442 unsigned LHSNumProtocols = LHS->getNumProtocols();
5443 if (LHSNumProtocols > 0)
5444 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5445 else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005446 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005447 Context.CollectInheritedProtocols(LHS->getInterface(),
5448 LHSInheritedProtocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005449 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5450 LHSInheritedProtocols.end());
5451 }
5452
5453 unsigned RHSNumProtocols = RHS->getNumProtocols();
5454 if (RHSNumProtocols > 0) {
Dan Gohman145f3f12010-04-19 16:39:44 +00005455 ObjCProtocolDecl **RHSProtocols =
5456 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005457 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5458 if (InheritedProtocolSet.count(RHSProtocols[i]))
5459 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00005460 } else {
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005461 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCall8b07ec22010-05-15 11:32:37 +00005462 Context.CollectInheritedProtocols(RHS->getInterface(),
5463 RHSInheritedProtocols);
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00005464 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5465 RHSInheritedProtocols.begin(),
5466 E = RHSInheritedProtocols.end(); I != E; ++I)
5467 if (InheritedProtocolSet.count((*I)))
5468 IntersectionOfProtocols.push_back((*I));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005469 }
5470}
5471
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005472/// areCommonBaseCompatible - Returns common base class of the two classes if
5473/// one found. Note that this is O'2 algorithm. But it will be called as the
5474/// last type comparison in a ?-exp of ObjC pointer types before a
5475/// warning is issued. So, its invokation is extremely rare.
5476QualType ASTContext::areCommonBaseCompatible(
John McCall8b07ec22010-05-15 11:32:37 +00005477 const ObjCObjectPointerType *Lptr,
5478 const ObjCObjectPointerType *Rptr) {
5479 const ObjCObjectType *LHS = Lptr->getObjectType();
5480 const ObjCObjectType *RHS = Rptr->getObjectType();
5481 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5482 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor0b144e12011-12-15 00:29:59 +00005483 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005484 return QualType();
5485
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005486 do {
John McCall8b07ec22010-05-15 11:32:37 +00005487 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005488 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005489 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCall8b07ec22010-05-15 11:32:37 +00005490 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5491
5492 QualType Result = QualType(LHS, 0);
5493 if (!Protocols.empty())
5494 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5495 Result = getObjCObjectPointerType(Result);
5496 return Result;
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00005497 }
Fariborz Jahanianb1071432011-04-18 21:16:59 +00005498 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00005499
5500 return QualType();
5501}
5502
John McCall8b07ec22010-05-15 11:32:37 +00005503bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5504 const ObjCObjectType *RHS) {
5505 assert(LHS->getInterface() && "LHS is not an interface type");
5506 assert(RHS->getInterface() && "RHS is not an interface type");
5507
Chris Lattner49af6a42008-04-07 06:51:04 +00005508 // Verify that the base decls are compatible: the RHS must be a subclass of
5509 // the LHS.
John McCall8b07ec22010-05-15 11:32:37 +00005510 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner49af6a42008-04-07 06:51:04 +00005511 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005512
Chris Lattner49af6a42008-04-07 06:51:04 +00005513 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5514 // protocol qualified at all, then we are good.
Steve Naroffc277ad12009-07-18 15:33:26 +00005515 if (LHS->getNumProtocols() == 0)
Chris Lattner49af6a42008-04-07 06:51:04 +00005516 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005517
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005518 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5519 // more detailed analysis is required.
5520 if (RHS->getNumProtocols() == 0) {
5521 // OK, if LHS is a superclass of RHS *and*
5522 // this superclass is assignment compatible with LHS.
5523 // false otherwise.
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005524 bool IsSuperClass =
5525 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5526 if (IsSuperClass) {
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005527 // OK if conversion of LHS to SuperClass results in narrowing of types
5528 // ; i.e., SuperClass may implement at least one of the protocols
5529 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5530 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5531 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian240400b2011-04-12 16:34:14 +00005532 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanian4806ff82011-04-08 18:25:29 +00005533 // If super class has no protocols, it is not a match.
5534 if (SuperClassInheritedProtocols.empty())
5535 return false;
5536
5537 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5538 LHSPE = LHS->qual_end();
5539 LHSPI != LHSPE; LHSPI++) {
5540 bool SuperImplementsProtocol = false;
5541 ObjCProtocolDecl *LHSProto = (*LHSPI);
5542
5543 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5544 SuperClassInheritedProtocols.begin(),
5545 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5546 ObjCProtocolDecl *SuperClassProto = (*I);
5547 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5548 SuperImplementsProtocol = true;
5549 break;
5550 }
5551 }
5552 if (!SuperImplementsProtocol)
5553 return false;
5554 }
5555 return true;
5556 }
5557 return false;
5558 }
Mike Stump11289f42009-09-09 15:08:12 +00005559
John McCall8b07ec22010-05-15 11:32:37 +00005560 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5561 LHSPE = LHS->qual_end();
Steve Naroff114aecb2009-03-01 16:12:44 +00005562 LHSPI != LHSPE; LHSPI++) {
5563 bool RHSImplementsProtocol = false;
5564
5565 // If the RHS doesn't implement the protocol on the left, the types
5566 // are incompatible.
John McCall8b07ec22010-05-15 11:32:37 +00005567 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5568 RHSPE = RHS->qual_end();
Steve Narofffac5bc92009-07-16 16:21:02 +00005569 RHSPI != RHSPE; RHSPI++) {
5570 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff114aecb2009-03-01 16:12:44 +00005571 RHSImplementsProtocol = true;
Steve Narofffac5bc92009-07-16 16:21:02 +00005572 break;
5573 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005574 }
5575 // FIXME: For better diagnostics, consider passing back the protocol name.
5576 if (!RHSImplementsProtocol)
5577 return false;
Chris Lattner49af6a42008-04-07 06:51:04 +00005578 }
Steve Naroff114aecb2009-03-01 16:12:44 +00005579 // The RHS implements all protocols listed on the LHS.
5580 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00005581}
5582
Steve Naroffb7605152009-02-12 17:52:19 +00005583bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5584 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00005585 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5586 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00005587
Steve Naroff7cae42b2009-07-10 23:34:53 +00005588 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00005589 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005590
5591 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5592 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00005593}
5594
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005595bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5596 return canAssignObjCInterfaces(
5597 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5598 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5599}
5600
Mike Stump11289f42009-09-09 15:08:12 +00005601/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00005602/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00005603/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00005604/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005605bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5606 bool CompareUnqualified) {
Douglas Gregor21e771e2010-02-03 21:02:30 +00005607 if (getLangOptions().CPlusPlus)
5608 return hasSameType(LHS, RHS);
5609
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005610 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00005611}
5612
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005613bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00005614 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00005615}
5616
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005617bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5618 return !mergeTypes(LHS, RHS, true).isNull();
5619}
5620
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005621/// mergeTransparentUnionType - if T is a transparent union type and a member
5622/// of T is compatible with SubType, return the merged type, else return
5623/// QualType()
5624QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5625 bool OfBlockPointer,
5626 bool Unqualified) {
5627 if (const RecordType *UT = T->getAsUnionType()) {
5628 RecordDecl *UD = UT->getDecl();
5629 if (UD->hasAttr<TransparentUnionAttr>()) {
5630 for (RecordDecl::field_iterator it = UD->field_begin(),
5631 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbourne19b961d2010-12-02 21:00:06 +00005632 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005633 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5634 if (!MT.isNull())
5635 return MT;
5636 }
5637 }
5638 }
5639
5640 return QualType();
5641}
5642
5643/// mergeFunctionArgumentTypes - merge two types which appear as function
5644/// argument types
5645QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5646 bool OfBlockPointer,
5647 bool Unqualified) {
5648 // GNU extension: two types are compatible if they appear as a function
5649 // argument, one of the types is a transparent union type and the other
5650 // type is compatible with a union member
5651 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5652 Unqualified);
5653 if (!lmerge.isNull())
5654 return lmerge;
5655
5656 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5657 Unqualified);
5658 if (!rmerge.isNull())
5659 return rmerge;
5660
5661 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5662}
5663
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005664QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005665 bool OfBlockPointer,
5666 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00005667 const FunctionType *lbase = lhs->getAs<FunctionType>();
5668 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005669 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5670 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00005671 bool allLTypes = true;
5672 bool allRTypes = true;
5673
5674 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005675 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00005676 if (OfBlockPointer) {
5677 QualType RHS = rbase->getResultType();
5678 QualType LHS = lbase->getResultType();
5679 bool UnqualifiedResult = Unqualified;
5680 if (!UnqualifiedResult)
5681 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005682 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00005683 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005684 else
John McCall8c6b56f2010-12-15 01:06:38 +00005685 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5686 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005687 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005688
5689 if (Unqualified)
5690 retType = retType.getUnqualifiedType();
5691
5692 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5693 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5694 if (Unqualified) {
5695 LRetType = LRetType.getUnqualifiedType();
5696 RRetType = RRetType.getUnqualifiedType();
5697 }
5698
5699 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005700 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005701 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00005702 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005703
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00005704 // FIXME: double check this
5705 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5706 // rbase->getRegParmAttr() != 0 &&
5707 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00005708 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5709 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00005710
Douglas Gregor8c940862010-01-18 17:14:39 +00005711 // Compatible functions must have compatible calling conventions
John McCall8c6b56f2010-12-15 01:06:38 +00005712 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregor8c940862010-01-18 17:14:39 +00005713 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005714
John McCall8c6b56f2010-12-15 01:06:38 +00005715 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00005716 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5717 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00005718 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5719 return QualType();
5720
John McCall31168b02011-06-15 23:02:42 +00005721 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5722 return QualType();
5723
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005724 // functypes which return are preferred over those that do not.
5725 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5726 allLTypes = false;
5727 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5728 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00005729 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5730 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00005731
John McCall31168b02011-06-15 23:02:42 +00005732 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00005733
Eli Friedman47f77112008-08-22 00:56:42 +00005734 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005735 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5736 "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005737 unsigned lproto_nargs = lproto->getNumArgs();
5738 unsigned rproto_nargs = rproto->getNumArgs();
5739
5740 // Compatible functions must have the same number of arguments
5741 if (lproto_nargs != rproto_nargs)
5742 return QualType();
5743
5744 // Variadic and non-variadic functions aren't compatible
5745 if (lproto->isVariadic() != rproto->isVariadic())
5746 return QualType();
5747
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00005748 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5749 return QualType();
5750
Fariborz Jahanian97676972011-09-28 21:52:05 +00005751 if (LangOpts.ObjCAutoRefCount &&
5752 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5753 return QualType();
5754
Eli Friedman47f77112008-08-22 00:56:42 +00005755 // Check argument compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005756 SmallVector<QualType, 10> types;
Eli Friedman47f77112008-08-22 00:56:42 +00005757 for (unsigned i = 0; i < lproto_nargs; i++) {
5758 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5759 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00005760 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5761 OfBlockPointer,
5762 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005763 if (argtype.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005764
5765 if (Unqualified)
5766 argtype = argtype.getUnqualifiedType();
5767
Eli Friedman47f77112008-08-22 00:56:42 +00005768 types.push_back(argtype);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005769 if (Unqualified) {
5770 largtype = largtype.getUnqualifiedType();
5771 rargtype = rargtype.getUnqualifiedType();
5772 }
5773
Chris Lattner465fa322008-10-05 17:34:18 +00005774 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5775 allLTypes = false;
5776 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5777 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00005778 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00005779
Eli Friedman47f77112008-08-22 00:56:42 +00005780 if (allLTypes) return lhs;
5781 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005782
5783 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5784 EPI.ExtInfo = einfo;
5785 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005786 }
5787
5788 if (lproto) allRTypes = false;
5789 if (rproto) allLTypes = false;
5790
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005791 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00005792 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00005793 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00005794 if (proto->isVariadic()) return QualType();
5795 // Check that the types are compatible with the types that
5796 // would result from default argument promotions (C99 6.7.5.3p15).
5797 // The only types actually affected are promotable integer
5798 // types and floats, which would be passed as a different
5799 // type depending on whether the prototype is visible.
5800 unsigned proto_nargs = proto->getNumArgs();
5801 for (unsigned i = 0; i < proto_nargs; ++i) {
5802 QualType argTy = proto->getArgType(i);
Douglas Gregor2973d402010-02-03 19:27:29 +00005803
5804 // Look at the promotion type of enum types, since that is the type used
5805 // to pass enum values.
5806 if (const EnumType *Enum = argTy->getAs<EnumType>())
5807 argTy = Enum->getDecl()->getPromotionType();
5808
Eli Friedman47f77112008-08-22 00:56:42 +00005809 if (argTy->isPromotableIntegerType() ||
5810 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5811 return QualType();
5812 }
5813
5814 if (allLTypes) return lhs;
5815 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00005816
5817 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5818 EPI.ExtInfo = einfo;
Eli Friedman47f77112008-08-22 00:56:42 +00005819 return getFunctionType(retType, proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005820 proto->getNumArgs(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00005821 }
5822
5823 if (allLTypes) return lhs;
5824 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00005825 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00005826}
5827
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00005828QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005829 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00005830 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00005831 // C++ [expr]: If an expression initially has the type "reference to T", the
5832 // type is adjusted to "T" prior to any further analysis, the expression
5833 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005834 // expression is an lvalue unless the reference is an rvalue reference and
5835 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00005836 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5837 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005838
5839 if (Unqualified) {
5840 LHS = LHS.getUnqualifiedType();
5841 RHS = RHS.getUnqualifiedType();
5842 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00005843
Eli Friedman47f77112008-08-22 00:56:42 +00005844 QualType LHSCan = getCanonicalType(LHS),
5845 RHSCan = getCanonicalType(RHS);
5846
5847 // If two types are identical, they are compatible.
5848 if (LHSCan == RHSCan)
5849 return LHS;
5850
John McCall8ccfcb52009-09-24 19:53:00 +00005851 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005852 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5853 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00005854 if (LQuals != RQuals) {
5855 // If any of these qualifiers are different, we have a type
5856 // mismatch.
5857 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00005858 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5859 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00005860 return QualType();
5861
5862 // Exactly one GC qualifier difference is allowed: __strong is
5863 // okay if the other type has no GC qualifier but is an Objective
5864 // C object pointer (i.e. implicitly strong by default). We fix
5865 // this by pretending that the unqualified type was actually
5866 // qualified __strong.
5867 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5868 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5869 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5870
5871 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5872 return QualType();
5873
5874 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5875 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5876 }
5877 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5878 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5879 }
Eli Friedman47f77112008-08-22 00:56:42 +00005880 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00005881 }
5882
5883 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00005884
Eli Friedmandcca6332009-06-01 01:22:52 +00005885 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5886 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00005887
Chris Lattnerfd652912008-01-14 05:45:46 +00005888 // We want to consider the two function types to be the same for these
5889 // comparisons, just force one to the other.
5890 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5891 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00005892
5893 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00005894 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5895 LHSClass = Type::ConstantArray;
5896 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5897 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00005898
John McCall8b07ec22010-05-15 11:32:37 +00005899 // ObjCInterfaces are just specialized ObjCObjects.
5900 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5901 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5902
Nate Begemance4d7fc2008-04-18 23:10:10 +00005903 // Canonicalize ExtVector -> Vector.
5904 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5905 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00005906
Chris Lattner95554662008-04-07 05:43:21 +00005907 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005908 if (LHSClass != RHSClass) {
Chris Lattnerfd652912008-01-14 05:45:46 +00005909 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump11289f42009-09-09 15:08:12 +00005910 // a signed integer type, or an unsigned integer type.
John McCall56774992009-12-09 09:09:27 +00005911 // Compatibility is based on the underlying type, not the promotion
5912 // type.
John McCall9dd450b2009-09-21 23:43:11 +00005913 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00005914 QualType TINT = ETy->getDecl()->getIntegerType();
5915 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00005916 return RHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005917 }
John McCall9dd450b2009-09-21 23:43:11 +00005918 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Fariborz Jahanianadfe9052012-02-06 19:06:20 +00005919 QualType TINT = ETy->getDecl()->getIntegerType();
5920 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
Eli Friedman47f77112008-08-22 00:56:42 +00005921 return LHS;
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00005922 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00005923 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00005924 if (OfBlockPointer && !BlockReturnType) {
5925 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5926 return LHS;
5927 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5928 return RHS;
5929 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00005930
Eli Friedman47f77112008-08-22 00:56:42 +00005931 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00005932 }
Eli Friedman47f77112008-08-22 00:56:42 +00005933
Steve Naroffc6edcbd2008-01-09 22:43:08 +00005934 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00005935 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005936#define TYPE(Class, Base)
5937#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00005938#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005939#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5940#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5941#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00005942 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005943
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005944 case Type::LValueReference:
5945 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005946 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00005947 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005948
John McCall8b07ec22010-05-15 11:32:37 +00005949 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005950 case Type::IncompleteArray:
5951 case Type::VariableArray:
5952 case Type::FunctionProto:
5953 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00005954 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005955
Chris Lattnerfd652912008-01-14 05:45:46 +00005956 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00005957 {
5958 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005959 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5960 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005961 if (Unqualified) {
5962 LHSPointee = LHSPointee.getUnqualifiedType();
5963 RHSPointee = RHSPointee.getUnqualifiedType();
5964 }
5965 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5966 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00005967 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00005968 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005969 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00005970 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00005971 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00005972 return getPointerType(ResultType);
5973 }
Steve Naroff68e167d2008-12-10 17:49:55 +00005974 case Type::BlockPointer:
5975 {
5976 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005977 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5978 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00005979 if (Unqualified) {
5980 LHSPointee = LHSPointee.getUnqualifiedType();
5981 RHSPointee = RHSPointee.getUnqualifiedType();
5982 }
5983 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5984 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00005985 if (ResultType.isNull()) return QualType();
5986 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5987 return LHS;
5988 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5989 return RHS;
5990 return getBlockPointerType(ResultType);
5991 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00005992 case Type::Atomic:
5993 {
5994 // Merge two pointer types, while trying to preserve typedef info
5995 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
5996 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
5997 if (Unqualified) {
5998 LHSValue = LHSValue.getUnqualifiedType();
5999 RHSValue = RHSValue.getUnqualifiedType();
6000 }
6001 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6002 Unqualified);
6003 if (ResultType.isNull()) return QualType();
6004 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6005 return LHS;
6006 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6007 return RHS;
6008 return getAtomicType(ResultType);
6009 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006010 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00006011 {
6012 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6013 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6014 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6015 return QualType();
6016
6017 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6018 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006019 if (Unqualified) {
6020 LHSElem = LHSElem.getUnqualifiedType();
6021 RHSElem = RHSElem.getUnqualifiedType();
6022 }
6023
6024 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00006025 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00006026 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6027 return LHS;
6028 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6029 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00006030 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6031 ArrayType::ArraySizeModifier(), 0);
6032 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6033 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006034 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6035 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00006036 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6037 return LHS;
6038 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6039 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00006040 if (LVAT) {
6041 // FIXME: This isn't correct! But tricky to implement because
6042 // the array's size has to be the size of LHS, but the type
6043 // has to be different.
6044 return LHS;
6045 }
6046 if (RVAT) {
6047 // FIXME: This isn't correct! But tricky to implement because
6048 // the array's size has to be the size of RHS, but the type
6049 // has to be different.
6050 return RHS;
6051 }
Eli Friedman3e62c212008-08-22 01:48:21 +00006052 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6053 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00006054 return getIncompleteArrayType(ResultType,
6055 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00006056 }
Chris Lattnerfd652912008-01-14 05:45:46 +00006057 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00006058 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006059 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006060 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00006061 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00006062 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006063 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00006064 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00006065 case Type::Complex:
6066 // Distinct complex types are incompatible.
6067 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00006068 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00006069 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00006070 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6071 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00006072 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00006073 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00006074 case Type::ObjCObject: {
6075 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00006076 // FIXME: This should be type compatibility, e.g. whether
6077 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00006078 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6079 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6080 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00006081 return LHS;
6082
Eli Friedman47f77112008-08-22 00:56:42 +00006083 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00006084 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00006085 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006086 if (OfBlockPointer) {
6087 if (canAssignObjCInterfacesInBlockPointer(
6088 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00006089 RHS->getAs<ObjCObjectPointerType>(),
6090 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00006091 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00006092 return QualType();
6093 }
John McCall9dd450b2009-09-21 23:43:11 +00006094 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6095 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00006096 return LHS;
6097
Steve Naroffc68cfcf2008-12-10 22:14:21 +00006098 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00006099 }
Steve Naroff32e44c02007-10-15 20:41:53 +00006100 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006101
David Blaikie8a40f702012-01-17 06:56:22 +00006102 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00006103}
Ted Kremenekfc581a92007-10-31 17:10:13 +00006104
Fariborz Jahanian97676972011-09-28 21:52:05 +00006105bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6106 const FunctionProtoType *FromFunctionType,
6107 const FunctionProtoType *ToFunctionType) {
6108 if (FromFunctionType->hasAnyConsumedArgs() !=
6109 ToFunctionType->hasAnyConsumedArgs())
6110 return false;
6111 FunctionProtoType::ExtProtoInfo FromEPI =
6112 FromFunctionType->getExtProtoInfo();
6113 FunctionProtoType::ExtProtoInfo ToEPI =
6114 ToFunctionType->getExtProtoInfo();
6115 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6116 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6117 ArgIdx != NumArgs; ++ArgIdx) {
6118 if (FromEPI.ConsumedArguments[ArgIdx] !=
6119 ToEPI.ConsumedArguments[ArgIdx])
6120 return false;
6121 }
6122 return true;
6123}
6124
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006125/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6126/// 'RHS' attributes and returns the merged version; including for function
6127/// return types.
6128QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6129 QualType LHSCan = getCanonicalType(LHS),
6130 RHSCan = getCanonicalType(RHS);
6131 // If two types are identical, they are compatible.
6132 if (LHSCan == RHSCan)
6133 return LHS;
6134 if (RHSCan->isFunctionType()) {
6135 if (!LHSCan->isFunctionType())
6136 return QualType();
6137 QualType OldReturnType =
6138 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6139 QualType NewReturnType =
6140 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6141 QualType ResReturnType =
6142 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6143 if (ResReturnType.isNull())
6144 return QualType();
6145 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6146 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6147 // In either case, use OldReturnType to build the new function type.
6148 const FunctionType *F = LHS->getAs<FunctionType>();
6149 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00006150 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6151 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006152 QualType ResultType
6153 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00006154 FPT->getNumArgs(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00006155 return ResultType;
6156 }
6157 }
6158 return QualType();
6159 }
6160
6161 // If the qualifiers are different, the types can still be merged.
6162 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6163 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6164 if (LQuals != RQuals) {
6165 // If any of these qualifiers are different, we have a type mismatch.
6166 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6167 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6168 return QualType();
6169
6170 // Exactly one GC qualifier difference is allowed: __strong is
6171 // okay if the other type has no GC qualifier but is an Objective
6172 // C object pointer (i.e. implicitly strong by default). We fix
6173 // this by pretending that the unqualified type was actually
6174 // qualified __strong.
6175 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6176 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6177 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6178
6179 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6180 return QualType();
6181
6182 if (GC_L == Qualifiers::Strong)
6183 return LHS;
6184 if (GC_R == Qualifiers::Strong)
6185 return RHS;
6186 return QualType();
6187 }
6188
6189 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6190 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6191 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6192 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6193 if (ResQT == LHSBaseQT)
6194 return LHS;
6195 if (ResQT == RHSBaseQT)
6196 return RHS;
6197 }
6198 return QualType();
6199}
6200
Chris Lattner4ba0cef2008-04-07 07:01:58 +00006201//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006202// Integer Predicates
6203//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00006204
Jay Foad39c79802011-01-12 09:06:06 +00006205unsigned ASTContext::getIntWidth(QualType T) const {
John McCall424cec92011-01-19 06:33:43 +00006206 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedmanee275c82009-12-10 22:29:29 +00006207 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00006208 if (T->isBooleanType())
6209 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00006210 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006211 return (unsigned)getTypeSize(T);
6212}
6213
6214QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006215 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00006216
6217 // Turn <4 x signed int> -> <4 x unsigned int>
6218 if (const VectorType *VTy = T->getAs<VectorType>())
6219 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00006220 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00006221
6222 // For enums, we return the unsigned version of the base type.
6223 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006224 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00006225
6226 const BuiltinType *BTy = T->getAs<BuiltinType>();
6227 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006228 switch (BTy->getKind()) {
6229 case BuiltinType::Char_S:
6230 case BuiltinType::SChar:
6231 return UnsignedCharTy;
6232 case BuiltinType::Short:
6233 return UnsignedShortTy;
6234 case BuiltinType::Int:
6235 return UnsignedIntTy;
6236 case BuiltinType::Long:
6237 return UnsignedLongTy;
6238 case BuiltinType::LongLong:
6239 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00006240 case BuiltinType::Int128:
6241 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006242 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006243 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00006244 }
6245}
6246
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006247ASTMutationListener::~ASTMutationListener() { }
6248
Chris Lattnerecd79c62009-06-14 00:45:47 +00006249
6250//===----------------------------------------------------------------------===//
6251// Builtin Type Computation
6252//===----------------------------------------------------------------------===//
6253
6254/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00006255/// pointer over the consumed characters. This returns the resultant type. If
6256/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6257/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6258/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006259///
6260/// RequiresICE is filled in on return to indicate whether the value is required
6261/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00006262static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00006263 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006264 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00006265 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00006266 // Modifiers.
6267 int HowLong = 0;
6268 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006269 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00006270
Chris Lattnerdc226c22010-10-01 22:42:38 +00006271 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00006272 bool Done = false;
6273 while (!Done) {
6274 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00006275 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00006276 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006277 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00006278 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006279 case 'S':
6280 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6281 assert(!Signed && "Can't use 'S' modifier multiple times!");
6282 Signed = true;
6283 break;
6284 case 'U':
6285 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6286 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6287 Unsigned = true;
6288 break;
6289 case 'L':
6290 assert(HowLong <= 2 && "Can't have LLLL modifier");
6291 ++HowLong;
6292 break;
6293 }
6294 }
6295
6296 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00006297
Chris Lattnerecd79c62009-06-14 00:45:47 +00006298 // Read the base type.
6299 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00006300 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006301 case 'v':
6302 assert(HowLong == 0 && !Signed && !Unsigned &&
6303 "Bad modifiers used with 'v'!");
6304 Type = Context.VoidTy;
6305 break;
6306 case 'f':
6307 assert(HowLong == 0 && !Signed && !Unsigned &&
6308 "Bad modifiers used with 'f'!");
6309 Type = Context.FloatTy;
6310 break;
6311 case 'd':
6312 assert(HowLong < 2 && !Signed && !Unsigned &&
6313 "Bad modifiers used with 'd'!");
6314 if (HowLong)
6315 Type = Context.LongDoubleTy;
6316 else
6317 Type = Context.DoubleTy;
6318 break;
6319 case 's':
6320 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6321 if (Unsigned)
6322 Type = Context.UnsignedShortTy;
6323 else
6324 Type = Context.ShortTy;
6325 break;
6326 case 'i':
6327 if (HowLong == 3)
6328 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6329 else if (HowLong == 2)
6330 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6331 else if (HowLong == 1)
6332 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6333 else
6334 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6335 break;
6336 case 'c':
6337 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6338 if (Signed)
6339 Type = Context.SignedCharTy;
6340 else if (Unsigned)
6341 Type = Context.UnsignedCharTy;
6342 else
6343 Type = Context.CharTy;
6344 break;
6345 case 'b': // boolean
6346 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6347 Type = Context.BoolTy;
6348 break;
6349 case 'z': // size_t.
6350 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6351 Type = Context.getSizeType();
6352 break;
6353 case 'F':
6354 Type = Context.getCFConstantStringType();
6355 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00006356 case 'G':
6357 Type = Context.getObjCIdType();
6358 break;
6359 case 'H':
6360 Type = Context.getObjCSelType();
6361 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006362 case 'a':
6363 Type = Context.getBuiltinVaListType();
6364 assert(!Type.isNull() && "builtin va list type not initialized!");
6365 break;
6366 case 'A':
6367 // This is a "reference" to a va_list; however, what exactly
6368 // this means depends on how va_list is defined. There are two
6369 // different kinds of va_list: ones passed by value, and ones
6370 // passed by reference. An example of a by-value va_list is
6371 // x86, where va_list is a char*. An example of by-ref va_list
6372 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6373 // we want this argument to be a char*&; for x86-64, we want
6374 // it to be a __va_list_tag*.
6375 Type = Context.getBuiltinVaListType();
6376 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006377 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00006378 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006379 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00006380 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006381 break;
6382 case 'V': {
6383 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006384 unsigned NumElements = strtoul(Str, &End, 10);
6385 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00006386 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00006387
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006388 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6389 RequiresICE, false);
6390 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00006391
6392 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00006393 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00006394 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006395 break;
6396 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006397 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006398 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6399 false);
6400 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00006401 Type = Context.getComplexType(ElementType);
6402 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00006403 }
6404 case 'Y' : {
6405 Type = Context.getPointerDiffType();
6406 break;
6407 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00006408 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00006409 Type = Context.getFILEType();
6410 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006411 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006412 return QualType();
6413 }
Mike Stump2adb4da2009-07-28 23:47:15 +00006414 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00006415 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00006416 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00006417 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00006418 else
6419 Type = Context.getjmp_bufType();
6420
Mike Stump2adb4da2009-07-28 23:47:15 +00006421 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00006422 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00006423 return QualType();
6424 }
6425 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00006426 case 'K':
6427 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6428 Type = Context.getucontext_tType();
6429
6430 if (Type.isNull()) {
6431 Error = ASTContext::GE_Missing_ucontext;
6432 return QualType();
6433 }
6434 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00006435 }
Mike Stump11289f42009-09-09 15:08:12 +00006436
Chris Lattnerdc226c22010-10-01 22:42:38 +00006437 // If there are modifiers and if we're allowed to parse them, go for it.
6438 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006439 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00006440 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006441 default: Done = true; --Str; break;
6442 case '*':
6443 case '&': {
6444 // Both pointers and references can have their pointee types
6445 // qualified with an address space.
6446 char *End;
6447 unsigned AddrSpace = strtoul(Str, &End, 10);
6448 if (End != Str && AddrSpace != 0) {
6449 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6450 Str = End;
6451 }
6452 if (c == '*')
6453 Type = Context.getPointerType(Type);
6454 else
6455 Type = Context.getLValueReferenceType(Type);
6456 break;
6457 }
6458 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6459 case 'C':
6460 Type = Type.withConst();
6461 break;
6462 case 'D':
6463 Type = Context.getVolatileType(Type);
6464 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00006465 case 'R':
6466 Type = Type.withRestrict();
6467 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006468 }
6469 }
Chris Lattner84733392010-10-01 07:13:18 +00006470
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006471 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00006472 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00006473
Chris Lattnerecd79c62009-06-14 00:45:47 +00006474 return Type;
6475}
6476
6477/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00006478QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006479 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00006480 unsigned *IntegerConstantArgs) const {
Chris Lattnerdc226c22010-10-01 22:42:38 +00006481 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00006482
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006483 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00006484
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006485 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00006486 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006487 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6488 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006489 if (Error != GE_None)
6490 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006491
6492 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6493
Chris Lattnerecd79c62009-06-14 00:45:47 +00006494 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006495 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006496 if (Error != GE_None)
6497 return QualType();
6498
Chris Lattnerbd6e6932010-10-01 22:53:11 +00006499 // If this argument is required to be an IntegerConstantExpression and the
6500 // caller cares, fill in the bitmask we return.
6501 if (RequiresICE && IntegerConstantArgs)
6502 *IntegerConstantArgs |= 1 << ArgTypes.size();
6503
Chris Lattnerecd79c62009-06-14 00:45:47 +00006504 // Do array -> pointer decay. The builtin should use the decayed type.
6505 if (Ty->isArrayType())
6506 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00006507
Chris Lattnerecd79c62009-06-14 00:45:47 +00006508 ArgTypes.push_back(Ty);
6509 }
6510
6511 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6512 "'.' should only occur at end of builtin type list!");
6513
John McCall991eb4b2010-12-21 00:44:39 +00006514 FunctionType::ExtInfo EI;
6515 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6516
6517 bool Variadic = (TypeStr[0] == '.');
6518
6519 // We really shouldn't be making a no-proto type here, especially in C++.
6520 if (ArgTypes.empty() && Variadic)
6521 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00006522
John McCalldb40c7f2010-12-14 08:05:40 +00006523 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00006524 EPI.ExtInfo = EI;
6525 EPI.Variadic = Variadic;
John McCalldb40c7f2010-12-14 08:05:40 +00006526
6527 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00006528}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00006529
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006530GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6531 GVALinkage External = GVA_StrongExternal;
6532
6533 Linkage L = FD->getLinkage();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006534 switch (L) {
6535 case NoLinkage:
6536 case InternalLinkage:
6537 case UniqueExternalLinkage:
6538 return GVA_Internal;
6539
6540 case ExternalLinkage:
6541 switch (FD->getTemplateSpecializationKind()) {
6542 case TSK_Undeclared:
6543 case TSK_ExplicitSpecialization:
6544 External = GVA_StrongExternal;
6545 break;
6546
6547 case TSK_ExplicitInstantiationDefinition:
6548 return GVA_ExplicitTemplateInstantiation;
6549
6550 case TSK_ExplicitInstantiationDeclaration:
6551 case TSK_ImplicitInstantiation:
6552 External = GVA_TemplateInstantiation;
6553 break;
6554 }
6555 }
6556
6557 if (!FD->isInlined())
6558 return External;
6559
6560 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6561 // GNU or C99 inline semantics. Determine whether this symbol should be
6562 // externally visible.
6563 if (FD->isInlineDefinitionExternallyVisible())
6564 return External;
6565
6566 // C99 inline semantics, where the symbol is not externally visible.
6567 return GVA_C99Inline;
6568 }
6569
6570 // C++0x [temp.explicit]p9:
6571 // [ Note: The intent is that an inline function that is the subject of
6572 // an explicit instantiation declaration will still be implicitly
6573 // instantiated when used so that the body can be considered for
6574 // inlining, but that no out-of-line copy of the inline function would be
6575 // generated in the translation unit. -- end note ]
6576 if (FD->getTemplateSpecializationKind()
6577 == TSK_ExplicitInstantiationDeclaration)
6578 return GVA_C99Inline;
6579
6580 return GVA_CXXInline;
6581}
6582
6583GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6584 // If this is a static data member, compute the kind of template
6585 // specialization. Otherwise, this variable is not part of a
6586 // template.
6587 TemplateSpecializationKind TSK = TSK_Undeclared;
6588 if (VD->isStaticDataMember())
6589 TSK = VD->getTemplateSpecializationKind();
6590
6591 Linkage L = VD->getLinkage();
6592 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6593 VD->getType()->getLinkage() == UniqueExternalLinkage)
6594 L = UniqueExternalLinkage;
6595
6596 switch (L) {
6597 case NoLinkage:
6598 case InternalLinkage:
6599 case UniqueExternalLinkage:
6600 return GVA_Internal;
6601
6602 case ExternalLinkage:
6603 switch (TSK) {
6604 case TSK_Undeclared:
6605 case TSK_ExplicitSpecialization:
6606 return GVA_StrongExternal;
6607
6608 case TSK_ExplicitInstantiationDeclaration:
6609 llvm_unreachable("Variable should not be instantiated");
6610 // Fall through to treat this like any other instantiation.
6611
6612 case TSK_ExplicitInstantiationDefinition:
6613 return GVA_ExplicitTemplateInstantiation;
6614
6615 case TSK_ImplicitInstantiation:
6616 return GVA_TemplateInstantiation;
6617 }
6618 }
6619
David Blaikie8a40f702012-01-17 06:56:22 +00006620 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006621}
6622
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00006623bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006624 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6625 if (!VD->isFileVarDecl())
6626 return false;
Argyrios Kyrtzidisa98e8612011-09-13 21:35:00 +00006627 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006628 return false;
6629
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006630 // Weak references don't produce any output by themselves.
6631 if (D->hasAttr<WeakRefAttr>())
6632 return false;
6633
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006634 // Aliases and used decls are required.
6635 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6636 return true;
6637
6638 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6639 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00006640 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00006641 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006642
6643 // Constructors and destructors are required.
6644 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6645 return true;
6646
6647 // The key function for a class is required.
6648 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6649 const CXXRecordDecl *RD = MD->getParent();
6650 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6651 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6652 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6653 return true;
6654 }
6655 }
6656
6657 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6658
6659 // static, static inline, always_inline, and extern inline functions can
6660 // always be deferred. Normal inline functions can be deferred in C99/C++.
6661 // Implicit template instantiations can also be deferred in C++.
6662 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
Anton Yartsev79de4d42012-02-02 06:06:34 +00006663 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006664 return false;
6665 return true;
6666 }
Douglas Gregor87d81242011-09-10 00:22:34 +00006667
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006668 const VarDecl *VD = cast<VarDecl>(D);
6669 assert(VD->isFileVarDecl() && "Expected file scoped var");
6670
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00006671 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6672 return false;
6673
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006674 // Structs that have non-trivial constructors or destructors are required.
6675
6676 // FIXME: Handle references.
Alexis Huntf479f1b2011-05-09 18:22:59 +00006677 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006678 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6679 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Alexis Huntf479f1b2011-05-09 18:22:59 +00006680 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6681 RD->hasTrivialCopyConstructor() &&
6682 RD->hasTrivialMoveConstructor() &&
6683 RD->hasTrivialDestructor()))
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00006684 return true;
6685 }
6686 }
6687
6688 GVALinkage L = GetGVALinkageForVariable(VD);
6689 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6690 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6691 return false;
6692 }
6693
6694 return true;
6695}
Charles Davis53c59df2010-08-16 03:33:14 +00006696
Charles Davis99202b32010-11-09 18:04:24 +00006697CallingConv ASTContext::getDefaultMethodCallConv() {
6698 // Pass through to the C++ ABI object
6699 return ABI->getDefaultMethodCallConv();
6700}
6701
Jay Foad39c79802011-01-12 09:06:06 +00006702bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00006703 // Pass through to the C++ ABI object
6704 return ABI->isNearlyEmpty(RD);
6705}
6706
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006707MangleContext *ASTContext::createMangleContext() {
Douglas Gregore8bbc122011-09-02 00:18:52 +00006708 switch (Target->getCXXABI()) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006709 case CXXABI_ARM:
6710 case CXXABI_Itanium:
6711 return createItaniumMangleContext(*this, getDiagnostics());
6712 case CXXABI_Microsoft:
6713 return createMicrosoftMangleContext(*this, getDiagnostics());
6714 }
David Blaikie83d382b2011-09-23 05:06:16 +00006715 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00006716}
6717
Charles Davis53c59df2010-08-16 03:33:14 +00006718CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006719
6720size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek7d39c9a2011-07-27 18:41:12 +00006721 return ASTRecordLayouts.getMemorySize()
6722 + llvm::capacity_in_bytes(ObjCLayouts)
6723 + llvm::capacity_in_bytes(KeyFunctions)
6724 + llvm::capacity_in_bytes(ObjCImpls)
6725 + llvm::capacity_in_bytes(BlockVarCopyInits)
6726 + llvm::capacity_in_bytes(DeclAttrs)
6727 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6728 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6729 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6730 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6731 + llvm::capacity_in_bytes(OverriddenMethods)
6732 + llvm::capacity_in_bytes(Types)
Francois Pichet00c7e6c2011-08-14 03:52:19 +00006733 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet57928252011-08-14 14:28:49 +00006734 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00006735}
Ted Kremenek540017e2011-10-06 05:00:56 +00006736
Douglas Gregor63798542012-02-20 19:44:39 +00006737unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
6738 CXXRecordDecl *Lambda = CallOperator->getParent();
6739 return LambdaMangleContexts[Lambda->getDeclContext()]
6740 .getManglingNumber(CallOperator);
6741}
6742
6743
Ted Kremenek540017e2011-10-06 05:00:56 +00006744void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6745 ParamIndices[D] = index;
6746}
6747
6748unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6749 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6750 assert(I != ParamIndices.end() &&
6751 "ParmIndices lacks entry set by ParmVarDecl");
6752 return I->second;
6753}